-
Notifications
You must be signed in to change notification settings - Fork 0
/
refreshSession.go
75 lines (61 loc) · 1.53 KB
/
refreshSession.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
package pogifyapi
import (
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
gonanoid "github.com/matoous/go-nanoid"
)
// RefreshSession ...
func (s *server) refreshSession(c *gin.Context) {
sessionJWT := c.Query("sessionToken")
if sessionJWT == "" {
c.String(400, "missing query: sessionToken")
return
}
refreshToken := c.Query("refreshToken")
if refreshToken == "" {
c.String(400, "missing query: refreshToken")
return
}
token, err := jwt.Parse(sessionJWT, func(token *jwt.Token) (interface{}, error) {
return s.jwt.secret, nil
})
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorExpired == 0 {
c.AbortWithError(400, err)
return
}
}
sessionID := token.Claims.(jwt.MapClaims)["session"].(string)
newRefreshToken, err := gonanoid.ID(64)
val, err := s.redis.verifyAndSetNewRefreshToken(sessionID, refreshToken, newRefreshToken)
if err != nil {
c.AbortWithError(500, err)
return
}
switch val {
case -1:
c.String(400, "refresh token expired")
case 0:
c.String(400, "invalid refreshToken")
case 1:
claims := sessionJwtClaims{
sessionID,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour).Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenSign, err := token.SignedString(s.jwt.secret)
if err != nil {
c.AbortWithError(500, err)
return
}
c.JSON(200, gin.H{
"session": sessionID,
"refreshToken": newRefreshToken,
"token": tokenSign,
"expiresIn": time.Hour.Seconds(),
})
}
}