-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.go
84 lines (70 loc) · 1.8 KB
/
data.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 (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
)
type UserServiceAuthenticator struct {
endpoint string
issuer string
accessTokenExpiration int
signingKey []byte
}
type ServiceUser struct {
Id int `json:"id"`
Username string `json:"username"`
EncryptedPassword string `json:"encrypted_password"`
}
func NewUserServiceAuthenticator(
endpoint string,
issuer string,
accessTokenExpiration int,
signingKey []byte,
) *UserServiceAuthenticator {
return &UserServiceAuthenticator{
endpoint: endpoint,
issuer: issuer,
accessTokenExpiration: accessTokenExpiration,
signingKey: signingKey,
}
}
func (a *UserServiceAuthenticator) Authenticate(credentials Credentials) (*Tokens, error) {
resp, err := http.Get(fmt.Sprintf("http://%s/%s", a.endpoint, credentials["username"]))
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, ErrUnauthorized
}
user := new(ServiceUser)
err = json.NewDecoder(resp.Body).Decode(user)
if err != nil {
return nil, err
}
err = bcrypt.CompareHashAndPassword([]byte(user.EncryptedPassword), []byte(credentials["password"]))
if err != nil {
return nil, ErrUnauthorized
}
now := time.Now()
claims := &jwt.StandardClaims{
IssuedAt: now.Unix(),
ExpiresAt: now.Add(time.Duration(a.accessTokenExpiration)).Unix(),
Issuer: a.issuer,
Subject: string(user.Id),
}
jwt := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := jwt.SignedString(a.signingKey)
if err != nil {
return nil, err
}
return &Tokens{
AccessToken: &Token{
Token: tokenString,
ExpiresIn: a.accessTokenExpiration,
},
}, nil
}