-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
47 lines (37 loc) · 1.03 KB
/
token.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
package org
import (
"errors"
"strconv"
"time"
"github.com/cristianuser/go-bun-webserver/bunapp"
"github.com/dgrijalva/jwt-go"
)
func decodeUserToken(app *bunapp.App, jwtToken string) (uint64, error) {
if len(jwtToken) == 0 {
return 0, errors.New("token is missing or empty")
}
token, err := jwt.ParseWithClaims(jwtToken, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(app.Config().SecretKey), nil
})
if err != nil {
return 0, err
}
if !token.Valid {
return 0, errors.New("invalid token")
}
claims := token.Claims.(*jwt.StandardClaims)
id, err := strconv.ParseUint(claims.Subject, 10, 64)
if err != nil {
return 0, err
}
return id, nil
}
func CreateUserToken(app *bunapp.App, userID uint64, ttl time.Duration) (string, error) {
claims := &jwt.StandardClaims{
Subject: strconv.FormatUint(userID, 10),
ExpiresAt: time.Now().Add(ttl).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
key := []byte(app.Config().SecretKey)
return token.SignedString(key)
}