This repository has been archived by the owner on Jan 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
145 lines (121 loc) · 3.44 KB
/
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package server
import (
"encoding/json"
"errors"
"io/ioutil"
"log"
"net/http"
"regexp"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
)
type Auth struct {
privateKey []byte
publicKey []byte
tokenExpiry time.Duration
}
func NewAuth(privateKey string, publicKey string, tokenExpiry int) *Auth {
// todo: error handling (when keys not present)
privKey, err := ioutil.ReadFile(privateKey)
if err != nil {
log.Fatal(err)
}
pubKey, err := ioutil.ReadFile(publicKey)
if err != nil {
log.Fatal(err)
}
return &Auth{privKey, pubKey, time.Duration(tokenExpiry)}
}
func (auth *Auth) Authenticate(user *User, pwd string) (string, error) {
err := bcrypt.CompareHashAndPassword(user.PasswordHash, []byte(pwd))
if err != nil {
return "", errors.New("invalid password")
}
token, err := auth.createToken(user)
if err != nil {
return "", errors.New("token could not created")
}
return token, nil
}
func (auth *Auth) createToken(user *User) (string, error) {
token := jwt.New(jwt.GetSigningMethod("HS256"))
token.Claims["user"] = user
token.Claims["exp"] = time.Now().Add(time.Minute * auth.tokenExpiry).Unix()
return token.SignedString(auth.privateKey)
}
func (auth *Auth) getToken(r *http.Request) (*jwt.Token, error) {
token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
return auth.privateKey, nil
})
if err != nil {
return nil, err
}
return token, nil
}
func (auth *Auth) ValidateToken(context *HandlerContext) bool {
token, err := auth.getToken(context.Request)
if err != nil {
return false
}
return token.Valid
}
func (auth *Auth) AuthenticateUser(context *HandlerContext) (string, error) {
token, err := auth.getToken(context.Request)
if err != nil || !token.Valid {
return "", errNotAuthenticated
}
user, err := auth.extractUser(token.Raw)
if err != nil {
return "", err
}
context.User = user
// create new token -> to reset exp time
newToken, err := auth.createToken(user)
if err != nil {
return "", err
}
return newToken, nil
}
func (auth *Auth) extractUser(token string) (*User, error) {
// todo: rethink: how to get user struct out of token?
// this seems lika a ridiculous solution:
// 1. get part of token, which contains claims (middle part):
// eyJhb[...]XVCJ9.eyJle[...]IifX0.4ZEVb[...]xc8ig -> eyJle[...]IifX0
// 2. decode that segment using jwt -> []byte
// 3. []byte to string:
// {"exp":1414463656,"user":{"id":1,"username":"admin","first_name":"","last_name":"","email":""}}
// 4. extract user json part (using regexp):
// {"id":1,"username":"admin","first_name":"","last_name":"","email":""}
// 5. unmarshal
tokenParts := strings.Split(token, ".")
if len(tokenParts) != 3 {
return nil, errors.New("extract user from token: invalid raw token")
}
tokenClaimsPart := tokenParts[1]
claimsData, err := jwt.DecodeSegment(tokenClaimsPart)
if err != nil {
return nil, err
}
jsonClaims := string(claimsData)
re := regexp.MustCompile(`"user":(.*)?}`)
matches := re.FindStringSubmatch(jsonClaims)
if len(matches) != 2 {
return nil, errors.New("extract user from token: invalid json data")
}
jsonUser := matches[1]
var user *User
err = json.Unmarshal([]byte(jsonUser), &user)
if err != nil {
return nil, err
}
return user, nil
}
func (auth *Auth) GeneratePasswordHash(pwd string) ([]byte, error) {
pwdHash, err := bcrypt.GenerateFromPassword([]byte(pwd), BcryptCost)
if err != nil {
return nil, err
}
return pwdHash, nil
}