-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_utils.go
111 lines (100 loc) · 3.12 KB
/
auth_utils.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package routes
import (
"github.com/golang-jwt/jwt/v5"
"github.com/kayprogrammer/socialnet-v6/config"
"github.com/kayprogrammer/socialnet-v6/models"
"github.com/kayprogrammer/socialnet-v6/utils"
"github.com/pborman/uuid"
"gorm.io/gorm"
"log"
"time"
)
var cfg = config.GetConfig()
var SECRETKEY = []byte(cfg.SecretKey)
type AccessTokenPayload struct {
UserId uuid.UUID `json:"user_id"`
Username string `json:"username"`
jwt.RegisteredClaims
}
type RefreshTokenPayload struct {
Data string `json:"data"`
jwt.RegisteredClaims
}
func GenerateAccessToken(userId uuid.UUID, username string) string {
expirationTime := time.Now().Add(time.Duration(cfg.AccessTokenExpireMinutes) * time.Minute)
payload := AccessTokenPayload{
UserId: userId,
Username: username,
RegisteredClaims: jwt.RegisteredClaims{
// In JWT, the expiry time is expressed as unix milliseconds
ExpiresAt: jwt.NewNumericDate(expirationTime),
},
}
// Declare the token with the algorithm used for signing, and the claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, payload)
// Create the JWT string
tokenString, err := token.SignedString(SECRETKEY)
if err != nil {
// If there is an error in creating the JWT return an internal server error
log.Fatal("Error Generating Access token: ", err)
}
return tokenString
}
func GenerateRefreshToken() string {
expirationTime := time.Now().Add(time.Duration(cfg.RefreshTokenExpireMinutes) * time.Minute)
payload := RefreshTokenPayload{
Data: utils.GetRandomString(10),
RegisteredClaims: jwt.RegisteredClaims{
// In JWT, the expiry time is expressed as unix milliseconds
ExpiresAt: jwt.NewNumericDate(expirationTime),
},
}
// Declare the token with the algorithm used for signing, and the claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, payload)
// Create the JWT string
tokenString, err := token.SignedString(SECRETKEY)
if err != nil {
// If there is an error in creating the JWT return an internal server error
log.Fatal("Error Generating Refresh token: ", err)
}
return tokenString
}
func DecodeAccessToken(token string, db *gorm.DB) (*models.User, *string) {
claims := &AccessTokenPayload{}
tkn, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
return SECRETKEY, nil
})
tokenErr := "Auth Token is Invalid or Expired!"
if err != nil {
return nil, &tokenErr
}
if !tkn.Valid {
return nil, &tokenErr
}
user := models.User{Access: &token}
// Fetch User model object
result := db.Where(user).Joins("CityObj").Joins("CityObj.RegionObj").Joins("CityObj.CountryObj").Joins("AvatarObj").Take(&user, claims.UserId)
if result.Error != nil {
return nil, &tokenErr
}
return &user, nil
}
func DecodeRefreshToken(token string) bool {
claims := &RefreshTokenPayload{}
tkn, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
return SECRETKEY, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
log.Println("JWT Error: ", "Invalid Signature")
} else {
log.Println("JWT Error: ", err)
}
return false
}
if !tkn.Valid {
log.Println("Invalid Refresh Token")
return false
}
return true
}