-
Notifications
You must be signed in to change notification settings - Fork 1
/
handlers.go
248 lines (178 loc) · 5.73 KB
/
handlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package main
import (
"database/sql"
"fmt"
"golang.org/x/crypto/bcrypt"
"io"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
)
func registerHandler(w http.ResponseWriter, r *http.Request) {
type registerPageDataStruct = struct {
UsernameTaken bool
PasswordMismatch bool
Authenticated bool
}
if r.Method != "POST" {
if !authenticated {
_ = tpl.ExecuteTemplate(w, "register.gohtml", registerPageDataStruct{false, false, false})
} else {
http.Redirect(w, r, "/", http.StatusMovedPermanently)
}
return
}
// grab user info
username := r.FormValue("username")
password := r.FormValue("password")
passAgain := r.FormValue("pass-again")
// Check existence of user
var user User
err := database.QueryRow("SELECT username, password FROM userInfo WHERE username=?;",
username).Scan(&user.Username, &user.Password)
switch {
// user is available
case err == sql.ErrNoRows && password == passAgain:
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
checkInternalServerError(err, w)
// insert to database
_, err = database.Exec("INSERT INTO userInfo(username, password) VALUES(?, ?);", username, hashedPassword)
checkInternalServerError(err, w)
http.Redirect(w, r, "/login", http.StatusMovedPermanently)
default:
_ = tpl.ExecuteTemplate(w, "register.gohtml", registerPageDataStruct{err != sql.ErrNoRows, password != passAgain, false})
}
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
type loginPageDataStruct = struct {
Failed bool
Authenticated bool
}
if r.Method != "POST" {
if !authenticated {
_ = tpl.ExecuteTemplate(w, "login.gohtml", loginPageDataStruct{false, false})
} else {
http.Redirect(w, r, "/", http.StatusMovedPermanently)
}
return
}
// grab user info from the submitted form
username := r.FormValue("username")
password := r.FormValue("password")
// query database to get match username
_ = database.QueryRow("SELECT username, password FROM userInfo WHERE username=?;",
username).Scan(&user.Username, &user.Password)
// validate password
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if err == nil {
authenticated = true
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
} else {
_ = tpl.ExecuteTemplate(w, "login.gohtml", loginPageDataStruct{true, false})
}
}
func logoutHandler(w http.ResponseWriter, r *http.Request) {
authenticated = false
isAuthenticated(w, r)
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
isAuthenticated(w, r)
if r.Method == "GET" {
err := tpl.ExecuteTemplate(w, "upload.gohtml", nil)
checkInternalServerError(err, w)
return
}
err = r.ParseMultipartForm(32 << 20)
checkInternalServerError(err, w)
var post Homework
post.Username = user.Username
file, handler, err := r.FormFile("upload-file")
checkInternalServerError(err, w)
rows, err := database.Query("SELECT COUNT(*) FROM postInfo")
checkInternalServerError(err, w)
defer rows.Close()
var count int64
for rows.Next() {
if err := rows.Scan(&count); err != nil {
log.Fatal(err)
}
}
post.Id = count + 1
post.Title = r.FormValue("title")
log.Printf("ID: %d\n", post.Id)
checkInternalServerError(err, w)
defer file.Close()
// Regex to match the file extension
reg, _ := regexp.Compile("\\.[0-9a-z]{1,5}$")
post.Extension = string(reg.Find([]byte(handler.Filename)))
filename := fmt.Sprintf("%d%s", post.Id, post.Extension)
f, err := os.OpenFile("./posts/"+filename, os.O_WRONLY|os.O_CREATE, 0666)
checkInternalServerError(err, w)
defer f.Close()
_, err = io.Copy(f, file)
checkInternalServerError(err, w)
_, err = database.Exec("INSERT INTO postInfo(username, title, extension) VALUES(?, ?, ?);",
post.Username, post.Title, post.Extension)
http.Redirect(w, r, "/", http.StatusMovedPermanently)
}
func indexHandler(w http.ResponseWriter, _ *http.Request) {
var posts []Homework
rows, err := database.Query("SELECT * FROM postInfo")
for rows.Next() {
var curPost Homework
if err := rows.Scan(&curPost.Id, &curPost.Username, &curPost.Title, &curPost.Extension); err != nil {
log.Fatal(err)
}
curPost.PostImage = fmt.Sprintf("%d%s", curPost.Id, curPost.Extension)
posts = append(posts, curPost)
}
indexData := struct {
Authenticated bool
Posts []Homework
}{
authenticated,
posts,
}
err = tpl.ExecuteTemplate(w, "index.gohtml", indexData)
checkInternalServerError(err, w)
}
func postViewHandler(w http.ResponseWriter, r *http.Request) {
var post Homework
post.Id, _ = strconv.ParseInt(strings.Replace(r.URL.Path, "/h/", "", 1), 10, 32)
err := database.QueryRow("SELECT title, username, extension FROM postInfo WHERE postId=?;",
post.Id).Scan(&post.Title, &post.Username, &post.Extension)
checkInternalServerError(err, w)
var comments []string
rows, err := database.Query("SELECT comment FROM commentSection WHERE postId=?;", post.Id)
for rows.Next() {
var curComment string
if err := rows.Scan(&curComment); err != nil {
log.Fatal(err)
}
comments = append(comments, curComment)
}
hw := Homework{
Id: post.Id,
Title: post.Title,
PostImage: fmt.Sprintf("%d%s", post.Id, post.Extension),
Username: post.Username,
Comments: comments,
}
postViewData := struct {
Authenticated bool
Hw Homework
}{
authenticated,
hw,
}
err = tpl.ExecuteTemplate(w, "homework.gohtml", postViewData)
checkInternalServerError(err, w)
}
func commentHandler(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseInt(strings.Replace(r.URL.Path, "/comment/", "", 1), 10, 32)
_, err = database.Exec("INSERT INTO commentSection(postId, comment) VALUES(?, ?);", id, r.FormValue("comment"))
http.Redirect(w, r, fmt.Sprintf("/h/%d", id), http.StatusMovedPermanently)
}