-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
69 lines (52 loc) · 1.37 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package auth
import (
"time"
"github.com/gin-gonic/gin"
"../../db"
"github.com/dgrijalva/jwt-go"
)
const authHeader string = "Bearer "
type membershipToken struct {
User db.UsersList
jwt.StandardClaims
}
var signKey []byte = []byte("MyCLoud#2020#sErver")
func GenerateToken(user db.UsersList) string {
tokenResult := "TOKEN_ERR"
tokenClaim := membershipToken{
user,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 48).Unix(),
Issuer: "MyCloud",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, tokenClaim)
if tokenStr, tokenStrErr := token.SignedString(signKey); tokenStrErr == nil {
tokenResult = tokenStr
}
return tokenResult
}
func DecodeToken(tokenString string) (bool, db.UsersList) {
var result db.UsersList
var hasError = true
token, err := jwt.ParseWithClaims(tokenString, &membershipToken{}, func(token *jwt.Token) (interface{}, error) {
return signKey, nil
})
if err == nil {
if claims, ok := token.Claims.(*membershipToken); ok && token.Valid {
result = claims.User
hasError = false
}
}
return hasError, result
}
func GetHTTPToken(c *gin.Context) db.UsersList {
var result db.UsersList
if authorization, err := c.Cookie("mc_tok"); err == nil {
tokenStr := authorization[len(authHeader):]
if hasError, decUserToken := DecodeToken(tokenStr); !hasError {
result = decUserToken
}
}
return result
}