-
Notifications
You must be signed in to change notification settings - Fork 2
/
authentication.go
86 lines (71 loc) · 2.28 KB
/
authentication.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
package api
import (
"errors"
"net/http"
"strconv"
"strings"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/julienschmidt/httprouter"
)
type authenticateRequest struct {
UserName string `json:"username"`
Password string `json:"password"`
}
type authenticateResponse struct {
Token string `json:"token"`
}
func (h apiHandler) postAuthenticate(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
var authRequest authenticateRequest
if err := readJSONFromRequest(req, &authRequest); err != nil {
h.JSON(resp, http.StatusBadRequest, err.Error())
return
}
user, err := h.model.Users.Authenticate(authRequest.UserName, authRequest.Password)
if err != nil {
h.JSON(resp, http.StatusUnauthorized, err.Error())
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 14 * 24).Unix(),
IssuedAt: time.Now().Unix(),
Subject: strconv.FormatInt(user.ID, 10),
})
// Always sign using the 0'th key
tokenStr, err := token.SignedString([]byte(h.cfg.SecureKeys[0]))
if err != nil {
h.JSON(resp, http.StatusInternalServerError, err.Error())
}
h.JSON(resp, http.StatusOK, authenticateResponse{Token: tokenStr})
}
func (h apiHandler) requireAuthentication(handler httprouter.Handle) httprouter.Handle {
return func(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
authHeader := req.Header.Get("Authorization")
if authHeader == "" {
h.JSON(resp, http.StatusUnauthorized, "Authorization header missing")
return
}
authHeaderParts := strings.Split(authHeader, " ")
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
h.JSON(resp, http.StatusUnauthorized, "Authorization header must be in the form 'Bearer {token}'")
return
}
tokenStr := authHeaderParts[1]
// Try each key when validating the token
var lastErr error
for _, key := range h.cfg.SecureKeys {
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
if token.Method != jwt.SigningMethodHS256 {
return nil, errors.New("Incorrect signing method")
}
return []byte(key), nil
})
if err == nil && token.Valid {
handler(resp, req, p)
return
}
lastErr = err
}
h.JSON(resp, http.StatusUnauthorized, lastErr.Error())
}
}