From dfd0bb22a1bb0d2a568f9b47886e92026dc5a120 Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts
Date: Fri, 19 Oct 2018 12:17:28 -0400
Subject: [PATCH 01/62] DB scripts
---
db/databaseSetAdmin.go | 28 +++++++++++++++++++++++
db/databseCreateV2.go | 32 ++++++++++++++++++++++++++
db/userTestV2.go | 52 ++++++++++++++++++++++++++++++++++++++++++
3 files changed, 112 insertions(+)
create mode 100644 db/databaseSetAdmin.go
create mode 100644 db/databseCreateV2.go
create mode 100644 db/userTestV2.go
diff --git a/db/databaseSetAdmin.go b/db/databaseSetAdmin.go
new file mode 100644
index 0000000..486bbd2
--- /dev/null
+++ b/db/databaseSetAdmin.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "database/sql"
+ //"fmt"
+ _ "github.com/go-sql-driver/mysql"
+)
+
+func main() {
+ set("homeworkHubUser")
+}
+
+func set(name string) {
+ db, err := sql.Open("mysql", "root:password@/")
+ if err != nil {
+ panic(err)
+ }
+ defer db.Close()
+
+ _, err = db.Exec("USE " + name)
+ if err != nil {
+ panic(err)
+ }
+ _, err = db.Exec("ALTER TABLE userInfo ALTER isAdmin SET DEFAULT false;")
+ if err != nil {
+ panic(err)
+ }
+}
diff --git a/db/databseCreateV2.go b/db/databseCreateV2.go
new file mode 100644
index 0000000..595f9fa
--- /dev/null
+++ b/db/databseCreateV2.go
@@ -0,0 +1,32 @@
+package main
+
+import (
+ "database/sql"
+ //"fmt"
+ _ "github.com/go-sql-driver/mysql"
+)
+
+func main() {
+ create("homeworkHubUser")
+}
+
+func create(name string) {
+ db, err := sql.Open("mysql", "root:password@/")
+ if err != nil {
+ panic(err)
+ }
+ defer db.Close()
+
+ _, err = db.Exec("CREATE DATABASE " + name)
+ if err != nil {
+ panic(err)
+ }
+ _, err = db.Exec("USE " + name)
+ if err != nil {
+ panic(err)
+ }
+ _, err = db.Exec("CREATE TABLE userInfo(user_id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, email VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, isAdmin BOOLEAN, passwordHash BINARY(60) NOT NULL);")
+ if err != nil {
+ panic(err)
+ }
+}
diff --git a/db/userTestV2.go b/db/userTestV2.go
new file mode 100644
index 0000000..d25750a
--- /dev/null
+++ b/db/userTestV2.go
@@ -0,0 +1,52 @@
+package main
+
+import (
+ "bufio"
+ "database/sql"
+ "fmt"
+ _ "github.com/go-sql-driver/mysql"
+ "golang.org/x/crypto/bcrypt"
+ "log"
+ "os"
+ "strings"
+)
+
+func main() {
+ userMake("homeworkHubUser")
+}
+
+func userMake(name string) {
+
+ reader := bufio.NewReader(os.Stdin)
+ // var username string
+ fmt.Println("Enter Username: ")
+ username, _ := reader.ReadString('\n')
+ username = strings.Replace(username, "\n", "", -1)
+ // var email string
+ fmt.Println("Enter Email: ")
+ email, _ := reader.ReadString('\n')
+ email = strings.Replace(email, "\n", "", -1)
+
+ // var passwordhash string
+ fmt.Println("Enter Password: ")
+ password, _ := reader.ReadString('\n')
+ password = strings.Replace(password, "\n", "", -1)
+ hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
+ if err != nil {
+ log.Fatal(err)
+ }
+ db, err := sql.Open("mysql", "root:password@/")
+ if err != nil {
+ panic(err)
+ }
+ defer db.Close()
+
+ _, err = db.Exec("USE " + name)
+ if err != nil {
+ panic(err)
+ }
+ _, err = db.Exec(fmt.Sprintf("INSERT INTO userInfo (email,username,passwordHash) VALUES('%s', '%s', '%s');", email, username, hash))
+ if err != nil {
+ panic(err)
+ }
+}
From 584fdecbddbaa323911f8b79221c2c5c29d5e6d2 Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Tue, 27 Nov 2018 14:55:21 -0500
Subject: [PATCH 02/62] Trimmed down the homework struct
---
main.go | 6 ------
1 file changed, 6 deletions(-)
diff --git a/main.go b/main.go
index 6778251..837bffb 100644
--- a/main.go
+++ b/main.go
@@ -25,8 +25,6 @@ func main() {
Id: 123,
Title: "[CS][370][Confer] First Homework",
PostImage: "image1.jpeg",
- Upvotes: 1,
- Downvotes: 99,
Comments: []string{"This post is great!", "No, it really isn't"},
Tags: []string{"2018", "MAT", "413", "Andriamanalimanana"},
},
@@ -50,8 +48,6 @@ func main() {
Id: 123,
Title: "[CS][370][Confer] First Homework",
PostImage: "image1.jpeg",
- Upvotes: 1,
- Downvotes: 99,
Comments: []string{"This post is great!", "No, it really isn't"},
Tags: []string{"2018", "MAT", "413", "Andriamanalimanana"},
}
@@ -75,8 +71,6 @@ type homework struct {
Id uint
Title string
PostImage string
- Upvotes uint
- Downvotes uint
Comments []string
Tags []string
}
From ccdb2e6b98be7f0f41c6dc84ed0c75471dcbebee Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts
Date: Tue, 27 Nov 2018 15:06:37 -0500
Subject: [PATCH 03/62] Drop Old Files, Add New Go DB Files for SQLite
---
db/comment_section.go | 13 +++++++++++
db/databaseSetAdmin.go | 28 ----------------------
db/databseCreate.go | 32 -------------------------
db/databseCreateV2.go | 32 -------------------------
db/homeworkHub.db | Bin 0 -> 24576 bytes
db/post_info.go | 13 +++++++++++
db/post_tags.go | 13 +++++++++++
db/userTest.go | 48 -------------------------------------
db/userTestV2.go | 52 -----------------------------------------
db/user_info.go | 13 +++++++++++
10 files changed, 52 insertions(+), 192 deletions(-)
create mode 100644 db/comment_section.go
delete mode 100644 db/databaseSetAdmin.go
delete mode 100644 db/databseCreate.go
delete mode 100644 db/databseCreateV2.go
create mode 100644 db/homeworkHub.db
create mode 100644 db/post_info.go
create mode 100644 db/post_tags.go
delete mode 100644 db/userTest.go
delete mode 100644 db/userTestV2.go
create mode 100644 db/user_info.go
diff --git a/db/comment_section.go b/db/comment_section.go
new file mode 100644
index 0000000..7b5e5bd
--- /dev/null
+++ b/db/comment_section.go
@@ -0,0 +1,13 @@
+package main
+
+import (
+ "database/sql"
+
+ _ "github.com/mattn/go-sqlite3"
+)
+
+func main() {
+ database, _ := sql.Open("sqlite3", "./homeworkHub.db")
+ statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS comment_section (post_id INTEGER, username TEXT, comment TEXT)")
+ statement.Exec()
+}
diff --git a/db/databaseSetAdmin.go b/db/databaseSetAdmin.go
deleted file mode 100644
index 486bbd2..0000000
--- a/db/databaseSetAdmin.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package main
-
-import (
- "database/sql"
- //"fmt"
- _ "github.com/go-sql-driver/mysql"
-)
-
-func main() {
- set("homeworkHubUser")
-}
-
-func set(name string) {
- db, err := sql.Open("mysql", "root:password@/")
- if err != nil {
- panic(err)
- }
- defer db.Close()
-
- _, err = db.Exec("USE " + name)
- if err != nil {
- panic(err)
- }
- _, err = db.Exec("ALTER TABLE userInfo ALTER isAdmin SET DEFAULT false;")
- if err != nil {
- panic(err)
- }
-}
diff --git a/db/databseCreate.go b/db/databseCreate.go
deleted file mode 100644
index 6fe5424..0000000
--- a/db/databseCreate.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package main
-
-import (
- "database/sql"
- //"fmt"
- _ "github.com/go-sql-driver/mysql"
-)
-
-func main() {
- create("homeworkHub")
-}
-
-func create(name string) {
- db, err := sql.Open("mysql", "root:password@/")
- if err != nil {
- panic(err)
- }
- defer db.Close()
-
- _, err = db.Exec("CREATE DATABASE " + name)
- if err != nil {
- panic(err)
- }
- _, err = db.Exec("USE " + name)
- if err != nil {
- panic(err)
- }
- _, err = db.Exec("CREATE TABLE userInfo(user_id integer NOT NULL AUTO_INCREMENT PRIMARY KEY, email varchar(32) NOT NULL, username varchar(32) NOT NULL, isAdmin varchar(6), passwordHash varchar(32) NOT NULL )")
- if err != nil {
- panic(err)
- }
-}
diff --git a/db/databseCreateV2.go b/db/databseCreateV2.go
deleted file mode 100644
index 595f9fa..0000000
--- a/db/databseCreateV2.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package main
-
-import (
- "database/sql"
- //"fmt"
- _ "github.com/go-sql-driver/mysql"
-)
-
-func main() {
- create("homeworkHubUser")
-}
-
-func create(name string) {
- db, err := sql.Open("mysql", "root:password@/")
- if err != nil {
- panic(err)
- }
- defer db.Close()
-
- _, err = db.Exec("CREATE DATABASE " + name)
- if err != nil {
- panic(err)
- }
- _, err = db.Exec("USE " + name)
- if err != nil {
- panic(err)
- }
- _, err = db.Exec("CREATE TABLE userInfo(user_id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, email VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, isAdmin BOOLEAN, passwordHash BINARY(60) NOT NULL);")
- if err != nil {
- panic(err)
- }
-}
diff --git a/db/homeworkHub.db b/db/homeworkHub.db
new file mode 100644
index 0000000000000000000000000000000000000000..5eefb5d366c32afa58691e0151471b3aa5253e38
GIT binary patch
literal 24576
zcmeI#O;5rw7{KvO-Y&jf3@1YqFBl0I51++1G-N{T@=8Tm>aTHBUwTgO6JmX+7FsB2nG-_*3&Y2%k?
z-l|uhHuMLDjZbUqed}oRW3#TC6a)}J009ILKmY**5I_Kd{}XTu#q!RM{h<8&p;Z1u
zY-;he?K++-Jm=)X6=pdlo_prDYi3w@?wz+kUC)=wm5M!07D+w~2hn$<
zu&~_s@XDIvs@-Th?T$EiJHom3E*mX9v+1_Hns|xjB=kpe7E%Wf)G%!if}!k=ef5}Z
z=QUR<9~{`zz1fj^(P$(?)s1CO1yQ)v%`fb1>E+7)R(3I;ki@-OE1I~SS=jh_s559C
z_4!4HJ-O7)EreZqSvAM3>6!a)cB#C(Yfqiol18ARS<~m*!XoLYsQ%p1A3Vo?9KS`A
zesUC(o9m>Xf&c;tAb
Date: Tue, 4 Dec 2018 14:06:23 -0500
Subject: [PATCH 04/62] Delete homeworkHub.db
Deleting .DB file
---
db/homeworkHub.db | Bin 24576 -> 0 bytes
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 db/homeworkHub.db
diff --git a/db/homeworkHub.db b/db/homeworkHub.db
deleted file mode 100644
index 5eefb5d366c32afa58691e0151471b3aa5253e38..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 24576
zcmeI#O;5rw7{KvO-Y&jf3@1YqFBl0I51++1G-N{T@=8Tm>aTHBUwTgO6JmX+7FsB2nG-_*3&Y2%k?
z-l|uhHuMLDjZbUqed}oRW3#TC6a)}J009ILKmY**5I_Kd{}XTu#q!RM{h<8&p;Z1u
zY-;he?K++-Jm=)X6=pdlo_prDYi3w@?wz+kUC)=wm5M!07D+w~2hn$<
zu&~_s@XDIvs@-Th?T$EiJHom3E*mX9v+1_Hns|xjB=kpe7E%Wf)G%!if}!k=ef5}Z
z=QUR<9~{`zz1fj^(P$(?)s1CO1yQ)v%`fb1>E+7)R(3I;ki@-OE1I~SS=jh_s559C
z_4!4HJ-O7)EreZqSvAM3>6!a)cB#C(Yfqiol18ARS<~m*!XoLYsQ%p1A3Vo?9KS`A
zesUC(o9m>Xf&c;tAb
Date: Tue, 4 Dec 2018 14:07:03 -0500
Subject: [PATCH 05/62] Delete homeworkHub.db
delete .db file
---
db/homeworkHub.db | Bin 24576 -> 0 bytes
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 db/homeworkHub.db
diff --git a/db/homeworkHub.db b/db/homeworkHub.db
deleted file mode 100644
index 5eefb5d366c32afa58691e0151471b3aa5253e38..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 24576
zcmeI#O;5rw7{KvO-Y&jf3@1YqFBl0I51++1G-N{T@=8Tm>aTHBUwTgO6JmX+7FsB2nG-_*3&Y2%k?
z-l|uhHuMLDjZbUqed}oRW3#TC6a)}J009ILKmY**5I_Kd{}XTu#q!RM{h<8&p;Z1u
zY-;he?K++-Jm=)X6=pdlo_prDYi3w@?wz+kUC)=wm5M!07D+w~2hn$<
zu&~_s@XDIvs@-Th?T$EiJHom3E*mX9v+1_Hns|xjB=kpe7E%Wf)G%!if}!k=ef5}Z
z=QUR<9~{`zz1fj^(P$(?)s1CO1yQ)v%`fb1>E+7)R(3I;ki@-OE1I~SS=jh_s559C
z_4!4HJ-O7)EreZqSvAM3>6!a)cB#C(Yfqiol18ARS<~m*!XoLYsQ%p1A3Vo?9KS`A
zesUC(o9m>Xf&c;tAb
Date: Tue, 4 Dec 2018 14:08:22 -0500
Subject: [PATCH 06/62] Update .gitignore
add .db file
---
.gitignore | 3 +++
1 file changed, 3 insertions(+)
diff --git a/.gitignore b/.gitignore
index 10efe95..996f904 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,9 +10,12 @@
*.dll
*.so
*.dylib
+*.db
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
+
+
From 918456e3305e152f6907bede06fa06e9e2daaa01 Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts <43045671+NateMitts@users.noreply.github.com>
Date: Tue, 4 Dec 2018 14:10:50 -0500
Subject: [PATCH 07/62] Update .gitignore
---
.gitignore | 1 +
1 file changed, 1 insertion(+)
diff --git a/.gitignore b/.gitignore
index 10efe95..89e6483 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,6 +10,7 @@
*.dll
*.so
*.dylib
+*.db
# Test binary, build with `go test -c`
*.test
From 392db662674907422ac15ef00d54e1cfb1dd172e Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Tue, 4 Dec 2018 14:11:02 -0500
Subject: [PATCH 08/62] Added design artifacts from our Google Drive file, and
updated README to reflect recent design changes.
---
README.md | 14 +-------------
design_artifacts/account-creation.md | 16 ++++++++++++++++
design_artifacts/database_communication.md | 13 +++++++++++++
design_artifacts/database_design.md | 20 ++++++++++++++++++++
design_artifacts/feedback_mechanism.md | 5 +++++
design_artifacts/file_uploading.md | 13 +++++++++++++
design_artifacts/post_searching.md | 9 +++++++++
7 files changed, 77 insertions(+), 13 deletions(-)
create mode 100644 design_artifacts/account-creation.md
create mode 100644 design_artifacts/database_communication.md
create mode 100644 design_artifacts/database_design.md
create mode 100644 design_artifacts/feedback_mechanism.md
create mode 100644 design_artifacts/file_uploading.md
create mode 100644 design_artifacts/post_searching.md
diff --git a/README.md b/README.md
index 0d4da1c..13c15dd 100644
--- a/README.md
+++ b/README.md
@@ -13,22 +13,10 @@ Download the source using the command:
git clone https://github.com/SocialHW/HomeworkHub.git
```
-Installing the required dependencies to run (such as MySQL):
-
-```bash
-cd HomeworkHub/
-sh init/init.sh
-```
+Running this project no longer requires any external dependencies to be running, such as MySQL.
## Building and Running
-The project depends on the existence of a local instance of MySQL running. To start MySQL after it is installed,
-run the command:
-
-```bash
-sh init/start_db.sh
-```
-
To run the project as a Go script, simply run this command from the root directory of the project:
```bash
diff --git a/design_artifacts/account-creation.md b/design_artifacts/account-creation.md
new file mode 100644
index 0000000..4eb33e5
--- /dev/null
+++ b/design_artifacts/account-creation.md
@@ -0,0 +1,16 @@
+###Account Creation
+
+Users will be able to create an account by clicking a link in the top right corner of
+the home page with the text "Register". The link will direct the user to /register where
+they can provide a username, and a password. They submit the request to create an
+account by pressing a button labeled "Create Account". If the username is not taken, they
+will be redirected to the index page. From there they can continue to login by clicking
+a link in the top right corner with the text "Login". From there they can enter the
+username and password they provided before. They will be redirected to the index page,
+where they will now be logged in.
+
+When the user clicks on the Create Account button, they will be submitting an HTTP POST
+request, to /register/details with the information they provided. There will be a
+handler function listening on /register/details which will query the user info table
+to find an account with a matching username. If there is no account with a matching
+username, the account can be created by inserting a new row into the database.
\ No newline at end of file
diff --git a/design_artifacts/database_communication.md b/design_artifacts/database_communication.md
new file mode 100644
index 0000000..2e5b5c3
--- /dev/null
+++ b/design_artifacts/database_communication.md
@@ -0,0 +1,13 @@
+###Database Communication
+
+We should have a file at the db directory of the project that contains all of the functions needed to interact with the
+database.
+* There should be a RegisterUser function that will take the email and password as strings, and executes the queries to
+insert the user into the database if it is a valid registration.
+* There should be a LoginUser function that will take a username and password as strings, query the database to for the
+password associated with the username entered. If the username exists and the password entered is equal to the password
+in the database, the user is redirected to the home page.
+* There should be a GetPosts function that takes a predicate function (of Post -> Boolean) and returns []Post,
+containing the Posts in the database that meet the predicate. Future implementations may use a comparator function to
+rank the results, such as closest search result match.
+* There should be a CreatePost function, that takes a Post struct and inserts all of its fields into.
diff --git a/design_artifacts/database_design.md b/design_artifacts/database_design.md
new file mode 100644
index 0000000..d1ed2d2
--- /dev/null
+++ b/design_artifacts/database_design.md
@@ -0,0 +1,20 @@
+###Database Structure
+
+SQLite uses a .db file to represent the database. We should have some .db file located in the db directory. This file
+will contain all of the tables we use to store information related to the site.
+___
+
+There should be a Posts table with the following columns:
+
+post_id primary key, auto inc INTEGER | username TEXT | title TEXT | file_path TEXT
+___
+
+There should be a Comments table with the following columns:
+
+post_id INTEGER | username TEXT | comment TEXT
+___
+
+There should be a user info table with the following columns:
+
+ID primary key, auto inc INTEGER | Username TEXT | password TEXT
+___
\ No newline at end of file
diff --git a/design_artifacts/feedback_mechanism.md b/design_artifacts/feedback_mechanism.md
new file mode 100644
index 0000000..3ea5279
--- /dev/null
+++ b/design_artifacts/feedback_mechanism.md
@@ -0,0 +1,5 @@
+###Feedback Mechanism
+
+We were planning on creating some sort of rating system in order to show users more
+relevant and higher quality results. We have since abandoned this idea for the sake of
+time.
\ No newline at end of file
diff --git a/design_artifacts/file_uploading.md b/design_artifacts/file_uploading.md
new file mode 100644
index 0000000..b6ca091
--- /dev/null
+++ b/design_artifacts/file_uploading.md
@@ -0,0 +1,13 @@
+###File Uploading
+
+Uploading images to the site represent the core value of the project. Users will have the ability to upload jpg/jpeg,
+png, gif, and pdf files to be stored on the site. There will be a maximum upload size of 8MB in order to restrict users
+from overusing the resources of the web server. Each file will be associated with a post, which is a row in the Posts
+table containing information such as the user who created the post, the title, and the extension of the file. The file
+will be saved in the location "posts/.". Since each post will have a unique ID, this will prevent
+collisions when storing files on the disk.
+
+In order to create a new post, a user must be logged in and will click a link in the top right corner of the web page.
+The user will be redirected to /create-post, where they will be prompted for the information required for a new post.
+
+It should not be allowed to use punctuation such as ;, in order to avoid SQL injection.
\ No newline at end of file
diff --git a/design_artifacts/post_searching.md b/design_artifacts/post_searching.md
new file mode 100644
index 0000000..5c69971
--- /dev/null
+++ b/design_artifacts/post_searching.md
@@ -0,0 +1,9 @@
+###Post Searching
+
+In order to aid users in navigating the site, we will provide a searching feature. There
+will be a text box located in the header of the page, where users (who do not need to be
+logged in) can enter a string of text and hit enter to see the results. The search will
+return results that include any of the words in the query in the title, and present
+them in a vertical listing.
+
+It should not be allowed to use punctuation such as ;, in order to avoid SQL injection.
\ No newline at end of file
From 8f646f48b064dac8a3e35a4cfdfa4229270315ed Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts <43045671+NateMitts@users.noreply.github.com>
Date: Tue, 4 Dec 2018 14:11:41 -0500
Subject: [PATCH 09/62] Delete post_tags.go
dropping post tags
---
db/post_tags.go | 13 -------------
1 file changed, 13 deletions(-)
delete mode 100644 db/post_tags.go
diff --git a/db/post_tags.go b/db/post_tags.go
deleted file mode 100644
index 9f134b7..0000000
--- a/db/post_tags.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package main
-
-import (
- "database/sql"
-
- _ "github.com/mattn/go-sqlite3"
-)
-
-func main() {
- database, _ := sql.Open("sqlite3", "./homeworkHub.db")
- statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS tags (post_id INTEGER, tag TEXT)")
- statement.Exec()
-}
From 5403354524bac9d4e16fcfa90c19e391fe4f6a41 Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts <43045671+NateMitts@users.noreply.github.com>
Date: Tue, 4 Dec 2018 14:15:22 -0500
Subject: [PATCH 10/62] Delete databaseSetAdmin.go
dropping older files
---
db/databaseSetAdmin.go | 28 ----------------------------
1 file changed, 28 deletions(-)
delete mode 100644 db/databaseSetAdmin.go
diff --git a/db/databaseSetAdmin.go b/db/databaseSetAdmin.go
deleted file mode 100644
index 486bbd2..0000000
--- a/db/databaseSetAdmin.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package main
-
-import (
- "database/sql"
- //"fmt"
- _ "github.com/go-sql-driver/mysql"
-)
-
-func main() {
- set("homeworkHubUser")
-}
-
-func set(name string) {
- db, err := sql.Open("mysql", "root:password@/")
- if err != nil {
- panic(err)
- }
- defer db.Close()
-
- _, err = db.Exec("USE " + name)
- if err != nil {
- panic(err)
- }
- _, err = db.Exec("ALTER TABLE userInfo ALTER isAdmin SET DEFAULT false;")
- if err != nil {
- panic(err)
- }
-}
From e68feded7ac1622aa027f6097012512b1058c6de Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts <43045671+NateMitts@users.noreply.github.com>
Date: Tue, 4 Dec 2018 14:15:39 -0500
Subject: [PATCH 11/62] Delete databseCreateV2.go
dropping older tables
---
db/databseCreateV2.go | 32 --------------------------------
1 file changed, 32 deletions(-)
delete mode 100644 db/databseCreateV2.go
diff --git a/db/databseCreateV2.go b/db/databseCreateV2.go
deleted file mode 100644
index 595f9fa..0000000
--- a/db/databseCreateV2.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package main
-
-import (
- "database/sql"
- //"fmt"
- _ "github.com/go-sql-driver/mysql"
-)
-
-func main() {
- create("homeworkHubUser")
-}
-
-func create(name string) {
- db, err := sql.Open("mysql", "root:password@/")
- if err != nil {
- panic(err)
- }
- defer db.Close()
-
- _, err = db.Exec("CREATE DATABASE " + name)
- if err != nil {
- panic(err)
- }
- _, err = db.Exec("USE " + name)
- if err != nil {
- panic(err)
- }
- _, err = db.Exec("CREATE TABLE userInfo(user_id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, email VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, isAdmin BOOLEAN, passwordHash BINARY(60) NOT NULL);")
- if err != nil {
- panic(err)
- }
-}
From 043b0e6e4319bbe8616a544465d2e847ad052ba6 Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts <43045671+NateMitts@users.noreply.github.com>
Date: Tue, 4 Dec 2018 14:16:00 -0500
Subject: [PATCH 12/62] Delete userTestV2.go
dropping old files
---
db/userTestV2.go | 52 ------------------------------------------------
1 file changed, 52 deletions(-)
delete mode 100644 db/userTestV2.go
diff --git a/db/userTestV2.go b/db/userTestV2.go
deleted file mode 100644
index d25750a..0000000
--- a/db/userTestV2.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package main
-
-import (
- "bufio"
- "database/sql"
- "fmt"
- _ "github.com/go-sql-driver/mysql"
- "golang.org/x/crypto/bcrypt"
- "log"
- "os"
- "strings"
-)
-
-func main() {
- userMake("homeworkHubUser")
-}
-
-func userMake(name string) {
-
- reader := bufio.NewReader(os.Stdin)
- // var username string
- fmt.Println("Enter Username: ")
- username, _ := reader.ReadString('\n')
- username = strings.Replace(username, "\n", "", -1)
- // var email string
- fmt.Println("Enter Email: ")
- email, _ := reader.ReadString('\n')
- email = strings.Replace(email, "\n", "", -1)
-
- // var passwordhash string
- fmt.Println("Enter Password: ")
- password, _ := reader.ReadString('\n')
- password = strings.Replace(password, "\n", "", -1)
- hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
- if err != nil {
- log.Fatal(err)
- }
- db, err := sql.Open("mysql", "root:password@/")
- if err != nil {
- panic(err)
- }
- defer db.Close()
-
- _, err = db.Exec("USE " + name)
- if err != nil {
- panic(err)
- }
- _, err = db.Exec(fmt.Sprintf("INSERT INTO userInfo (email,username,passwordHash) VALUES('%s', '%s', '%s');", email, username, hash))
- if err != nil {
- panic(err)
- }
-}
From b9b9682aaead92738b437409639104601ef7c9cc Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts <43045671+NateMitts@users.noreply.github.com>
Date: Tue, 4 Dec 2018 14:20:27 -0500
Subject: [PATCH 13/62] Delete post_tags.go
deleted post tags
---
db/post_tags.go | 13 -------------
1 file changed, 13 deletions(-)
delete mode 100644 db/post_tags.go
diff --git a/db/post_tags.go b/db/post_tags.go
deleted file mode 100644
index 9f134b7..0000000
--- a/db/post_tags.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package main
-
-import (
- "database/sql"
-
- _ "github.com/mattn/go-sqlite3"
-)
-
-func main() {
- database, _ := sql.Open("sqlite3", "./homeworkHub.db")
- statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS tags (post_id INTEGER, tag TEXT)")
- statement.Exec()
-}
From eb5016ae3e186be9d2bf3da9bc9f58e42acfa2a6 Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Tue, 4 Dec 2018 14:40:21 -0500
Subject: [PATCH 14/62] Trimmed down Homework struct
---
main.go | 3 ---
1 file changed, 3 deletions(-)
diff --git a/main.go b/main.go
index 837bffb..1f005c3 100644
--- a/main.go
+++ b/main.go
@@ -26,7 +26,6 @@ func main() {
Title: "[CS][370][Confer] First Homework",
PostImage: "image1.jpeg",
Comments: []string{"This post is great!", "No, it really isn't"},
- Tags: []string{"2018", "MAT", "413", "Andriamanalimanana"},
},
},
})
@@ -49,7 +48,6 @@ func main() {
Title: "[CS][370][Confer] First Homework",
PostImage: "image1.jpeg",
Comments: []string{"This post is great!", "No, it really isn't"},
- Tags: []string{"2018", "MAT", "413", "Andriamanalimanana"},
}
err := tpl.ExecuteTemplate(w, "homework.gohtml", hw)
@@ -72,5 +70,4 @@ type homework struct {
Title string
PostImage string
Comments []string
- Tags []string
}
From dafd3bad5ce4bc5efe6584da7db65bdf844b9c21 Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Tue, 4 Dec 2018 14:55:27 -0500
Subject: [PATCH 15/62] Removed unsed init scripts
---
init/databaseCreate.go | 32 --------------------------------
init/init.sh | 33 ---------------------------------
init/start_db.sh | 4 ----
init/uninit.sh | 7 -------
4 files changed, 76 deletions(-)
delete mode 100644 init/databaseCreate.go
delete mode 100644 init/init.sh
delete mode 100644 init/start_db.sh
delete mode 100644 init/uninit.sh
diff --git a/init/databaseCreate.go b/init/databaseCreate.go
deleted file mode 100644
index 6fe5424..0000000
--- a/init/databaseCreate.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package main
-
-import (
- "database/sql"
- //"fmt"
- _ "github.com/go-sql-driver/mysql"
-)
-
-func main() {
- create("homeworkHub")
-}
-
-func create(name string) {
- db, err := sql.Open("mysql", "root:password@/")
- if err != nil {
- panic(err)
- }
- defer db.Close()
-
- _, err = db.Exec("CREATE DATABASE " + name)
- if err != nil {
- panic(err)
- }
- _, err = db.Exec("USE " + name)
- if err != nil {
- panic(err)
- }
- _, err = db.Exec("CREATE TABLE userInfo(user_id integer NOT NULL AUTO_INCREMENT PRIMARY KEY, email varchar(32) NOT NULL, username varchar(32) NOT NULL, isAdmin varchar(6), passwordHash varchar(32) NOT NULL )")
- if err != nil {
- panic(err)
- }
-}
diff --git a/init/init.sh b/init/init.sh
deleted file mode 100644
index 55ebdef..0000000
--- a/init/init.sh
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/bin/sh
-
-
-is_installed() {
- search="$(apt-cache pkgnames | grep -i $1)"
-
- if [ -z "${search}" ]; then
- return 1
- fi
-
- return 0
-}
-
-
-# Install mysql-server
-get_mysql() {
- p="mysql-server"
-
- if [ ! $(is_installed $p) ]; then
- # is not installed
- echo "$p is not installed"
-
- echo "Installing... "
- sudo apt update
- sudo apt install mysql-server -y
-
- fi
-
- echo "Installed: "
- apt-cache pkgnames | grep -i $p
-}
-
-get_mysql
diff --git a/init/start_db.sh b/init/start_db.sh
deleted file mode 100644
index f55f9a8..0000000
--- a/init/start_db.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-
-systemctl start mysql
-
diff --git a/init/uninit.sh b/init/uninit.sh
deleted file mode 100644
index 55fc0df..0000000
--- a/init/uninit.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/bin/sh
-
-systemctl stop mysql
-
-sudo apt remove mysql-server
-
-sudo apt autoremove
From 4b2c09b46e849e2cec13515846b69b468b631d33 Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts
Date: Wed, 5 Dec 2018 17:21:40 -0500
Subject: [PATCH 16/62] Add db function to main
---
main.go | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/main.go b/main.go
index 7afdba0..d94a130 100644
--- a/main.go
+++ b/main.go
@@ -5,9 +5,20 @@ import (
"net/http"
)
+var database *sql.DB
+
func main() {
http.Handle("/", http.FileServer(http.Dir("static/")))
log.Println("Server running...")
http.ListenAndServe(":3000", nil)
}
+func initialize_DB() {
+ database, _ = sql.Open("sqlite3", "./homeworkHub.db")
+ statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS userInfo (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)")
+ statement.Exec()
+ statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS post_info (post_id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, title TEXT, file_path TEXT)")
+ statement.Exec()
+ statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS comment_section (post_id INTEGER, username TEXT, comment TEXT)")
+ statement.Exec()
+}
From 75c43522bda6bd7b90a1770b6c2a364180598762 Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts
Date: Wed, 5 Dec 2018 17:27:31 -0500
Subject: [PATCH 17/62] added imports to main
---
main.go | 2 ++
1 file changed, 2 insertions(+)
diff --git a/main.go b/main.go
index d94a130..c193f20 100644
--- a/main.go
+++ b/main.go
@@ -1,6 +1,8 @@
package main
import (
+ "database/sql"
+ _ "github.com/mattn/go-sqlite3"
"log"
"net/http"
)
From a19d9343be6e767075d5f6288f83df4359ad1844 Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Wed, 5 Dec 2018 17:28:53 -0500
Subject: [PATCH 18/62] Created handler and models files based on Github
example
---
handlers.go | 175 ++++++++++++++++++++++++++++++++++++++++++++++++++++
main.go | 24 +++----
models.go | 15 +++++
3 files changed, 203 insertions(+), 11 deletions(-)
create mode 100644 handlers.go
create mode 100644 models.go
diff --git a/handlers.go b/handlers.go
new file mode 100644
index 0000000..96080e9
--- /dev/null
+++ b/handlers.go
@@ -0,0 +1,175 @@
+package main
+
+import (
+ "database/sql"
+ "fmt"
+ "net/http"
+ "strconv"
+)
+
+func registerHandler(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "POST" {
+ http.ServeFile(w, r, "tmpl/register.html")
+ return
+ }
+ // grab user info
+ username := r.FormValue("username")
+ password := r.FormValue("password")
+ role := r.FormValue("role")
+ // Check existence of user
+ var user User
+ err := db.QueryRow("SELECT username, password, role FROM users WHERE username=?",
+ username).Scan(&user.Username, &user.Password, &user.Role)
+ switch {
+ // user is available
+ case err == sql.ErrNoRows:
+ hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
+ checkInternalServerError(err, w)
+ // insert to database
+ _, err = db.Exec(`INSERT INTO users(username, password, role) VALUES(?, ?, ?)`,
+ username, hashedPassword, role)
+ fmt.Println("Created user: ", username)
+ checkInternalServerError(err, w)
+ case err != nil:
+ http.Error(w, "loi: "+err.Error(), http.StatusBadRequest)
+ return
+ default:
+ http.Redirect(w, r, "/login", http.StatusMovedPermanently)
+ }
+}
+
+func loginHandler(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "POST" {
+ http.ServeFile(w, r, "tmpl/login.html")
+ return
+ }
+ // grab user info from the submitted form
+ username := r.FormValue("usrname")
+ password := r.FormValue("psw")
+ // query database to get match username
+ var user User
+ err := db.QueryRow("SELECT username, password FROM users WHERE username=?",
+ username).Scan(&user.Username, &user.Password)
+ checkInternalServerError(err, w)
+ // validate password
+ err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
+ if err != nil {
+ http.Redirect(w, r, "/login", 301)
+ }
+ authenticated = true
+ http.Redirect(w, r, "/list", 301)
+
+}
+
+func logoutHandler(w http.ResponseWriter, r *http.Request) {
+ authenticated = false
+ isAuthenticated(w, r)
+}
+
+func listHandler(w http.ResponseWriter, r *http.Request) {
+ isAuthenticated(w, r)
+ if r.Method != "GET" {
+ http.Error(w, "Method not allowed", http.StatusBadRequest)
+ }
+ rows, err := db.Query("SELECT * FROM cost")
+ checkInternalServerError(err, w)
+ var funcMap = template.FuncMap{
+ "multiplication": func(n float64, f float64) float64 {
+ return n * f
+ },
+ "addOne": func(n int) int {
+ return n + 1
+ },
+ }
+ var costs []Cost
+ var cost Cost
+ for rows.Next() {
+ err = rows.Scan(&cost.Id, &cost.ElectricAmount,
+ &cost.ElectricPrice, &cost.WaterAmount, &cost.WaterPrice, &cost.CheckedDate)
+ checkInternalServerError(err, w)
+ costs = append(costs, cost)
+ }
+ t, err := template.New("list.html").Funcs(funcMap).ParseFiles("tmpl/list.html")
+ checkInternalServerError(err, w)
+ err = t.Execute(w, costs)
+ checkInternalServerError(err, w)
+
+}
+
+func createHandler(w http.ResponseWriter, r *http.Request) {
+ isAuthenticated(w, r)
+ if r.Method != "POST" {
+ http.Redirect(w, r, "/", 301)
+ }
+ var cost Cost
+ cost.ElectricAmount, _ = strconv.ParseInt(r.FormValue("ElectricAmount"), 10, 64)
+ cost.ElectricPrice, _ = strconv.ParseFloat(r.FormValue("ElectricPrice"), 64)
+ cost.WaterAmount, _ = strconv.ParseInt(r.FormValue("WaterAmount"), 10, 64)
+ cost.WaterPrice, _ = strconv.ParseFloat(r.FormValue("WaterPrice"), 64)
+ cost.CheckedDate = r.FormValue("CheckedDate")
+ fmt.Println(cost)
+
+ // Save to database
+ stmt, err := db.Prepare(`
+ INSERT INTO cost(electric_amount, electric_price, water_amount, water_price, checked_date)
+ VALUES(?, ?, ?, ?, ?)
+ `)
+ if err != nil {
+ fmt.Println("Prepare query error")
+ panic(err)
+ }
+ _, err = stmt.Exec(cost.ElectricAmount, cost.ElectricPrice,
+ cost.WaterAmount, cost.WaterPrice, cost.CheckedDate)
+ if err != nil {
+ fmt.Println("Execute query error")
+ panic(err)
+ }
+ http.Redirect(w, r, "/", 301)
+}
+
+func updateHandler(w http.ResponseWriter, r *http.Request) {
+ isAuthenticated(w, r)
+ if r.Method != "POST" {
+ http.Redirect(w, r, "/", 301)
+ }
+ var cost Cost
+ cost.Id, _ = strconv.ParseInt(r.FormValue("Id"), 10, 64)
+ cost.ElectricAmount, _ = strconv.ParseInt(r.FormValue("ElectricAmount"), 10, 64)
+ cost.ElectricPrice, _ = strconv.ParseFloat(r.FormValue("ElectricPrice"), 64)
+ cost.WaterAmount, _ = strconv.ParseInt(r.FormValue("WaterAmount"), 10, 64)
+ cost.WaterPrice, _ = strconv.ParseFloat(r.FormValue("WaterPrice"), 64)
+ cost.CheckedDate = r.FormValue("CheckedDate")
+ fmt.Println(cost)
+ stmt, err := db.Prepare(`
+ UPDATE cost SET electric_amount=?, electric_price=?, water_amount=?, water_price=?, checked_date=?
+ WHERE id=?
+ `)
+ checkInternalServerError(err, w)
+ res, err := stmt.Exec(cost.ElectricAmount, cost.ElectricPrice,
+ cost.WaterAmount, cost.WaterPrice, cost.CheckedDate, cost.Id)
+ checkInternalServerError(err, w)
+ _, err = res.RowsAffected()
+ checkInternalServerError(err, w)
+ http.Redirect(w, r, "/", 301)
+}
+
+func deleteHandler(w http.ResponseWriter, r *http.Request) {
+ isAuthenticated(w, r)
+ if r.Method != "POST" {
+ http.Redirect(w, r, "/", 301)
+ }
+ var costId, _ = strconv.ParseInt(r.FormValue("Id"), 10, 64)
+ stmt, err := db.Prepare("DELETE FROM cost WHERE id=?")
+ checkInternalServerError(err, w)
+ res, err := stmt.Exec(costId)
+ checkInternalServerError(err, w)
+ _, err = res.RowsAffected()
+ checkInternalServerError(err, w)
+ http.Redirect(w, r, "/", 301)
+
+}
+
+func indexHandler(w http.ResponseWriter, r *http.Request) {
+ isAuthenticated(w, r)
+ http.Redirect(w, r, "/list", 301)
+}
diff --git a/main.go b/main.go
index 1f005c3..1cb2b8f 100644
--- a/main.go
+++ b/main.go
@@ -10,7 +10,10 @@ import (
"net/http"
)
-var tpl *template.Template
+var (
+ tpl *template.Template
+ authenticated = false
+)
func init() {
tpl = template.Must(template.ParseGlob("templates/*.gohtml"))
@@ -19,8 +22,8 @@ func init() {
func main() {
/* Route for index page */
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
- err := tpl.ExecuteTemplate(w, "index.gohtml", struct{ Posts []homework }{
- []homework{
+ err := tpl.ExecuteTemplate(w, "index.gohtml", struct{ Posts []Homework }{
+ []Homework{
{
Id: 123,
Title: "[CS][370][Confer] First Homework",
@@ -43,7 +46,7 @@ func main() {
/* Route for posts */
http.HandleFunc("/h/", func(w http.ResponseWriter, req *http.Request) {
- hw := homework{
+ hw := Homework{
Id: 123,
Title: "[CS][370][Confer] First Homework",
PostImage: "image1.jpeg",
@@ -59,15 +62,14 @@ func main() {
}
})
+ http.HandleFunc("/login", loginHandler)
+ http.HandleFunc("/logout", logoutHandler)
+ http.HandleFunc("/register", registerHandler)
+ http.HandleFunc("/list", listHandler)
+ http.HandleFunc("/create", createHandler)
+
port := ":3000"
log.Printf("Server running on port %s...\n", port)
http.ListenAndServe(port, nil)
}
-
-type homework struct {
- Id uint
- Title string
- PostImage string
- Comments []string
-}
diff --git a/models.go b/models.go
new file mode 100644
index 0000000..b9008ef
--- /dev/null
+++ b/models.go
@@ -0,0 +1,15 @@
+package main
+
+type Homework struct {
+ Id uint
+ Title string
+ PostImage string
+ Comments []string
+}
+
+type User struct {
+ Id int64 `json:"id"`
+ Username string `json:"username"`
+ Password string `json:"password"`
+ Role int64 `json:"role"`
+}
From 83741500f16bc4d25a09305df8454def5a589843 Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts
Date: Wed, 5 Dec 2018 17:33:17 -0500
Subject: [PATCH 19/62] changed statement names
---
main.go | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/main.go b/main.go
index c193f20..027d56e 100644
--- a/main.go
+++ b/main.go
@@ -17,10 +17,10 @@ func main() {
}
func initialize_DB() {
database, _ = sql.Open("sqlite3", "./homeworkHub.db")
- statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS userInfo (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)")
- statement.Exec()
- statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS post_info (post_id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, title TEXT, file_path TEXT)")
- statement.Exec()
- statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS comment_section (post_id INTEGER, username TEXT, comment TEXT)")
- statement.Exec()
+ statement1, _ := database.Prepare("CREATE TABLE IF NOT EXISTS userInfo (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)")
+ statement1.Exec()
+ statement2, _ := database.Prepare("CREATE TABLE IF NOT EXISTS post_info (post_id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, title TEXT, file_path TEXT)")
+ statement2.Exec()
+ statement3, _ := database.Prepare("CREATE TABLE IF NOT EXISTS comment_section (post_id INTEGER, username TEXT, comment TEXT)")
+ statement3.Exec()
}
From bc0fd8e6f9db5740b60ec0919e5a61e2b338f817 Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts
Date: Wed, 5 Dec 2018 17:35:50 -0500
Subject: [PATCH 20/62] add function caller
---
main.go | 1 +
1 file changed, 1 insertion(+)
diff --git a/main.go b/main.go
index 027d56e..d7c66f8 100644
--- a/main.go
+++ b/main.go
@@ -10,6 +10,7 @@ import (
var database *sql.DB
func main() {
+ intitalize_DB()
http.Handle("/", http.FileServer(http.Dir("static/")))
log.Println("Server running...")
From c9efd12bbadfef7c754710035965bf588753100e Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts
Date: Wed, 5 Dec 2018 17:37:20 -0500
Subject: [PATCH 21/62] fixed spelling errors
---
main.go | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/main.go b/main.go
index d7c66f8..2fc021b 100644
--- a/main.go
+++ b/main.go
@@ -10,7 +10,7 @@ import (
var database *sql.DB
func main() {
- intitalize_DB()
+ initialize_DB()
http.Handle("/", http.FileServer(http.Dir("static/")))
log.Println("Server running...")
From 402203312af9b7c28a4a1db1c2087adb2d6bab98 Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Wed, 5 Dec 2018 17:37:36 -0500
Subject: [PATCH 22/62] Added database variable
---
main.go | 2 ++
1 file changed, 2 insertions(+)
diff --git a/main.go b/main.go
index 1cb2b8f..a7bac88 100644
--- a/main.go
+++ b/main.go
@@ -5,6 +5,7 @@
package main
import (
+ "database/sql"
"html/template"
"log"
"net/http"
@@ -13,6 +14,7 @@ import (
var (
tpl *template.Template
authenticated = false
+ database *sql.DB
)
func init() {
From 58ea0be85ab1f114ce0dc7c89b90e414488c5eb6 Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Wed, 5 Dec 2018 19:49:56 -0500
Subject: [PATCH 23/62] Moved all handler functions to handlers go file.
Created handler function for post viewing page. Commented out related code
that is not exactly what is needed.
---
handlers.go | 217 ++++++++++++++++++++------------------
main.go | 51 ++-------
templates/homework.gohtml | 20 ----
3 files changed, 125 insertions(+), 163 deletions(-)
diff --git a/handlers.go b/handlers.go
index 96080e9..f8a8818 100644
--- a/handlers.go
+++ b/handlers.go
@@ -3,13 +3,13 @@ package main
import (
"database/sql"
"fmt"
+ "log"
"net/http"
- "strconv"
)
func registerHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
- http.ServeFile(w, r, "tmpl/register.html")
+ http.ServeFile(w, r, "templates/register.html")
return
}
// grab user info
@@ -18,16 +18,17 @@ func registerHandler(w http.ResponseWriter, r *http.Request) {
role := r.FormValue("role")
// Check existence of user
var user User
- err := db.QueryRow("SELECT username, password, role FROM users WHERE username=?",
+ err := database.QueryRow("SELECT username, password, role FROM users WHERE username=?",
username).Scan(&user.Username, &user.Password, &user.Role)
+
switch {
// user is available
case err == sql.ErrNoRows:
- hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
+ //hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
checkInternalServerError(err, w)
// insert to database
- _, err = db.Exec(`INSERT INTO users(username, password, role) VALUES(?, ?, ?)`,
- username, hashedPassword, role)
+ _, err = database.Exec(`INSERT INTO users(username, password, role) VALUES(?, ?, ?)`,
+ username, password, role)
fmt.Println("Created user: ", username)
checkInternalServerError(err, w)
case err != nil:
@@ -40,22 +41,22 @@ func registerHandler(w http.ResponseWriter, r *http.Request) {
func loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
- http.ServeFile(w, r, "tmpl/login.html")
+ http.ServeFile(w, r, "templates/login.html")
return
}
- // grab user info from the submitted form
- username := r.FormValue("usrname")
- password := r.FormValue("psw")
- // query database to get match username
- var user User
- err := db.QueryRow("SELECT username, password FROM users WHERE username=?",
- username).Scan(&user.Username, &user.Password)
- checkInternalServerError(err, w)
- // validate password
- err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
- if err != nil {
- http.Redirect(w, r, "/login", 301)
- }
+ //// grab user info from the submitted form
+ //username := r.FormValue("usrname")
+ //password := r.FormValue("psw")
+ //// query database to get match username
+ //var user User
+ //err := database.QueryRow("SELECT username, password FROM users WHERE username=?",
+ // username).Scan(&user.Username, &user.Password)
+ //checkInternalServerError(err, w)
+ //// validate password
+ //err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
+ //if err != nil {
+ // http.Redirect(w, r, "/login", 301)
+ //}
authenticated = true
http.Redirect(w, r, "/list", 301)
@@ -71,28 +72,28 @@ func listHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusBadRequest)
}
- rows, err := db.Query("SELECT * FROM cost")
- checkInternalServerError(err, w)
- var funcMap = template.FuncMap{
- "multiplication": func(n float64, f float64) float64 {
- return n * f
- },
- "addOne": func(n int) int {
- return n + 1
- },
- }
- var costs []Cost
- var cost Cost
- for rows.Next() {
- err = rows.Scan(&cost.Id, &cost.ElectricAmount,
- &cost.ElectricPrice, &cost.WaterAmount, &cost.WaterPrice, &cost.CheckedDate)
- checkInternalServerError(err, w)
- costs = append(costs, cost)
- }
- t, err := template.New("list.html").Funcs(funcMap).ParseFiles("tmpl/list.html")
- checkInternalServerError(err, w)
- err = t.Execute(w, costs)
- checkInternalServerError(err, w)
+ //rows, err := database.Query("SELECT * FROM homework")
+ //checkInternalServerError(err, w)
+ //var funcMap = tpl.FuncMap{
+ // "multiplication": func(n float64, f float64) float64 {
+ // return n * f
+ // },
+ // "addOne": func(n int) int {
+ // return n + 1
+ // },
+ //}
+ //var homeworks []Homework
+ //var homework Homework
+ //for rows.Next() {
+ // err = rows.Scan(&homework.Id, &homework.ElectricAmount,
+ // &homework.ElectricPrice, &homework.WaterAmount, &homework.WaterPrice, &homework.CheckedDate)
+ // checkInternalServerError(err, w)
+ // homeworks = append(homeworks, homework)
+ //}
+ //t, err := tpl.New("list.html").Funcs(funcMap).ParseFiles("templates/list.html")
+ //checkInternalServerError(err, w)
+ //err = t.Execute(w, homeworks)
+ //checkInternalServerError(err, w)
}
@@ -101,75 +102,89 @@ func createHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Redirect(w, r, "/", 301)
}
- var cost Cost
- cost.ElectricAmount, _ = strconv.ParseInt(r.FormValue("ElectricAmount"), 10, 64)
- cost.ElectricPrice, _ = strconv.ParseFloat(r.FormValue("ElectricPrice"), 64)
- cost.WaterAmount, _ = strconv.ParseInt(r.FormValue("WaterAmount"), 10, 64)
- cost.WaterPrice, _ = strconv.ParseFloat(r.FormValue("WaterPrice"), 64)
- cost.CheckedDate = r.FormValue("CheckedDate")
- fmt.Println(cost)
+ var homework Homework
+
+ fmt.Println(homework)
// Save to database
- stmt, err := db.Prepare(`
- INSERT INTO cost(electric_amount, electric_price, water_amount, water_price, checked_date)
- VALUES(?, ?, ?, ?, ?)
- `)
- if err != nil {
- fmt.Println("Prepare query error")
- panic(err)
- }
- _, err = stmt.Exec(cost.ElectricAmount, cost.ElectricPrice,
- cost.WaterAmount, cost.WaterPrice, cost.CheckedDate)
- if err != nil {
- fmt.Println("Execute query error")
- panic(err)
- }
+ //stmt, err := database.Prepare(`
+ // INSERT INTO cost(electric_amount, electric_price, water_amount, water_price, checked_date)
+ // VALUES(?, ?, ?, ?, ?)
+ //`)
+
+ //if err != nil {
+ // fmt.Println("Prepare query error")
+ // panic(err)
+ //}
+ //_, err = stmt.Exec(cost.ElectricAmount, cost.ElectricPrice,
+ // cost.WaterAmount, cost.WaterPrice, cost.CheckedDate)
+ //if err != nil {
+ // fmt.Println("Execute query error")
+ // panic(err)
+ //}
+
http.Redirect(w, r, "/", 301)
}
-func updateHandler(w http.ResponseWriter, r *http.Request) {
- isAuthenticated(w, r)
- if r.Method != "POST" {
- http.Redirect(w, r, "/", 301)
+func indexHandler(w http.ResponseWriter, r *http.Request) {
+ if true {
+ posts := []Homework{
+ {
+ Id: 123,
+ Title: "[CS][370][Confer] First Homework",
+ PostImage: "image1.jpeg",
+ Comments: []string{"This post is great!", "No, it really isn't"},
+ },
+ }
+
+ indexData := struct {
+ Authenticated bool
+ Posts []Homework
+ }{
+ authenticated,
+ posts,
+ }
+
+ err := tpl.ExecuteTemplate(w, "index.gohtml", indexData)
+
+ if err != nil {
+ log.Println(err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
}
- var cost Cost
- cost.Id, _ = strconv.ParseInt(r.FormValue("Id"), 10, 64)
- cost.ElectricAmount, _ = strconv.ParseInt(r.FormValue("ElectricAmount"), 10, 64)
- cost.ElectricPrice, _ = strconv.ParseFloat(r.FormValue("ElectricPrice"), 64)
- cost.WaterAmount, _ = strconv.ParseInt(r.FormValue("WaterAmount"), 10, 64)
- cost.WaterPrice, _ = strconv.ParseFloat(r.FormValue("WaterPrice"), 64)
- cost.CheckedDate = r.FormValue("CheckedDate")
- fmt.Println(cost)
- stmt, err := db.Prepare(`
- UPDATE cost SET electric_amount=?, electric_price=?, water_amount=?, water_price=?, checked_date=?
- WHERE id=?
- `)
- checkInternalServerError(err, w)
- res, err := stmt.Exec(cost.ElectricAmount, cost.ElectricPrice,
- cost.WaterAmount, cost.WaterPrice, cost.CheckedDate, cost.Id)
- checkInternalServerError(err, w)
- _, err = res.RowsAffected()
- checkInternalServerError(err, w)
- http.Redirect(w, r, "/", 301)
+
+ //http.Redirect(w, r, "/list", 301)
}
-func deleteHandler(w http.ResponseWriter, r *http.Request) {
- isAuthenticated(w, r)
- if r.Method != "POST" {
- http.Redirect(w, r, "/", 301)
+func postViewHandler(w http.ResponseWriter, req *http.Request) {
+
+ hw := Homework{
+ Id: 123,
+ Title: "[CS][370][Confer] First Homework",
+ PostImage: "image1.jpeg",
+ Comments: []string{"This post is great!", "No, it really isn't"},
}
- var costId, _ = strconv.ParseInt(r.FormValue("Id"), 10, 64)
- stmt, err := db.Prepare("DELETE FROM cost WHERE id=?")
- checkInternalServerError(err, w)
- res, err := stmt.Exec(costId)
- checkInternalServerError(err, w)
- _, err = res.RowsAffected()
- checkInternalServerError(err, w)
- http.Redirect(w, r, "/", 301)
+ err := tpl.ExecuteTemplate(w, "homework.gohtml", hw)
+
+ if err != nil {
+ log.Println(err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+}
+
+func checkInternalServerError(err error, w http.ResponseWriter) {
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
}
-func indexHandler(w http.ResponseWriter, r *http.Request) {
- isAuthenticated(w, r)
- http.Redirect(w, r, "/list", 301)
+func isAuthenticated(w http.ResponseWriter, r *http.Request) {
+ if !authenticated {
+ http.Redirect(w, r, "/login", 301)
+ }
}
diff --git a/main.go b/main.go
index 1fe87b3..6630e3c 100644
--- a/main.go
+++ b/main.go
@@ -6,10 +6,10 @@ package main
import (
"database/sql"
+ _ "github.com/mattn/go-sqlite3"
"html/template"
"log"
"net/http"
- _ "github.com/mattn/go-sqlite3"
)
var (
@@ -24,60 +24,27 @@ func init() {
func main() {
initialize_DB()
- http.Handle("/", http.FileServer(http.Dir("static/")))
/* Route for index page */
- http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
- err := tpl.ExecuteTemplate(w, "index.gohtml", struct{ Posts []Homework }{
- []Homework{
- {
- Id: 123,
- Title: "[CS][370][Confer] First Homework",
- PostImage: "image1.jpeg",
- Comments: []string{"This post is great!", "No, it really isn't"},
- },
- },
- })
-
- if err != nil {
- log.Println(err)
- http.Error(w, "Internal server error", http.StatusInternalServerError)
- return
- }
- })
+ http.HandleFunc("/", indexHandler)
// Route for static assets
http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("./static"))))
/* Route for posts */
- http.HandleFunc("/h/", func(w http.ResponseWriter, req *http.Request) {
-
- hw := Homework{
- Id: 123,
- Title: "[CS][370][Confer] First Homework",
- PostImage: "image1.jpeg",
- Comments: []string{"This post is great!", "No, it really isn't"},
- }
+ http.HandleFunc("/h/", postViewHandler)
- err := tpl.ExecuteTemplate(w, "homework.gohtml", hw)
-
- if err != nil {
- log.Println(err)
- http.Error(w, "Internal server error", http.StatusInternalServerError)
- return
- }
- })
-
- http.HandleFunc("/login", loginHandler)
- http.HandleFunc("/logout", logoutHandler)
- http.HandleFunc("/register", registerHandler)
- http.HandleFunc("/list", listHandler)
- http.HandleFunc("/create", createHandler)
+ http.HandleFunc("/login/", loginHandler)
+ http.HandleFunc("/logout/", logoutHandler)
+ http.HandleFunc("/register/", registerHandler)
+ http.HandleFunc("/list/", listHandler)
+ http.HandleFunc("/create/", createHandler)
port := ":3000"
log.Printf("Server running on port %s...\n", port)
http.ListenAndServe(port, nil)
}
+
func initialize_DB() {
database, _ = sql.Open("sqlite3", "./homeworkHub.db")
statement1, _ := database.Prepare("CREATE TABLE IF NOT EXISTS userInfo (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)")
diff --git a/templates/homework.gohtml b/templates/homework.gohtml
index 597dc00..ed9203c 100644
--- a/templates/homework.gohtml
+++ b/templates/homework.gohtml
@@ -7,29 +7,9 @@
PostImage:

- Upvotes: {{.Upvotes}}
-
- Downvotes: {{.Downvotes}}
Comments: {{range .Comments}} {{.}} {{end}}
-
- Tags:
-
-
From 8c1fe66c8b97b0fe11d3bf9a0f3267b3a80e0f64 Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Wed, 5 Dec 2018 20:20:06 -0500
Subject: [PATCH 24/62] Removed unnecessary field in User struct. Removed
unnecessary if statement.
---
handlers.go | 52 +++++++++++++++++++++++++---------------------------
models.go | 1 -
2 files changed, 25 insertions(+), 28 deletions(-)
diff --git a/handlers.go b/handlers.go
index f8a8818..cbef4bb 100644
--- a/handlers.go
+++ b/handlers.go
@@ -19,7 +19,7 @@ func registerHandler(w http.ResponseWriter, r *http.Request) {
// Check existence of user
var user User
err := database.QueryRow("SELECT username, password, role FROM users WHERE username=?",
- username).Scan(&user.Username, &user.Password, &user.Role)
+ username).Scan(&user.Username, &user.Password)
switch {
// user is available
@@ -127,35 +127,33 @@ func createHandler(w http.ResponseWriter, r *http.Request) {
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
- if true {
- posts := []Homework{
- {
- Id: 123,
- Title: "[CS][370][Confer] First Homework",
- PostImage: "image1.jpeg",
- Comments: []string{"This post is great!", "No, it really isn't"},
- },
- }
-
- indexData := struct {
- Authenticated bool
- Posts []Homework
- }{
- authenticated,
- posts,
- }
-
- err := tpl.ExecuteTemplate(w, "index.gohtml", indexData)
-
- if err != nil {
- log.Println(err)
- http.Error(w, "Internal server error", http.StatusInternalServerError)
- return
- }
+ // TODO: Query the database to populate this array.
+ posts := []Homework{
+ {
+ Id: 123,
+ Title: "[CS][370][Confer] First Homework",
+ PostImage: "image1.jpeg",
+ Comments: []string{"This post is great!", "No, it really isn't"},
+ },
+ }
+
+ indexData := struct {
+ Authenticated bool
+ Posts []Homework
+ }{
+ authenticated,
+ posts,
+ }
+
+ err := tpl.ExecuteTemplate(w, "index.gohtml", indexData)
+
+ if err != nil {
+ log.Println(err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
}
- //http.Redirect(w, r, "/list", 301)
}
func postViewHandler(w http.ResponseWriter, req *http.Request) {
diff --git a/models.go b/models.go
index b9008ef..ed94709 100644
--- a/models.go
+++ b/models.go
@@ -11,5 +11,4 @@ type User struct {
Id int64 `json:"id"`
Username string `json:"username"`
Password string `json:"password"`
- Role int64 `json:"role"`
}
From 9cbbfc65cff6b1048b5a773b6431082cc79632f1 Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Thu, 6 Dec 2018 14:02:10 -0500
Subject: [PATCH 25/62] Removed unnecessary variables, reassigned to the same
variable multiple times instead. Replaced redundant code with function call.
---
handlers.go | 14 ++++----------
main.go | 15 ++++++++-------
2 files changed, 12 insertions(+), 17 deletions(-)
diff --git a/handlers.go b/handlers.go
index cbef4bb..05c419d 100644
--- a/handlers.go
+++ b/handlers.go
@@ -148,16 +148,13 @@ func indexHandler(w http.ResponseWriter, r *http.Request) {
err := tpl.ExecuteTemplate(w, "index.gohtml", indexData)
- if err != nil {
- log.Println(err)
- http.Error(w, "Internal server error", http.StatusInternalServerError)
- return
- }
+ checkInternalServerError(err, w)
}
func postViewHandler(w http.ResponseWriter, req *http.Request) {
+ // TODO: Build this struct based on the information from the database
hw := Homework{
Id: 123,
Title: "[CS][370][Confer] First Homework",
@@ -167,15 +164,12 @@ func postViewHandler(w http.ResponseWriter, req *http.Request) {
err := tpl.ExecuteTemplate(w, "homework.gohtml", hw)
- if err != nil {
- log.Println(err)
- http.Error(w, "Internal server error", http.StatusInternalServerError)
- return
- }
+ checkInternalServerError(err, w)
}
func checkInternalServerError(err error, w http.ResponseWriter) {
if err != nil {
+ log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
diff --git a/main.go b/main.go
index 6630e3c..3cd4513 100644
--- a/main.go
+++ b/main.go
@@ -24,13 +24,14 @@ func init() {
func main() {
initialize_DB()
+
/* Route for index page */
http.HandleFunc("/", indexHandler)
// Route for static assets
http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("./static"))))
- /* Route for posts */
+ // Route for posts
http.HandleFunc("/h/", postViewHandler)
http.HandleFunc("/login/", loginHandler)
@@ -47,10 +48,10 @@ func main() {
func initialize_DB() {
database, _ = sql.Open("sqlite3", "./homeworkHub.db")
- statement1, _ := database.Prepare("CREATE TABLE IF NOT EXISTS userInfo (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)")
- statement1.Exec()
- statement2, _ := database.Prepare("CREATE TABLE IF NOT EXISTS post_info (post_id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, title TEXT, file_path TEXT)")
- statement2.Exec()
- statement3, _ := database.Prepare("CREATE TABLE IF NOT EXISTS comment_section (post_id INTEGER, username TEXT, comment TEXT)")
- statement3.Exec()
+ statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS userInfo (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)")
+ statement.Exec()
+ statement, _ = database.Prepare("CREATE TABLE IF NOT EXISTS post_info (post_id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, title TEXT, file_path TEXT)")
+ statement.Exec()
+ statement, _ = database.Prepare("CREATE TABLE IF NOT EXISTS comment_section (post_id INTEGER, username TEXT, comment TEXT)")
+ statement.Exec()
}
From b5de00e25c3ee59a465fa677fb2e63128b7fe384 Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Thu, 6 Dec 2018 14:25:23 -0500
Subject: [PATCH 26/62] Dynamically render the login/logout based on if the
user is authenticated or not
---
templates/top_bar.gohtml | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/templates/top_bar.gohtml b/templates/top_bar.gohtml
index bf042be..a473562 100644
--- a/templates/top_bar.gohtml
+++ b/templates/top_bar.gohtml
@@ -2,6 +2,10 @@
{{end}}
\ No newline at end of file
From f143af4f525b354d7e4aaf7fad991c65bfd04e20 Mon Sep 17 00:00:00 2001
From: Nathaniel Mitts
Date: Thu, 6 Dec 2018 14:42:34 -0500
Subject: [PATCH 27/62] Changed handlers files and dropped 'role'
---
handlers.go | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/handlers.go b/handlers.go
index 05c419d..9dee028 100644
--- a/handlers.go
+++ b/handlers.go
@@ -15,10 +15,10 @@ func registerHandler(w http.ResponseWriter, r *http.Request) {
// grab user info
username := r.FormValue("username")
password := r.FormValue("password")
- role := r.FormValue("role")
+
// Check existence of user
var user User
- err := database.QueryRow("SELECT username, password, role FROM users WHERE username=?",
+ err := database.QueryRow("SELECT username, password",
username).Scan(&user.Username, &user.Password)
switch {
@@ -27,7 +27,7 @@ func registerHandler(w http.ResponseWriter, r *http.Request) {
//hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
checkInternalServerError(err, w)
// insert to database
- _, err = database.Exec(`INSERT INTO users(username, password, role) VALUES(?, ?, ?)`,
+ _, err = database.Exec(`INSERT INTO users(username, password) VALUES(?, ?)`,
username, password, role)
fmt.Println("Created user: ", username)
checkInternalServerError(err, w)
From 38e9d78c3cf2df3618858d32567a66e9bb7d3704 Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Thu, 6 Dec 2018 14:47:02 -0500
Subject: [PATCH 28/62] Redirect logged in users to index
---
handlers.go | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/handlers.go b/handlers.go
index 05c419d..bbf6bbf 100644
--- a/handlers.go
+++ b/handlers.go
@@ -58,7 +58,7 @@ func loginHandler(w http.ResponseWriter, r *http.Request) {
// http.Redirect(w, r, "/login", 301)
//}
authenticated = true
- http.Redirect(w, r, "/list", 301)
+ http.Redirect(w, r, "/", 301)
}
From efbd7e6dc951eda08a16600ba15a1655d5f5ee0c Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Thu, 6 Dec 2018 16:36:02 -0500
Subject: [PATCH 29/62] Created login and register page.
---
handlers.go | 56 +++++++++++++++++++++++++++------------
main.go | 2 +-
templates/login.gohtml | 19 +++++++++++++
templates/register.gohtml | 25 +++++++++++++++++
4 files changed, 84 insertions(+), 18 deletions(-)
create mode 100644 templates/login.gohtml
create mode 100644 templates/register.gohtml
diff --git a/handlers.go b/handlers.go
index bbf6bbf..825024b 100644
--- a/handlers.go
+++ b/handlers.go
@@ -8,14 +8,22 @@ import (
)
func registerHandler(w http.ResponseWriter, r *http.Request) {
+ if authenticated {
+ http.Redirect(w, r, "/", 301)
+ return
+ }
+
if r.Method != "POST" {
- http.ServeFile(w, r, "templates/register.html")
+ err := tpl.ExecuteTemplate(w, "register.gohtml", nil)
+ checkInternalServerError(err, w)
+
return
}
+
// grab user info
username := r.FormValue("username")
password := r.FormValue("password")
- role := r.FormValue("role")
+
// Check existence of user
var user User
err := database.QueryRow("SELECT username, password, role FROM users WHERE username=?",
@@ -28,7 +36,7 @@ func registerHandler(w http.ResponseWriter, r *http.Request) {
checkInternalServerError(err, w)
// insert to database
_, err = database.Exec(`INSERT INTO users(username, password, role) VALUES(?, ?, ?)`,
- username, password, role)
+ username, password)
fmt.Println("Created user: ", username)
checkInternalServerError(err, w)
case err != nil:
@@ -40,23 +48,36 @@ func registerHandler(w http.ResponseWriter, r *http.Request) {
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
+ if authenticated {
+ http.Redirect(w, r, "/", http.StatusSeeOther)
+ return
+ }
+
if r.Method != "POST" {
- http.ServeFile(w, r, "templates/login.html")
+ err := tpl.ExecuteTemplate(w, "login.gohtml", nil)
+ checkInternalServerError(err, w)
+
return
}
- //// grab user info from the submitted form
- //username := r.FormValue("usrname")
- //password := r.FormValue("psw")
- //// query database to get match username
- //var user User
- //err := database.QueryRow("SELECT username, password FROM users WHERE username=?",
- // username).Scan(&user.Username, &user.Password)
- //checkInternalServerError(err, w)
- //// validate password
+
+ // grab user info from the submitted form
+ username := r.FormValue("usrname")
+ password := r.FormValue("psw")
+
+ // query database to get match username
+ var user User
+ err := database.QueryRow("SELECT username, password FROM users WHERE username=?",
+ username).Scan(&user.Username, &user.Password)
+
+ checkInternalServerError(err, w)
+
+ // validate password
//err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
- //if err != nil {
- // http.Redirect(w, r, "/login", 301)
- //}
+
+ if err != nil || password != user.Password {
+ http.Redirect(w, r, "/login", 301)
+ }
+
authenticated = true
http.Redirect(w, r, "/", 301)
@@ -72,6 +93,7 @@ func listHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusBadRequest)
}
+
//rows, err := database.Query("SELECT * FROM homework")
//checkInternalServerError(err, w)
//var funcMap = tpl.FuncMap{
@@ -97,7 +119,7 @@ func listHandler(w http.ResponseWriter, r *http.Request) {
}
-func createHandler(w http.ResponseWriter, r *http.Request) {
+func newPost(w http.ResponseWriter, r *http.Request) {
isAuthenticated(w, r)
if r.Method != "POST" {
http.Redirect(w, r, "/", 301)
diff --git a/main.go b/main.go
index 3cd4513..547050d 100644
--- a/main.go
+++ b/main.go
@@ -38,7 +38,7 @@ func main() {
http.HandleFunc("/logout/", logoutHandler)
http.HandleFunc("/register/", registerHandler)
http.HandleFunc("/list/", listHandler)
- http.HandleFunc("/create/", createHandler)
+ http.HandleFunc("/create/", newPost)
port := ":3000"
diff --git a/templates/login.gohtml b/templates/login.gohtml
new file mode 100644
index 0000000..152dd5e
--- /dev/null
+++ b/templates/login.gohtml
@@ -0,0 +1,19 @@
+{{template "header"}}
+
+
+
+
+
+
+
+
+{{template "footer"}}
\ No newline at end of file
diff --git a/templates/register.gohtml b/templates/register.gohtml
new file mode 100644
index 0000000..70d556f
--- /dev/null
+++ b/templates/register.gohtml
@@ -0,0 +1,25 @@
+{{template "header"}}
+
+
+
Register
+
+
+
+
+{{template "footer"}}
\ No newline at end of file
From 40a9a094388b2f568a108ff7616b7547748c8135 Mon Sep 17 00:00:00 2001
From: Robby Zambito
Date: Thu, 6 Dec 2018 17:26:52 -0500
Subject: [PATCH 30/62] Moved register data handler to separate end point
---
handlers.go | 26 ++++++++++++++++----------
main.go | 1 +
templates/login.gohtml | 19 +++++--------------
templates/register.gohtml | 20 +++++++++++---------
4 files changed, 33 insertions(+), 33 deletions(-)
diff --git a/handlers.go b/handlers.go
index fc0f3b7..311457e 100644
--- a/handlers.go
+++ b/handlers.go
@@ -8,22 +8,28 @@ import (
)
func registerHandler(w http.ResponseWriter, r *http.Request) {
- if authenticated {
- http.Redirect(w, r, "/", 301)
- return
- }
-
if r.Method != "POST" {
+ if authenticated {
+ http.Redirect(w, r, "/", http.StatusMovedPermanently)
+ return
+ }
+
err := tpl.ExecuteTemplate(w, "register.gohtml", nil)
checkInternalServerError(err, w)
return
}
+}
+
+func registerDataHandler(w http.ResponseWriter, r *http.Request) {
+ r.ParseForm()
// grab user info
username := r.FormValue("username")
password := r.FormValue("password")
+ fmt.Printf("Name entered: %s \tPass entered: %s\n", username, password)
+
// Check existence of user
var user User
err := database.QueryRow("SELECT username, password",
@@ -49,12 +55,12 @@ func registerHandler(w http.ResponseWriter, r *http.Request) {
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
- if authenticated {
- http.Redirect(w, r, "/", http.StatusMovedPermanently)
- return
- }
-
if r.Method != "POST" {
+ if authenticated {
+ http.Redirect(w, r, "/", http.StatusMovedPermanently)
+ return
+ }
+
err := tpl.ExecuteTemplate(w, "login.gohtml", nil)
checkInternalServerError(err, w)
diff --git a/main.go b/main.go
index 547050d..134bc05 100644
--- a/main.go
+++ b/main.go
@@ -37,6 +37,7 @@ func main() {
http.HandleFunc("/login/", loginHandler)
http.HandleFunc("/logout/", logoutHandler)
http.HandleFunc("/register/", registerHandler)
+ http.HandleFunc("/register/data", registerDataHandler)
http.HandleFunc("/list/", listHandler)
http.HandleFunc("/create/", newPost)
diff --git a/templates/login.gohtml b/templates/login.gohtml
index 152dd5e..14d92de 100644
--- a/templates/login.gohtml
+++ b/templates/login.gohtml
@@ -1,19 +1,10 @@
{{template "header"}}
-
-
-
-
-
+
{{template "footer"}}
\ No newline at end of file
diff --git a/templates/register.gohtml b/templates/register.gohtml
index 70d556f..149754b 100644
--- a/templates/register.gohtml
+++ b/templates/register.gohtml
@@ -3,20 +3,22 @@
Register
-