-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
84 lines (74 loc) · 1.97 KB
/
jwt.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 (
"crypto/md5"
"encoding/json"
"errors"
"github.com/openware/rango/pkg/auth"
"net/http"
"strings"
)
type JWTService struct {
keys *auth.KeyStore
}
func NewJWTService(privKeyPath, pubKeyPath string) (*JWTService, error) {
keys, err := auth.LoadOrGenerateKeys(privKeyPath, pubKeyPath)
if err != nil {
return nil, err
}
return &JWTService{keys: keys}, nil
}
func (j *JWTService) GenearateJWT(u User) (string, error) {
return auth.ForgeToken("empty", u.Email, "empty", 0, j.keys.PrivateKey, nil)
}
func (j *JWTService) ParseJWT(jwt string) (auth.Auth, error) {
return auth.ParseAndValidate(jwt, j.keys.PublicKey)
}
type JWTParams struct {
Email string `json:"email"`
Password string `json:"password"`
}
func (u *UserService) JWT(w http.ResponseWriter, r *http.Request, jwtService *JWTService) {
params := &JWTParams{}
err := json.NewDecoder(r.Body).Decode(params)
if err != nil {
handleError(errors.New("could not read params"), w)
return
}
passwordDigest := md5.New().Sum([]byte(params.Password))
user, err := u.repository.Get(params.Email)
if err != nil {
handleError(err, w)
return
}
if string(passwordDigest) != user.PasswordDigest {
handleError(errors.New("invalid login params"), w)
return
}
token, err := jwtService.GenearateJWT(user)
if err != nil {
handleError(err, w)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(token))
}
type ProtectedHandler func(rw http.ResponseWriter, r *http.Request, u User)
func (j *JWTService) jwtAuth(users UserRepository, h ProtectedHandler) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
token := strings.TrimPrefix(authHeader, "Bearer ")
auth, err := j.ParseJWT(token)
if err != nil {
rw.WriteHeader(401)
rw.Write([]byte("unauthorized"))
return
}
user, err := users.Get(auth.Email)
if err != nil {
rw.WriteHeader(401)
rw.Write([]byte("unauthorized"))
return
}
h(rw, r, user)
}
}