-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
278 lines (219 loc) · 8.71 KB
/
handler.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package main
import (
"github.com/codegangsta/martini"
"github.com/gorilla/sessions"
"github.com/hoisie/mustache"
"github.com/justinas/nosurf"
"net/http"
"regexp"
"strconv"
"strings"
"time"
)
func Start(DB *Connection, config *Config) {
// Create a new cookie store
store := sessions.NewCookieStore([]byte(config.SecretKey))
m := martini.Classic()
// It will be available to all handlers as *sessions.CookieStore
m.Map(store)
// It will be available to all handlers as *connection *Connection
m.Map(DB)
// It will be available to all handlers as *Config
m.Map(config)
// public folder will serve the static content
m.Use(martini.Static("public"))
// Tag-related routes
m.Get("/tag/:tag/:page", AuthRequired, GetTagHandler)
// Bookmark-related routes
m.Get("/bookmarks/:page", AuthRequired, GetBookmarksHandler)
m.Post("/bookmark/new", AuthRequired, NewBookmarkHandler)
m.Delete("/bookmark/delete/:bookmark", AuthRequired, DeleteBookmarkHandler)
// Search
m.Post("/search/:page", AuthRequired, SearchHandler)
// User-related routes
m.Post("/login", LoginPostHandler)
m.Get("/logout", AuthRequired, LogoutHandler)
m.Post("/signup", SignUpHandler)
m.Post("/new_token", AuthRequired, RequestNewToken)
// Test
m.Get("/test", TestHandler)
// Home
m.Get("/", func(cs *sessions.CookieStore, req *http.Request, w http.ResponseWriter, connection *Connection) {
if GetUserID(cs, req, connection) == "" {
LoginHandler(req, w)
}
}, IndexHandler)
csrfHandler := nosurf.New(m)
csrfHandler.SetFailureHandler(http.HandlerFunc(CsrfFailHandler))
http.ListenAndServe(config.Port, csrfHandler)
}
// CsrfFailHandler writes invalid token response
func CsrfFailHandler(w http.ResponseWriter, r *http.Request) {
WriteJSONResponse(200, true, "Provided token is not valid.", r, w)
}
// GetBookmarksHandler writes bookmarks to JSON data
func GetBookmarksHandler(params martini.Params, req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, connection *Connection) {
_, userID := GetUserData(cs, req)
page, _ := strconv.ParseInt(params["page"], 10, 16)
bookmarks := GetBookmarks(page, connection, userID)
JSONDataResponse(200, false, bookmarks, req, w)
}
// IndexHandler writes out templates
func IndexHandler(req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, connection *Connection) {
username, userID := GetUserData(cs, req)
context := map[string]interface{}{
"title": "Magnet",
"csrf_token": nosurf.Token(req),
"bookmarks": GetBookmarks(0, connection, userID),
"tags": GetTags(connection, userID),
"username": username,
}
context["load_more"] = len(context["bookmarks"].([]Bookmark)) == 50
w.Write([]byte(mustache.RenderFileInLayout("templates/home.mustache", "templates/base.mustache", context)))
}
// TestHandler runs the tests
func TestHandler(req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, connection *Connection) {
w.Write([]byte(mustache.RenderFileInLayout("templates/test.mustache", "templates/test.base.mustache", nil)))
}
// NewBookmarkHandler writes out new bookmark JSON response
func NewBookmarkHandler(req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, connection *Connection) {
// We use a map instead of Bookmark because id would be ""
bookmark := make(map[string]interface{})
bookmark["Title"] = req.PostFormValue("title")
bookmark["Url"] = req.PostFormValue("url")
if !IsValidURL(bookmark["Url"].(string)) {
WriteJSONResponse(200, true, "The url is not valid.", req, w)
} else {
_, userID := GetUserData(cs, req)
bookmark["Created"] = float64(time.Now().Unix())
bookmark["Date"] = time.Unix(int64(bookmark["Created"].(float64)), 0).Format("Jan 2, 2006 at 3:04pm")
bookmark["User"] = userID
str := FetchUrl(bookmark["Url"].(string))
if strings.Contains(str, "<title>") {
left := strings.Index(str, "<title>")
right := strings.Index(str, "</title>")
bookmark["Title"] = str[left+len("<title>") : right]
} else {
bookmark["Title"] = bookmark["Url"]
}
bookmark["Tags"] = strings.Split(bookmark["Title"].(string), " ")
for i, v := range bookmark["Tags"].([]string) {
bookmark["Tags"].([]string)[i] = strings.ToLower(strings.TrimSpace(v))
}
response, _ := connection.NewBookmark(userID, bookmark)
if response.Inserted > 0 {
JSONDataResponse(200, false, bookmark, req, w)
} else {
WriteJSONResponse(200, true, "Error inserting bookmark.", req, w)
}
}
}
// DeleteBookmarkHandler writes out response to deleting a bookmark
func DeleteBookmarkHandler(params martini.Params, req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, connection *Connection) {
_, userID := GetUserData(cs, req)
response, err := connection.DeleteBookmark(userID, params)
if err != nil {
WriteJSONResponse(200, true, "Error deleting bookmark.", req, w)
} else {
if response.Deleted > 0 {
WriteJSONResponse(200, false, "Bookmark deleted successfully.", req, w)
} else {
WriteJSONResponse(200, true, "Error deleting bookmark.", req, w)
}
}
}
// SearchHandler writes out response when searching for a URL
func SearchHandler(params martini.Params, req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, connection *Connection) {
_, userID := GetUserData(cs, req)
query := req.PostFormValue("query")
response, err := connection.Search(userID, params, query)
if err != nil {
WriteJSONResponse(200, true, "Error retrieving bookmarks", req, w)
} else {
JSONDataResponse(200, false, response, req, w)
}
}
// GetTagHandler fetches books for a given tag
func GetTagHandler(params martini.Params, req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, connection *Connection) {
_, userID := GetUserData(cs, req)
response, err := connection.GetTag(userID, params)
if err != nil {
WriteJSONResponse(200, true, "Error getting bookmarks for tag "+params["tag"], req, w)
} else {
JSONDataResponse(200, false, response, req, w)
}
}
// LoginHandler writes out login template
func LoginHandler(r *http.Request, w http.ResponseWriter) {
context := map[string]interface{}{
"title": "Access magnet",
"csrf_token": nosurf.Token(r),
}
w.Write([]byte(mustache.RenderFileInLayout("templates/login.mustache", "templates/base.mustache", context)))
}
// LoginPostHandler writes out login response
func LoginPostHandler(req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, cfg *Config, connection *Connection) {
username := req.PostFormValue("username")
password := cryptPassword(req.PostFormValue("password"), cfg.SecretKey)
var response []interface{}
response, err := connection.LoginPost(username, password)
if err != nil || len(response) == 0 {
WriteJSONResponse(200, true, "Invalid username or password.", req, w)
} else {
// Store session
userID := response[0].(map[string]interface{})["id"].(string)
session := Session{UserID: userID,
Expires: time.Now().Unix() + int64(cfg.SessionExpires)}
response, err := connection.LoginPostInsertSession(session)
if err != nil || response.Inserted < 1 {
WriteJSONResponse(200, true, "Error creating the user session.", req, w)
} else {
session, _ := cs.Get(req, "magnet_session")
session.Values["session_id"] = response.GeneratedKeys[0]
session.Values["username"] = username
session.Values["user_id"] = userID
session.Save(req, w)
WriteJSONResponse(200, false, "User correctly logged in.", req, w)
}
}
}
// LogoutHandler writes out logout response
func LogoutHandler(cs *sessions.CookieStore, req *http.Request, connection *Connection, w http.ResponseWriter) {
session, _ := cs.Get(req, "magnet_session")
_, _ = connection.Logout(session)
session.Values["user_id"] = ""
session.Values["session_id"] = ""
session.Values["username"] = ""
session.Save(req, w)
http.Redirect(w, req, "/", 301)
}
// SignUpHandler writes out response to singing up
func SignUpHandler(req *http.Request, w http.ResponseWriter, connection *Connection, cs *sessions.CookieStore, cfg *Config) {
user := new(User)
req.ParseForm()
user.Username = req.PostFormValue("username")
user.Email = req.PostFormValue("email")
user.Password = cryptPassword(req.PostFormValue("password"), cfg.SecretKey)
errors := ""
if len(user.Username) == 0 || len(user.Email) == 0 {
errors += "Empty fields. "
}
exp, _ := regexp.Compile(`[a-zA-Z0-9._%+-]+@([a-zA-Z0-9-]+\.)+[A-Za-z]{2,6}`)
if !exp.MatchString(user.Email) {
errors += "Invalid email address. "
}
response, err := connection.SignUp(user)
if err != nil || len(response) != 0 {
errors += "Username or email taken."
} else {
_, err = connection.SignUpInsert(user)
if err != nil {
errors += "There was an error creating the user."
} else {
WriteJSONResponse(201, false, "New user created.", req, w)
}
}
if errors != "" {
WriteJSONResponse(200, true, errors, req, w)
}
}