-
Notifications
You must be signed in to change notification settings - Fork 27
/
handlers.go
177 lines (164 loc) · 5.25 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
package main
import (
"database/sql"
"fmt"
"html/template"
"net/http"
"strconv"
"golang.org/x/crypto/bcrypt"
)
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)
}