-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
281 lines (239 loc) · 6.52 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
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type loginInfo struct {
Email string `json:"email"`
Password string `json:"password"`
}
type name struct {
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
}
/*
------PostSignup(w http.ResponseWriter, r *http.Request)------
Input:
{
"email": "test@axiomzen.co",
"password": "axiomzen",
"firstName": "Alex",
"lastName": "Zimmerman"
}
Output:
{
"token": "some_jwt_token"
}
Notes:
1. need to return error if the user has already registerd
2. encode the whole payload
3. insert into the db
*/
func PostSignup(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var user userDetail
//Decode the request body part and match it against the userDetail struct
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
log.Printf("bad payload \n")
respondWithJson(w, http.StatusOK, err)
}
//establish connection with the local db and return a pointer to the db
//Input:
db := connectDB()
newUser := &userDetail{
Email: user.Email,
Password: user.Password,
FirstName: user.FirstName,
LastName: user.LastName,
}
//Generate a JWT for the JSON object and inset this new user into our local db
jwtToken := jwtSigning(newUser)
err = newUser.insertUser(db)
if err != nil {
respondWithJson(w, http.StatusBadRequest, err)
return
}
//Generate a response message that will return to the client server in JSON format
//Output:
var raw map[string]interface{}
responseMsg := fmt.Sprintf(` {
"token": "%s"
}`, jwtToken)
json.Unmarshal([]byte(responseMsg), &raw)
respondWithJson(w, http.StatusOK, raw)
closeDB()
return
}
/*
------PostLogin(w http.ResponseWriter, r *http.Request)------
Input:
{
"email": "test@axiomzen.co",
"password": "axiomzen"
}
Output:
{
"token": "some_jwt_token"
}
Notes:
1. need to capture the payload and extrat "usrname" and "password"
2. return the whole tuple after matching something in the db and pouplate a userDetail struct with it
*/
func PostLogin(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
loginInformation := loginInfo{}
//convet the payload into Byte for later proceeing use
bodyByte, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
respondWithJson(w, http.StatusBadRequest, err)
return
}
db := connectDB()
json.Unmarshal(bodyByte, &loginInformation)
//locate the user within the db and return an error if nothing matches
//When a match is found return the whole tuple and populate the userDetail struct
userDetailInfo := loginInformation.findUser(db)
if userDetailInfo == nil {
respondWithJson(w, http.StatusBadRequest, map[string]string{"result": "Incorrect username or password"})
return
}
verifyResult := verifyUser(userDetailInfo.Email, userDetailInfo.Password, db)
if verifyResult == false {
respondWithJson(w, http.StatusBadRequest, map[string]string{"result": "Incorrect Username or Password"})
return
}
//genertae a JWT
jwtToken := jwtSigning(userDetailInfo)
//Generate a response message that will return to the client server in JSON format
//Output:
var raw map[string]interface{}
responseMsg := fmt.Sprintf(` {
"token": "%s"
}`, jwtToken)
json.Unmarshal([]byte(responseMsg), &raw)
respondWithJson(w, http.StatusOK, raw)
closeDB()
return
}
/*
------GetUsers(w http.ResponseWriter, r *http.Request)------
Input:
x-authentication-token: {value}
Output:
{
"users": [
{
"email": "test@axiomzen.co",
"firstName": "Alex",
"lastName": "Zimmerman"
},
{
"email": "test@axiomzen.co",
"firstName": "Alex",
"lastName": "Zimmerman"
}
]
}
Notes:
1. extract the header
2. decode the JWT and find its corresponding email and password in the local db
3. validate the email and password in the db
4. return all users
*/
func GetUsers(w http.ResponseWriter, r *http.Request) {
jwtToken := r.Header.Get("x-authentication-token")
//decode the JWT and convet it back to the claim type
//https://jwt.io/introduction/
claim := jwtDecoding(jwtToken)
if claim == nil {
respondWithJson(w, http.StatusBadRequest, map[string]string{"result": "Incorrect JWT"})
return
}
db := connectDB()
//first it verifies the JWT token
verifyResult := verifyUser(claim.Email, claim.Password, db)
if verifyResult == false {
respondWithJson(w, http.StatusBadRequest, map[string]string{"result": "Incorrect JWT"})
return
}
//getAllUser returns x amount of users and they are pacakaged into a struct called "users"
allUsers, err := getAllUser(db)
if err != nil {
respondWithJson(w, http.StatusBadRequest, map[string]error{"result": err})
return
}
finalResult := map[string]interface{}{"users": allUsers}
respondWithJson(w, http.StatusOK, finalResult)
closeDB()
return
}
/*
------PutUsers(w http.ResponseWriter, r *http.Request)------
Input:
x-authentication-token: {value},
{
"firstName": "NewFirstName",
"lastName": "NewLastName"
}
Output:
{
"users": [
{
"email": "test@axiomzen.co",
"firstName": "Alex",
"lastName": "Zimmerman"
}
]
}
Notes:
1. extract the JWT in header
2. extractr the email and password in payload
3. validate the email and password in the db
4. update the information
5. update the db
*/
func PutUsers(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
newName := name{}
jwtToken := r.Header.Get("x-authentication-token")
//convet the payload into Byte for later proceeing use
bodyByte, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
respondWithJson(w, http.StatusBadRequest, err)
return
}
//decode the JWT and convet it back to the claim type
//https://jwt.io/introduction/
claim := jwtDecoding(jwtToken)
if claim == nil {
respondWithJson(w, http.StatusBadRequest, map[string]string{"result": "Incorrect JWT"})
return
}
//check the username and password against the db
db := connectDB()
Err := verifyUser(claim.Email, claim.Password, db)
if Err == nil {
respondWithJson(w, http.StatusBadRequest, map[string]string{"result": "Incorrect JWT"})
return
}
//unmarshal to the name struct
json.Unmarshal(bodyByte, &newName)
//updating the local db
newName.updateName(claim.Email, db)
log.Printf("Name changing done")
closeDB()
return
}
//This is a helper function that converts responses into JSON format and send back to the client server
func respondWithJson(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}