]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git/blame - api/auth_jwt.go
initial commit
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git] / api / auth_jwt.go
CommitLineData
7a9e5112 1package api
2
3import (
4 "fmt"
5 "strings"
6 "time"
7
8 "immae.eu/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front/db"
9
10 "github.com/dgrijalva/jwt-go"
11 "github.com/gin-gonic/gin"
12)
13
14// Static secret.
15var JWT_SECRET []byte
16
17type JwtClaims struct {
18 Authorized bool `json:"authorized"`
19 Subject int64 `json:"sub,omitempty"`
20 jwt.StandardClaims
21}
22
23func SetJwtSecretKey(secret string) {
24 JWT_SECRET = []byte(secret)
25}
26
27func VerifyJwtToken(token string) (JwtClaims, error) {
28 if len(JWT_SECRET) == 0 {
29 return JwtClaims{}, fmt.Errorf("not initialized jwt secret")
30 }
31
32 t, err := jwt.ParseWithClaims(token, &JwtClaims{}, func(t *jwt.Token) (interface{}, error) {
33 if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
34 return nil, fmt.Errorf("Unexpected signing method: %v", t.Header["alg"])
35 }
36
37 return JWT_SECRET, nil
38 })
39
40 claims, ok := t.Claims.(*JwtClaims)
41
42 if !ok || !t.Valid || err != nil {
43 return JwtClaims{}, fmt.Errorf("invalid token (err: %v, claimsok: %v)", err, ok)
44 }
45
46 return *claims, nil
47}
48
49func SignJwt(claims JwtClaims) (string, error) {
50 if len(JWT_SECRET) == 0 {
51 return "", fmt.Errorf("not initialized jwt secret")
52 }
53
54 token := jwt.NewWithClaims(jwt.SigningMethodHS256, &claims)
55
56 return token.SignedString(JWT_SECRET)
57}
58
59func CreateJwtToken(userId int64) (string, error) {
60 claims := JwtClaims{
61 false,
62 userId,
63 jwt.StandardClaims{
64 ExpiresAt: time.Now().Add(time.Hour * 24).Unix(),
65 },
66 }
67
68 return SignJwt(claims)
69}
70
71func GetBearerToken(header string) (string, error) {
72 const prefix = "Bearer "
73
74 if !strings.HasPrefix(header, prefix) {
75 return "", fmt.Errorf("invalid authorization token")
76 }
77
78 return header[len(prefix):], nil
79}
80
81func JwtAuth(c *gin.Context) *Error {
82 token, err := GetBearerToken(c.GetHeader("Authorization"))
83 if err != nil {
84 return &Error{NotAuthorized, "not authorized", err}
85 }
86
87 claims, err := VerifyJwtToken(token)
88 if err != nil {
89 return &Error{NotAuthorized, "not authorized", err}
90 }
91
92 user, err := db.GetUserById(claims.Subject)
93 if err != nil {
94 return &Error{NotAuthorized, "not authorized", err}
95 }
96
97 c.Set("user", *user)
98 c.Set("claims", claims)
99
100 return nil
101}
102
103func GetClaims(c *gin.Context) JwtClaims {
104 claims, _ := c.Get("claims")
105
106 return claims.(JwtClaims)
107}