-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes_auth.go
84 lines (75 loc) · 1.87 KB
/
routes_auth.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
package main
import (
"fmt"
"github.com/golang-jwt/jwt/v4"
"log"
"net/http"
"time"
)
func (s *server) handleIndex() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to Golfix")
}
}
func (s *server) handleTokenCreate() http.HandlerFunc {
type request struct {
Username string `json:"username"`
Password string `json:"password"`
}
type response struct {
Token string `json:"token"`
}
type responseError struct {
Error string `json:"error"`
}
return func(w http.ResponseWriter, r *http.Request) {
// Parsing login body
req := request{}
err := s.decode(w, r, &req)
if err != nil {
msg := fmt.Sprintf("Cannot parse login body. err=%v", err)
log.Println(msg)
s.respond(w, r, responseError{
Error: msg,
}, http.StatusBadRequest)
return
}
// Check credentials
found, err := s.store.FindUser(req.Username, req.Password)
if err != nil {
msg := fmt.Sprintf("Cannot find user. err=%v", err)
s.respond(w, r, responseError{
Error: msg,
}, http.StatusInternalServerError)
return
}
if !found {
s.respond(w, r, responseError{
Error: "Invalid credentials",
}, http.StatusUnauthorized)
return
}
if req.Username != "golang" || req.Password != "rocks" {
s.respond(w, r, responseError{
Error: "Invalid credentials",
}, http.StatusUnauthorized)
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": req.Username,
"exp": time.Now().Add(time.Hour * time.Duration(1)).Unix(),
"iat": time.Now().Unix(),
})
tokenStr, err := token.SignedString([]byte(JwtAppKey))
if err != nil {
msg := fmt.Sprintf("Cannot generate JWT. err=%v", err)
s.respond(w, r, responseError{
Error: msg,
}, http.StatusInternalServerError)
return
}
s.respond(w, r, response{
Token: tokenStr,
}, http.StatusOK)
}
}