-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
54 lines (45 loc) · 1.06 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
package auth
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
gauth "google.golang.org/api/oauth2/v2"
)
type Claims struct {
User *gauth.Userinfo `json:"user_info"`
jwt.StandardClaims
}
func New(key string) (*Auth, error) {
// if key == "" {
// return nil, fmt.Errorf("auth: key is empty")
// }
return &Auth{Key: []byte(key)}, nil
}
type Auth struct {
Key []byte
}
func (a *Auth) GetJWT(user *gauth.Userinfo) (string, error) {
expirationTime := time.Now().Add(10 * 24 * time.Hour)
claims := &Claims{
User: user,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
IssuedAt: time.Now().Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(a.Key)
}
func (a *Auth) ParseJWT(tokenStr string) (*Claims, error) {
claims := &Claims{}
tkn, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
return a.Key, nil
})
if err != nil {
return nil, err
}
if !tkn.Valid {
return nil, fmt.Errorf("failed to validate token")
}
return claims, nil
}