/
main.go
393 lines (338 loc) · 10.9 KB
/
main.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package main
import (
"net/http"
"html/template"
"database/sql"
_ "github.com/mattn/go-sqlite3"
_ "github.com/lib/pq"
"encoding/json"
"github.com/urfave/negroni"
"github.com/goincremental/negroni-sessions"
"github.com/goincremental/negroni-sessions/cookiestore"
gmux "github.com/gorilla/mux"
"strconv"
"golang.org/x/crypto/bcrypt"
"time"
"os"
"log"
)
type Page struct {
Tils []Til
User string
}
type LoginPage struct {
Register bool
Error string
}
type Til struct {
ID int
Title string
Date string
}
type User struct {
ID int
Email string
Password []byte
}
var db *sql.DB
func initDB() {
if os.Getenv("ENV") == "production" {
db, _ = sql.Open("postgres", os.Getenv("DATABASE_URL"))
if _, err := db.Exec("CREATE TABLE IF NOT EXISTS users (id serial NOT NULL PRIMARY KEY, email text NOT NULL, password text NOT NULL )"); err != nil {
log.Fatal("Error creating table users: " + err.Error())
return
}
if _, err := db.Exec("CREATE TABLE IF NOT EXISTS tils (id serial NOT NULL PRIMARY KEY, title text NOT NULL, user_id integer NOT NULL, date text NOT NULL )"); err != nil {
log.Fatal("Error creating table tils: " + err.Error())
return
}
} else {
db, _ = sql.Open("sqlite3", "til.db")
}
}
func verifyDatabase(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if err := db.Ping(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
next(w, r)
}
func NewUser(email, password string) *User {
pw, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return &User {
ID: -1,
Email: email,
Password: pw,
}
}
func getStringFromSession(r *http.Request, key string) string {
var strVal string
if val := sessions.GetSession(r).Get(key); val != nil {
strVal = val.(string)
}
return strVal
}
func verifyUser(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if r.URL.Path == "/login" {
next(w, r)
return
}
if email := getStringFromSession(r, "User"); email != "" {
var user User
var err error
if os.Getenv("ENV") == "production" {
err = db.QueryRow("SELECT id, email, password FROM users WHERE email = $1", r.FormValue("email")).Scan(&user.ID, &user.Email, &user.Password)
} else {
err = db.QueryRow("SELECT id, email, password FROM users WHERE email = ?", r.FormValue("email")).Scan(&user.ID, &user.Email, &user.Password)
}
if err == nil {
next(w, r)
return
}
}
//http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
next(w, r)
}
func (til *Til) formatDate() {
format := "2006-01-02 15:04:05-07:00"
if tilTime, err := time.Parse(format, til.Date); err == nil {
til.Date = tilTime.Format("Jan 2 2006")
}
}
func formatDate(date time.Time) string {
// 2016-12-03 15:22:41.822142097 -0800 PST
format := "2006-01-02 15:04:05 -0700 MST"
if t, err := time.Parse(format, time.Time.String(date)); err == nil {
return t.Format("Jan 2 2006")
}
return time.Time.String(date)
}
func main() {
templates := template.Must(template.ParseFiles(
"templates/index.html",
"templates/login.html"))
//db, _ = sql.Open("sqlite3", "til.db")
initDB()
mux := gmux.NewRouter()
s := http.StripPrefix("/resources/", http.FileServer(http.Dir("./resources/")))
mux.PathPrefix("/resources/").Handler(s)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
email := getStringFromSession(r, "User")
p := Page{
Tils: []Til{},
User: email,
}
// Fetch user
var user User
var err error
if os.Getenv("ENV") == "production" {
err = db.QueryRow("SELECT id, email FROM users WHERE email = $1", email).Scan(&user.ID, &user.Email)
} else {
err = db.QueryRow("SELECT id, email FROM users WHERE email = ?", email).Scan(&user.ID, &user.Email)
}
// Fetch TILs for user
if err == nil {
if os.Getenv("ENV") == "production" {
rows, _ := db.Query("SELECT id, title, date FROM tils WHERE user_id = $1", user.ID)
for rows.Next() {
var t Til
rows.Scan(&t.ID, &t.Title, &t.Date)
t.formatDate()
p.Tils = append(p.Tils, t)
}
} else {
rows, _ := db.Query("SELECT id, title, date FROM tils WHERE user_id = ?", user.ID)
for rows.Next() {
var t Til
rows.Scan(&t.ID, &t.Title, &t.Date)
t.formatDate()
p.Tils = append(p.Tils, t)
}
}
}
if err := templates.ExecuteTemplate(w, "index.html", p); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
mux.HandleFunc("/register", func(w http.ResponseWriter, r *http.Request){
var page LoginPage
page.Register = true
// If user already in session, redirect to home page
if email := getStringFromSession(r, "User"); email != "" {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
// Using the login.html template for both register and login
if err := templates.ExecuteTemplate(w, "login.html", page); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request){
var page LoginPage
var user User
validationPasses := true
// If user already in session, redirect to home page
if email := getStringFromSession(r, "User"); email != "" {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
if r.FormValue("register") != "" {
page.Register = true
// Validation
if r.FormValue("password") != r.FormValue("password-confirm") {
page.Error = "Passwords don't match."
validationPasses = false
}
user := NewUser(r.FormValue("email"), r.FormValue("password"))
// Check if user already exists
var err error
if os.Getenv("ENV") == "production" {
err = db.QueryRow("SELECT id, email, password FROM users WHERE email = $1", r.FormValue("email")).Scan(&user.ID, &user.Email, &user.Password)
} else {
err = db.QueryRow("SELECT id, email, password FROM users WHERE email = ?", r.FormValue("email")).Scan(&user.ID, &user.Email, &user.Password)
}
// If no error, user exists: don't add
if err == nil {
page.Error = "User already exists"
validationPasses = false
}
if validationPasses {
var err error
if os.Getenv("ENV") == "production" {
_, err = db.Exec("INSERT INTO users (email, password) VALUES($1, $2)", user.Email, user.Password)
} else {
_, err = db.Exec("INSERT INTO users (id, email, password) values (?, ?, ?)", nil, user.Email, user.Password)
}
//if _, err := db.Exec("INSERT INTO users (id, email, password) values (?, ?, ?)", nil, user.Email, user.Password); err != nil {
if err != nil {
page.Error = "tried to insert: " + err.Error() + " user: " + user.Email + " password: " + string(user.Password)
} else {
// Put user into session
sessions.GetSession(r).Set("User", user.Email)
http.Redirect(w, r, "/", http.StatusFound)
return
}
}
} else if r.FormValue("login") != "" {
var err error
if os.Getenv("ENV") == "production" {
err = db.QueryRow("SELECT id, email, password FROM users WHERE email = $1", r.FormValue("email")).Scan(&user.ID, &user.Email, &user.Password)
} else {
err = db.QueryRow("SELECT id, email, password FROM users WHERE email = ?", r.FormValue("email")).Scan(&user.ID, &user.Email, &user.Password)
}
if err != nil {
page.Error = "Email/password combination incorrect"
} else {
if err = bcrypt.CompareHashAndPassword(user.Password, []byte(r.FormValue("password"))); err != nil {
page.Error = "Email/password combination incorrect"
} else {
// Put user into session
sessions.GetSession(r).Set("User", user.Email)
http.Redirect(w, r, "/", http.StatusFound)
return
}
}
}
if err := templates.ExecuteTemplate(w, "login.html", page); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
mux.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request){
sessions.GetSession(r).Set("User", nil)
http.Redirect(w, r, "/login", http.StatusFound)
})
mux.HandleFunc("/create", func(w http.ResponseWriter, r *http.Request){
// Get user
var user User
email := getStringFromSession(r, "User")
var err error
if os.Getenv("ENV") == "production" {
err = db.QueryRow("SELECT id, email, password FROM users WHERE email = $1", email).Scan(&user.ID, &user.Email, &user.Password)
} else {
err = db.QueryRow("SELECT id, email, password FROM users WHERE email = ?", email).Scan(&user.ID, &user.Email, &user.Password)
}
now := time.Now()
formattedDate := formatDate(now)
encoder := json.NewEncoder(w)
// Only insert TIL if we have a user
if err == nil {
title := r.FormValue("title")
var results []Til
if os.Getenv("ENV") == "production" {
row, err := db.Exec("INSERT INTO tils (title, user_id, date) values ($1, $2, $3)", title, user.ID, now)
id, _ := row.LastInsertId()
results = []Til{
Til{ID: int(id), Title: title, Date: formattedDate},
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
} else {
row, err := db.Exec("INSERT INTO tils (id, title, user_id, date) values (?, ?, ?, ?)", nil, title, user.ID, now)
id, _ := row.LastInsertId()
results = []Til{
Til{ID: int(id), Title: title, Date: formattedDate},
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
if err := encoder.Encode(results); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
} else {
results := []Til{
Til{ID: int(-1), Title: r.FormValue("title"), Date: formattedDate},
}
encoder.Encode(results)
}
})
mux.HandleFunc("/delete/{id}", func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(gmux.Vars(r)["id"], 10, 64)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
if os.Getenv("ENV") == "production" {
_, err = db.Exec("DELETE FROM tils WHERE id = $1", id)
} else {
_, err = db.Exec("DELETE FROM tils WHERE id = ?", id)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("/edit", func(w http.ResponseWriter, r *http.Request) {
type JsonTil struct {
ID string `json:"ID"`
Title string `json:"Title"`
}
var til JsonTil
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&til)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if os.Getenv("ENV") == "production" {
_, err = db.Exec("UPDATE tils SET title = $1 WHERE id = $2", til.Title, til.ID)
} else {
_, err = db.Exec("UPDATE tils SET title = ? WHERE id = ?", til.Title, til.ID)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
})
n := negroni.Classic()
n.Use(sessions.Sessions("til", cookiestore.New([]byte("my-secret-123"))))
n.Use(negroni.HandlerFunc(verifyDatabase))
n.Use(negroni.HandlerFunc(verifyUser))
n.UseHandler(mux)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
n.Run(":" + port)
}