-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken.go
More file actions
59 lines (51 loc) · 1.56 KB
/
token.go
File metadata and controls
59 lines (51 loc) · 1.56 KB
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
// Package auth provides utility functions for password authentication
// and JWT access control.
package auth
import (
"errors"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/flick-web/dispatch"
)
// TokenSigner is an object providing methods for creating and validating JWTs.
type TokenSigner struct {
secret []byte
// Issuer is the value of the issuer field in the standard claims attached
// to tokens generated by this signer.
Issuer string
}
// NewTokenSigner generates a new TokenSigner object with the specified issuer
// and secret token.
func NewTokenSigner(issuer string, secret []byte) *TokenSigner {
return &TokenSigner{
secret: secret,
Issuer: issuer,
}
}
// CreateToken creates a JWT token for a user to use for authentication.
func (ts *TokenSigner) CreateToken(username string) (string, error) {
claims := dispatch.Claims{
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 24).Unix(),
NotBefore: time.Now().Unix(),
Issuer: ts.Issuer,
Subject: username,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(ts.secret))
}
// ParseToken verifies a token and returns its claims.
func (ts *TokenSigner) ParseToken(tokenStr string) (*dispatch.Claims, error) {
token, err := jwt.ParseWithClaims(tokenStr, &dispatch.Claims{}, func(t *jwt.Token) (interface{}, error) {
return []byte(ts.secret), nil
})
if err != nil {
return nil, err
}
claims, ok := token.Claims.(*dispatch.Claims)
if !ok {
return nil, errors.New("Incorrect claims type")
}
return claims, nil
}