-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_handler.go
95 lines (74 loc) · 2.03 KB
/
user_handler.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
package users
import (
"encoding/json"
"strconv"
"github.com/valyala/fasthttp"
"github.com/zoommix/fasthttp_template/utils"
)
type authData struct {
Email string `json:"email"`
Password string `json:"password"`
}
// ShowUsersHandler ...
func ShowUsersHandler(c *fasthttp.RequestCtx) {
// You can fetch current user object like that:
// currentUser := c.UserValue("user").(*User)
// currentUser = currentUser.Reload()
// utils.LogError(fmt.Sprintf("%+v", currentUser))
id, _ := strconv.Atoi(c.UserValue("id").(string))
u, err := FindUser(id)
if err != nil {
utils.LogError("Unable to find user: ", err)
utils.RenderNotFoundError(c, err.Error())
return
}
utils.SetStatus(c, fasthttp.StatusOK)
utils.WriteJSON(c, UserToJSON(u))
}
// CreateUserHandler ...
func CreateUserHandler(c *fasthttp.RequestCtx) {
user := userParams(c)
validationErrors := user.Validate()
if len(validationErrors) > 0 {
utils.RenderValidationErrors(c, validationErrors)
return
}
user, err := CreateUser(user)
if err != nil {
utils.LogError("Unable to create user", err)
utils.RenderInternalError(c, err.Error())
return
}
utils.SetStatus(c, fasthttp.StatusCreated)
utils.WriteJSON(c, UserToJSON(user))
}
func userParams(c *fasthttp.RequestCtx) *User {
params := NewUserJSON()
json.Unmarshal(c.PostBody(), ¶ms)
u := &User{
Email: params.Email,
FirstName: params.FirstName,
LastName: params.LastName,
Password: params.Password,
}
return u
}
// Authenticate ...
func Authenticate(c *fasthttp.RequestCtx) {
creds := authParams(c)
encodedPass := EncodePassword(creds.Password)
user, err := FindUserByEmail(creds.Email)
if err != nil || user.PasswordDigest != encodedPass {
utils.LogError("invalid token or password", err)
utils.RenderUnauthorized(c, "invalid token or password")
return
}
user.GenerateJWT()
utils.SetStatus(c, fasthttp.StatusOK)
utils.WriteJSON(c, UserToJSON(user))
}
func authParams(c *fasthttp.RequestCtx) authData {
data := &authData{}
json.Unmarshal(c.PostBody(), &data)
return *data
}