-
Notifications
You must be signed in to change notification settings - Fork 1
/
user_handler.go
80 lines (62 loc) · 1.63 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
package main
import (
"net/http"
"time"
"github.com/bigroom/communicator"
"github.com/bigroom/vision/models"
"github.com/dgrijalva/jwt-go"
"github.com/paked/restrict"
log "github.com/sirupsen/logrus"
)
func registerHandler(w http.ResponseWriter, r *http.Request) {
coms := communicator.New(w)
username := r.FormValue("username")
password := r.FormValue("password")
email := r.FormValue("email")
log.WithFields(log.Fields{
"username": username,
"email": email,
}).Info("User is tryingt to register")
u, err := models.NewUser(username, password, email)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("Unable to connect to user")
coms.Error("Unable to create user")
return
}
coms.With(u).OK("user")
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
coms := communicator.New(w)
username := r.FormValue("username")
password := r.FormValue("password")
u, err := models.FetchUser("username", username)
if err != nil {
coms.Error("Unable to login user")
return
}
if err := u.Login(password); err != nil {
coms.Errorf("Unable to login %v", err)
return
}
claims := make(map[string]interface{})
claims["id"] = u.ID
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
ts, err := restrict.Token(claims)
if err != nil {
coms.Fail("Failure signing the token")
sentry.CaptureError(err, nil)
return
}
coms.With(ts).OK()
}
func secretHandler(w http.ResponseWriter, r *http.Request, t *jwt.Token) {
coms := communicator.New(w)
u, err := models.FetchUser("id", t.Claims["id"])
if err != nil {
coms.Error("That user does not exist!")
return
}
coms.With(u).OK()
}