-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
184 lines (149 loc) · 4.54 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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"github.com/codegangsta/negroni"
"github.com/goincremental/negroni-sessions"
"github.com/goincremental/negroni-sessions/cookiestore"
_ "github.com/lib/pq"
"github.com/unrolled/render"
"golang.org/x/crypto/bcrypt"
)
var db *sql.DB = setupDB()
func init() {
db.Exec(`CREATE TABLE users (
id SERIAL,
user_name VARCHAR(60),
user_email VARCHAR(60),
user_password VARCHAR(60),
user_created TIMESTAMP WITH TIME ZONE,
user_last_login TIMESTAMP WITH TIME ZONE,
PRIMARY KEY (id),
CONSTRAINT users_email UNIQUE (user_email)
);`)
db.Exec(`INSERT INTO users (user_name, user_email, user_password)
VALUES ('john', 'john@example.com', 'supersecret');`)
}
func main() {
defer db.Close()
mux := http.NewServeMux()
n := negroni.Classic()
store := cookiestore.New([]byte("ohhhsooosecret"))
n.Use(sessions.Sessions("global_session_store", store))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
SimplePage(w, r, "mainpage")
})
mux.HandleFunc("/#", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
SimplePage(w, r, "login")
} else if r.Method == "POST" {
LoginPost(w, r)
}
})
mux.HandleFunc("/#", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
SimplePage(w, r, "#")
} else if r.Method == "POST" {
#Post(w, r)
}
})
mux.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
Logout(w, r)
})
mux.HandleFunc("/home", func(w http.ResponseWriter, r *http.Request) {
SimpleAuthenticatedPage(w, r, "home")
})
mux.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
APIHandler(w, r)
})
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
n.UseHandler(mux)
port := os.Getenv("PORT")
if port == "" {
port = "3300"
}
n.Run(":" + port)
}
func setupDB() *sql.DB {
db_url := os.Getenv("DATABASE_URL")
if db_url == "" {
db_url = "user=negroni password=negroni dbname=negroni-sample sslmode=disable"
}
db, err := sql.Open("postgres", db_url)
if err != nil {
fmt.Println(err)
panic(err)
}
return db
}
func errHandler(err error) {
if err != nil {
log.Print(err)
}
}
func SimplePage(w http.ResponseWriter, req *http.Request, template string) {
r := render.New(render.Options{})
r.HTML(w, http.StatusOK, template, nil)
}
func SimpleAuthenticatedPage(w http.ResponseWriter, req *http.Request, template string) {
session := sessions.GetSession(req)
sess := session.Get("useremail")
if sess == nil {
http.Redirect(w, req, "/notauthenticated", 301)
}
r := render.New(render.Options{})
r.HTML(w, http.StatusOK, template, nil)
}
func LoginPost(w http.ResponseWriter, req *http.Request) {
session := sessions.GetSession(req)
username := req.FormValue("inputUsername")
password := req.FormValue("inputPassword")
var (
email string
password_in_database string
)
err := db.QueryRow("SELECT user_email, user_password FROM users WHERE user_name = $1", username).Scan(&email, &password_in_database)
if err == sql.ErrNoRows {
http.Redirect(w, req, "/authfail", 301)
} else if err != nil {
log.Print(err)
http.Redirect(w, req, "/authfail", 301)
}
err = bcrypt.CompareHashAndPassword([]byte(password_in_database), []byte(password))
if err == bcrypt.ErrMismatchedHashAndPassword {
http.Redirect(w, req, "/authfail", 301)
} else if err != nil {
log.Print(err)
http.Redirect(w, req, "/authfail", 301)
}
session.Set("useremail", email)
http.Redirect(w, req, "/home", 302)
}
func #Post(w http.ResponseWriter, req *http.Request) {
username := req.FormValue("inputUsername")
password := req.FormValue("inputPassword")
email := req.FormValue("inputEmail")
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
panic(err)
}
_, err = db.Exec("INSERT INTO users (user_name, user_password, user_email) VALUES ($1, $2, $3)", username, string(hashedPassword), email)
if err != nil {
log.Print(err)
}
http.Redirect(w, req, "/#", 302)
}
func Logout(w http.ResponseWriter, req *http.Request) {
session := sessions.GetSession(req)
session.Delete("useremail")
http.Redirect(w, req, "/", 302)
}
func APIHandler(w http.ResponseWriter, req *http.Request) {
data, _ := json.Marshal("{'API Test':'Works!'}")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Write(data)
}