-
Notifications
You must be signed in to change notification settings - Fork 0
/
refresh_token.go
56 lines (46 loc) · 1.41 KB
/
refresh_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
48
49
50
51
52
53
54
55
56
package auth
import (
"time"
"github.com/mjah/jwt-auth/auth/jwt"
"github.com/mjah/jwt-auth/database"
"github.com/mjah/jwt-auth/errors"
"github.com/spf13/viper"
)
// RefreshTokenDetails holds the details required to refresh the access token.
type RefreshTokenDetails struct {
UserID uint
}
// RefreshToken handles the access token refresh.
func (details *RefreshTokenDetails) RefreshToken() (string, *errors.ErrorCode) {
// Get database connection
db, err := database.GetConnection()
if err != nil {
return "", errors.New(errors.DatabaseConnectionFailed, err.Error())
}
// Declare variables
user := &database.User{}
role := &database.Role{}
// Get user by ID
if err := db.Where("id = ?", details.UserID).First(user).Error; err != nil {
if database.IsRecordNotFoundError(err) {
return "", errors.New(errors.UserDoesNotExist, err.Error())
}
return "", errors.New(errors.DatabaseQueryFailed, err.Error())
}
// Get role name
if err := db.Where("id = ?", user.RoleID).First(&role).Error; err != nil {
return "", errors.New(errors.DatabaseQueryFailed, err.Error())
}
// Issue access token
atc := jwt.AccessTokenClaims{
Iat: time.Now().Unix(),
Exp: time.Now().Add(viper.GetDuration("token.access_token.expires")).Unix(),
UserID: user.ID,
Role: role.Role,
}
accessTokenString, errCode := atc.IssueAccessToken()
if errCode != nil {
return "", errCode
}
return accessTokenString, nil
}