8 "immae.eu/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front/db"
10 "github.com/dgrijalva/jwt-go"
11 "github.com/gin-gonic/gin"
17 type JwtClaims struct {
18 Authorized bool `json:"authorized"`
19 Subject int64 `json:"sub,omitempty"`
23 func VerifyJwtToken(token string) (JwtClaims, error) {
24 if len(JWT_SECRET) == 0 {
25 return JwtClaims{}, fmt.Errorf("not initialized jwt secret")
28 t, err := jwt.ParseWithClaims(token, &JwtClaims{}, func(t *jwt.Token) (interface{}, error) {
29 if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
30 return nil, fmt.Errorf("Unexpected signing method: %v", t.Header["alg"])
33 return JWT_SECRET, nil
36 claims, ok := t.Claims.(*JwtClaims)
38 if !ok || !t.Valid || err != nil {
39 return JwtClaims{}, fmt.Errorf("invalid token (err: %v, claimsok: %v)", err, ok)
45 func SignJwt(claims JwtClaims) (string, error) {
46 if len(JWT_SECRET) == 0 {
47 return "", fmt.Errorf("not initialized jwt secret")
50 token := jwt.NewWithClaims(jwt.SigningMethodHS256, &claims)
52 return token.SignedString(JWT_SECRET)
55 func CreateJwtToken(userId int64) (string, error) {
60 ExpiresAt: time.Now().Add(time.Hour * 24 * 7).Unix(),
64 return SignJwt(claims)
67 func GetBearerToken(header string) (string, error) {
68 const prefix = "Bearer "
70 if !strings.HasPrefix(header, prefix) {
71 return "", fmt.Errorf("invalid authorization token")
74 return header[len(prefix):], nil
77 func JwtAuth(c *gin.Context) *Error {
78 token, err := GetBearerToken(c.GetHeader("Authorization"))
80 return &Error{NotAuthorized, "not authorized", err}
83 claims, err := VerifyJwtToken(token)
85 return &Error{NotAuthorized, "not authorized", err}
88 user, err := db.GetUserById(claims.Subject)
90 return &Error{NotAuthorized, "not authorized", err}
94 c.Set("claims", claims)
99 func GetClaims(c *gin.Context) JwtClaims {
100 claims, _ := c.Get("claims")
102 return claims.(JwtClaims)