/
userApp.go
322 lines (295 loc) · 8.67 KB
/
userApp.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
package app
import (
"GoLive/cache"
"GoLive/db"
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"strings"
"time"
"github.com/gorilla/mux"
uuid "github.com/satori/go.uuid"
"golang.org/x/crypto/bcrypt"
)
type Data struct {
User db.User //to display individual user
Merchant db.Merchant //to display individual merchant profile to himself logged in merchant
MerchantShop db.Merchant //display individual merchant shop to consumers public page
Merchants []db.Merchant //to display all the merchants
Error Error //to display an error message IF there is an error msg
Products []db.Product //to display featured items
Cart cache.Cart //to display checkout cart
}
type Error struct {
ErrMsg string
}
func (a *App) displayLogin(w http.ResponseWriter, r *http.Request) {
// Check session; if already logged in then redirect to home page
if _, alreadyLoggedIn := a.HaveValidSessionCookie(r); alreadyLoggedIn {
fmt.Println("fuck you cookie")
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
// ExecuteTemplate
t, err := template.ParseFiles("templates/base.html", "templates/footer.html", "templates/navbar.html", "templates/loginBody.html", "templates/error.html")
if err != nil {
log.Fatal(err)
}
data := Data{}
err = t.Execute(w, data)
if err != nil {
log.Fatal(err)
}
}
func (a *App) validateUserLogin(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
hashedPW, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
if err != nil {
log.Fatal(err)
}
foundUser, err := a.db.GetUser(username)
if err != nil {
fmt.Println(err, "error in get user")
w.WriteHeader(http.StatusForbidden)
//w.Write([]byte("403 - Invalid Login Credentials"))
t, err := template.ParseFiles("templates/base.html", "templates/footer.html", "templates/navbar.html", "templates/loginBody.html", "templates/error.html")
if err != nil {
log.Fatal(err)
}
data := Data{Error: Error{"Piece of shit who can't even remember your password / username"}}
err = t.Execute(w, data)
if err != nil {
log.Fatal(err)
}
return
}
if err := bcrypt.CompareHashAndPassword(hashedPW, []byte(foundUser.Password)); err != nil {
fmt.Println(foundUser.Password, "not correct")
w.WriteHeader(http.StatusForbidden)
//w.Write([]byte("403 - Invalid Login Credentials"))
t, err := template.ParseFiles("templates/base.html", "templates/footer.html", "templates/navbar.html", "templates/loginBody.html", "templates/error.html")
if err != nil {
log.Fatal(err)
}
data := Data{Error: Error{"Piece of shit who can't even remember your password / username"}}
err = t.Execute(w, data)
if err != nil {
log.Fatal(err)
}
return
}
var cart cache.Cart
cart = make([]cache.CartItem, 0)
newsessionKey := "U" + uuid.NewV4().String()
newsession := cache.NewUserSession(
newsessionKey,
time.Now().Add(cache.SessionLife*time.Minute),
foundUser,
cart,
)
newCookie := &http.Cookie{
Name: "sessionCookie",
Value: newsessionKey,
Path: "/",
}
http.SetCookie(w, newCookie)
a.cacheManager.AddtoCache(newsession)
t, err := template.ParseFiles("templates/base.html", "templates/footer.html", "templates/navbar.html", "templates/body.html", "templates/error.html")
if err != nil {
log.Fatal(err)
}
p, _ := a.db.GetAllProducts()
data := Data{User: foundUser, Products: p}
err = t.Execute(w, data)
if err != nil {
fmt.Println(err)
}
}
func (a *App) validateMerchantLogin(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
hashedPW, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
if err != nil {
log.Fatal(err)
}
foundMerch, err := a.db.GetMerchant(username)
if err != nil {
w.WriteHeader(http.StatusForbidden)
//w.Write([]byte("403 - Invalid Login Credentials"))
return
}
if err := bcrypt.CompareHashAndPassword(hashedPW, []byte(foundMerch.User.Password)); err != nil {
w.WriteHeader(http.StatusForbidden)
//w.Write([]byte("403 - Invalid Login Credentials"))
return
}
newsessionKey := "M" + uuid.NewV4().String()
newsession := cache.NewMerchSession(newsessionKey,
time.Now().Add(cache.SessionLife),
foundMerch)
a.cacheManager.AddtoCache(newsession)
}
func (a *App) logout(w http.ResponseWriter, r *http.Request) {
sessionKey, err := r.Cookie("sessionCookie")
sessionKeyVal := sessionKey.String()
// Verify valid user type
if err != nil {
// No Session Cookie
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
switch string(sessionKeyVal[0]) {
case "U":
a.cacheManager.RemoveFromCache(sessionKeyVal, "activeUsers")
case "M":
a.cacheManager.RemoveFromCache(sessionKeyVal, "activeMerchants")
}
sessionKey.Expires = time.Now()
http.SetCookie(w, sessionKey)
jData, err := json.Marshal(Response{true})
w.Header().Set("Content-Type", "application/json")
w.Write(jData)
}
func (a *App) allUser(w http.ResponseWriter, r *http.Request) {
users, err := a.db.GetUsers()
if err != nil {
log.Fatal(err)
}
fmt.Println(users)
w.WriteHeader(http.StatusOK)
w.Write([]byte("200 - Get All Users OK"))
}
func (a *App) getUser(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
// Verify valid merchant ID
userID := params["userid"]
var u db.User
u, err := a.db.GetUser(userID)
if err != nil {
fmt.Println(err)
// Invalid user ID inputted
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 - No user for input USERID"))
return
}
fmt.Println(u, "printing user")
w.WriteHeader(http.StatusOK)
w.Write([]byte("200 - Valid merchant ID, displaying store"))
}
func (a *App) postUser(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username := r.FormValue("username")
email := strings.ToLower(r.FormValue("email"))
pw1 := r.FormValue("pw1")
pw2 := r.FormValue("pw2")
var u db.User
u.Name = username
u.Email = email
if u.Name == "" {
fmt.Println("Empty user name")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Bad Request"))
return
}
if u.Email == "" {
fmt.Println("Empty email")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Bad Request"))
return
}
err := a.db.CheckUser(u)
if err != nil {
//send the err msg back (err = errmsg)
fmt.Println(err, "CheckUser error")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Bad Request"))
return
}
if pw1 != pw2 {
//t.ParseFiles("./templates/errorRegister.html")
//data := Data{nil, ErrorMsg{"color:red", "Password entered are different"}, ErrorMsg{"display:none", ""}, ErrorMsg{"display:block", ""}, 0, nil}
//t.Execute(w, data)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Repeated PW"))
return
}
err = a.db.CreateUser(u, pw1)
if err != nil {
//send the err msg back (err = errmsg)
fmt.Println(err, "createuser error")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Bad Request"))
return
}
//w.Write([]byte("201 - User Creation Successful"))
newsessionKey := "U" + uuid.NewV4().String()
newsession := cache.NewUserSession(
newsessionKey,
time.Now().Add(cache.SessionLife*time.Minute),
u,
make([]cache.CartItem, 0))
newCookie := &http.Cookie{
Name: "sessionCookie",
Value: newsessionKey,
}
http.SetCookie(w, newCookie)
a.cacheManager.AddtoCache(newsession)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func (a *App) putUser(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
userID, ok := params["userid"]
if !ok {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 - Status Not Found"))
http.Redirect(w, r, "/users", http.StatusNotFound)
return
}
username := r.URL.Query().Get("Username")
if username == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Username cannot be empty"))
return
}
email := r.URL.Query().Get("Email")
if email == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Email cannot be empty"))
return
}
var u db.User
u.Name = username
u.Email = email
u.Id = userID
err := a.db.UpdateUser(u)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte("422 - Unprocessable Entity"))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("200 - Updated Successfully"))
}
func (a *App) delUser(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
userID, ok := params["userid"]
if !ok {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 - Status not Found"))
return
}
err := a.db.DeleteUser(userID)
if err != nil {
log.Fatal(err)
}
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte("422 - Unprocessable Entity"))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("200 - Deleted Successfully"))
}