forked from mycoralhealth/healthtip-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apihandlers.go
426 lines (336 loc) · 9.5 KB
/
apihandlers.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package main
import (
"crypto/rand"
"database/sql"
"encoding/base32"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"os"
"strconv"
"time"
"github.com/gorilla/mux"
)
func makeLoginResult(user User, auth AuthToken) LoginResult {
var result LoginResult
result.Token = auth
result.Email = user.Email
result.First_name = user.First_name
result.Last_name = user.Last_name
return result
}
func handleWriteUser(w http.ResponseWriter, r *http.Request, dbCon *sql.DB) {
var user User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&user); err != nil {
handleError(w, r, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
if len(user.Password) < 6 {
handleError(w, r, http.StatusUnprocessableEntity, "Minimum password length is 6 characters")
return
}
lastID, err := writeUser(dbCon, user)
if err != nil {
handleError(w, r, http.StatusUnprocessableEntity, err.Error())
return
}
user.ID = int(lastID)
auth, err := createAuthToken(user.ID, dbCon)
if err != nil {
handleError(w, r, http.StatusUnprocessableEntity, err.Error())
return
}
respondWithJSON(w, r, http.StatusCreated, makeLoginResult(user, auth))
}
func createAuthToken(ID int, dbCon *sql.DB) (AuthToken, error) {
var auth AuthToken
// create auth token and put in DB
auth.Api_user = ID
// generated salted hash from current time and random number is the auth token
token, err := getRandomString(10)
if err != nil {
return auth, err
}
auth.Api_key = hashPassword(token)
if err := writeAuthToken(dbCon, auth); err != nil {
return auth, err
}
return auth, nil
}
func getRandomString(length int) (string, error) {
randomBytes := make([]byte, 32)
_, err := rand.Read(randomBytes)
if err != nil {
return "", err
}
return base32.StdEncoding.EncodeToString(randomBytes)[:length], nil
}
func handleUpdateUser(w http.ResponseWriter, r *http.Request, dbCon *sql.DB) {
var user User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&user); err != nil {
handleError(w, r, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
auth, _ := getBasicAPIAuth(r)
user.ID = auth.Api_user
if err := updateUser(dbCon, user); err != nil {
handleError(w, r, http.StatusUnprocessableEntity, err.Error())
return
}
respondWithJSON(w, r, http.StatusCreated, user.Email)
}
func handleLogin(w http.ResponseWriter, r *http.Request, dbCon *sql.DB) {
user, err := getBasicLoginAuth(r)
if err != nil {
handleError(w, r, http.StatusUnauthorized, err.Error())
return
}
dbUser, err := checkUserExists(dbCon, user)
if err != nil {
handleError(w, r, 404, err.Error())
return
}
if err := checkLoginAuth(dbCon, user); err != nil {
handleError(w, r, http.StatusUnauthorized, "Unauthorized")
return
}
auth, err := createAuthToken(dbUser.ID, dbCon)
if err != nil {
handleError(w, r, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, r, http.StatusOK, makeLoginResult(dbUser, auth))
}
func handleChangePassword(w http.ResponseWriter, r *http.Request, dbCon *sql.DB) {
auth, _ := getBasicAPIAuth(r)
var user User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&user); err != nil {
handleError(w, r, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
user.ID = auth.Api_user
err := updateUserPassword(dbCon, user)
if err != nil {
handleError(w, r, http.StatusBadRequest, err.Error())
return
}
respondWithJSON(w, r, http.StatusNoContent, nil)
}
func handleResetPassword(w http.ResponseWriter, r *http.Request, dbCon *sql.DB) {
// request should send user object with just email
var user User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&user); err != nil {
handleError(w, r, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
dbUser, err := checkUserExists(dbCon, user)
if err != nil {
handleError(w, r, 404, err.Error())
return
}
auth, err := createAuthToken(dbUser.ID, dbCon)
if err != nil {
handleError(w, r, http.StatusUnprocessableEntity, err.Error())
return
}
url := os.Getenv("CLIENT_URL") + "changePass?token=" + url.QueryEscape(auth.Api_key)
emailPasswordReset(dbUser, url)
respondWithJSON(w, r, http.StatusNoContent, nil)
}
func handleClaimToken(w http.ResponseWriter, r *http.Request, dbCon *sql.DB) {
var auth AuthToken
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&auth); err != nil {
handleError(w, r, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
userID, err := returnAuthUserID(dbCon, auth)
if err != nil {
handleError(w, r, 404, err.Error())
return
}
auth.Api_user = userID
if err := deleteAuthToken(dbCon, auth); err != nil {
handleError(w, r, http.StatusInternalServerError, err.Error())
return
}
user, err := findUser(dbCon, userID)
if err != nil {
handleError(w, r, 404, err.Error())
return
}
newAuth, err := createAuthToken(user.ID, dbCon)
if err != nil {
handleError(w, r, http.StatusUnprocessableEntity, err.Error())
return
}
respondWithJSON(w, r, http.StatusOK, makeLoginResult(user, newAuth))
}
func getBasicLoginAuth(r *http.Request) (User, error) {
var user User
email, password, ok := r.BasicAuth()
if !ok {
return user, errors.New("Invalid login auth")
}
user.Email = email
user.Password = password
return user, nil
}
/*
API handlers, authorization is handled in web.go wrapper function
*/
func getBasicAPIAuth(r *http.Request) (AuthToken, error) {
var token AuthToken
p, s, ok := r.BasicAuth()
if !ok {
return token, errors.New("invalid API Authorization token. Required Basic Api_user:Api_key")
}
apiUser, err := strconv.Atoi(p)
if err != nil {
return token, errors.New("invalid Api_user")
}
token.Api_user = apiUser
token.Api_key = s
return token, nil
}
func handleLogout(w http.ResponseWriter, r *http.Request, dbCon *sql.DB) {
auth, _ := getBasicAPIAuth(r)
if err := deleteAuthToken(dbCon, auth); err != nil {
handleError(w, r, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, r, http.StatusNoContent, nil)
}
func handleRecords(w http.ResponseWriter, r *http.Request, dbCon *sql.DB) {
auth, _ := getBasicAPIAuth(r)
if r.Method == "GET" {
records, err := getAllRecords(auth.Api_user, dbCon)
if err != nil {
handleError(w, r, http.StatusInternalServerError, err.Error())
return
}
bytes, err := json.MarshalIndent(records, "", " ")
if err != nil {
handleError(w, r, http.StatusInternalServerError, err.Error())
return
}
io.WriteString(w, string(bytes))
}
if r.Method == "POST" {
var record Record
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&record); err != nil {
handleError(w, r, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
record.User_id = auth.Api_user
ID, err := writeRecord(dbCon, record)
if err != nil {
handleError(w, r, http.StatusInternalServerError, err.Error())
return
}
record.ID = int(ID)
respondWithJSON(w, r, http.StatusCreated, record)
}
}
func handleSingleRecord(w http.ResponseWriter, r *http.Request, dbCon *sql.DB) {
vars := mux.Vars(r)
ID, err := strconv.Atoi(vars["id"])
if err != nil {
handleError(w, r, http.StatusNotFound, err.Error())
return
}
if r.Method == "GET" {
record, err := getRecord(dbCon, ID)
if err != nil {
handleError(w, r, http.StatusInternalServerError, err.Error())
return
}
bytes, err := json.MarshalIndent(record, "", " ")
if err != nil {
handleError(w, r, http.StatusInternalServerError, err.Error())
return
}
io.WriteString(w, string(bytes))
}
if r.Method == "DELETE" {
if err := deleteRecord(dbCon, ID); err != nil {
handleError(w, r, http.StatusNotFound, err.Error())
return
}
respondWithJSON(w, r, http.StatusNoContent, ID)
}
if r.Method == "PUT" {
var record Record
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&record); err != nil {
handleError(w, r, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
record.ID = ID
if err := updateRecord(dbCon, record); err != nil {
handleError(w, r, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, r, http.StatusOK, record)
}
}
func handleRecordTip(w http.ResponseWriter, r *http.Request, dbCon *sql.DB) {
vars := mux.Vars(r)
ID, err := strconv.Atoi(vars["id"])
if err != nil {
handleError(w, r, http.StatusNotFound, err.Error())
return
}
record, err := getRecord(dbCon, ID)
if err != nil {
handleError(w, r, http.StatusUnprocessableEntity, err.Error())
return
}
if record.Tip_sent != 0 {
handleError(w, r, http.StatusUnprocessableEntity, "You can only request a tip on the same record once.")
return
}
auth, _ := getBasicAPIAuth(r)
dbUser, err := getUserForId(dbCon, auth.Api_user)
if err != nil {
handleError(w, r, http.StatusNotFound, err.Error())
return
}
now := time.Now()
if dbUser.Last_tip != 0 {
secs := now.Unix()
interval, err := strconv.ParseInt(os.Getenv("TIP_INTERVAL"), 10, 64)
if err != nil {
handleError(w, r, http.StatusInternalServerError, err.Error())
return
}
if secs < (dbUser.Last_tip + interval) {
handleError(w, r, http.StatusUnprocessableEntity, "You can only request one Health Tip every 24 hours.")
return
}
}
mailErr := emailHealthTipRequest(dbUser, record)
if mailErr != nil {
handleError(w, r, http.StatusUnprocessableEntity, "Unable to send email. Please contact Coral Health.")
return
}
dbUser.Last_tip = now.Unix()
updateUserTipTime(dbCon, dbUser)
record.Tip_sent = 1
updateRecord(dbCon, record)
respondWithJSON(w, r, http.StatusOK, record)
}