jwt.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package user
  2. import (
  3. "fmt"
  4. enteJWT "github.com/ente-io/museum/ente/jwt"
  5. "github.com/ente-io/museum/pkg/utils/time"
  6. "github.com/ente-io/stacktrace"
  7. "github.com/golang-jwt/jwt"
  8. )
  9. // jwt token validity = 1 day
  10. const ValidForDays = 1
  11. func (c *UserController) GetJWTToken(userID int64, scope enteJWT.ClaimScope) (string, error) {
  12. // Create a new token object, specifying signing method and the claims
  13. // you would like it to contain.
  14. token := jwt.NewWithClaims(jwt.SigningMethodHS256, &enteJWT.WebCommonJWTClaim{
  15. UserID: userID,
  16. ExpiryTime: time.NDaysFromNow(1),
  17. ClaimScope: &scope,
  18. })
  19. // Sign and get the complete encoded token as a string using the secret
  20. tokenString, err := token.SignedString(c.JwtSecret)
  21. if err != nil {
  22. return "", stacktrace.Propagate(err, "")
  23. }
  24. return tokenString, nil
  25. }
  26. func (c *UserController) ValidateJWTToken(jwtToken string, scope enteJWT.ClaimScope) (int64, error) {
  27. token, err := jwt.ParseWithClaims(jwtToken, &enteJWT.WebCommonJWTClaim{}, func(token *jwt.Token) (interface{}, error) {
  28. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  29. return nil, stacktrace.Propagate(fmt.Errorf("unexpected signing method: %v", token.Header["alg"]), "")
  30. }
  31. return c.JwtSecret, nil
  32. })
  33. if err != nil {
  34. return -1, stacktrace.Propagate(err, "JWT parsed failed")
  35. }
  36. claims, ok := token.Claims.(*enteJWT.WebCommonJWTClaim)
  37. if ok && token.Valid {
  38. if claims.GetScope() != scope {
  39. return -1, stacktrace.Propagate(fmt.Errorf("recived claimScope %s is different than expected scope: %s", claims.GetScope(), scope), "")
  40. }
  41. return claims.UserID, nil
  42. }
  43. return -1, stacktrace.Propagate(err, "JWT claim failed")
  44. }