auth.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package auth
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/golang-jwt/jwt/v4"
  6. )
  7. const (
  8. // issuer is the issuer of the jwt token.
  9. Issuer = "memos"
  10. // Signing key section. For now, this is only used for signing, not for verifying since we only
  11. // have 1 version. But it will be used to maintain backward compatibility if we change the signing mechanism.
  12. KeyID = "v1"
  13. // AccessTokenAudienceName is the audience name of the access token.
  14. AccessTokenAudienceName = "user.access-token"
  15. AccessTokenDuration = 7 * 24 * time.Hour
  16. // CookieExpDuration expires slightly earlier than the jwt expiration. Client would be logged out if the user
  17. // cookie expires, thus the client would always logout first before attempting to make a request with the expired jwt.
  18. CookieExpDuration = AccessTokenDuration - 1*time.Minute
  19. // AccessTokenCookieName is the cookie name of access token.
  20. AccessTokenCookieName = "memos.access-token"
  21. )
  22. type ClaimsMessage struct {
  23. Name string `json:"name"`
  24. jwt.RegisteredClaims
  25. }
  26. // GenerateAccessToken generates an access token.
  27. func GenerateAccessToken(username string, userID int32, expirationTime time.Time, secret []byte) (string, error) {
  28. return generateToken(username, userID, AccessTokenAudienceName, expirationTime, secret)
  29. }
  30. // generateToken generates a jwt token.
  31. func generateToken(username string, userID int32, audience string, expirationTime time.Time, secret []byte) (string, error) {
  32. registeredClaims := jwt.RegisteredClaims{
  33. Issuer: Issuer,
  34. Audience: jwt.ClaimStrings{audience},
  35. IssuedAt: jwt.NewNumericDate(time.Now()),
  36. Subject: fmt.Sprint(userID),
  37. }
  38. if !expirationTime.IsZero() {
  39. registeredClaims.ExpiresAt = jwt.NewNumericDate(expirationTime)
  40. }
  41. // Declare the token with the HS256 algorithm used for signing, and the claims.
  42. token := jwt.NewWithClaims(jwt.SigningMethodHS256, &ClaimsMessage{
  43. Name: username,
  44. RegisteredClaims: registeredClaims,
  45. })
  46. token.Header["kid"] = KeyID
  47. // Create the JWT string.
  48. tokenString, err := token.SignedString(secret)
  49. if err != nil {
  50. return "", err
  51. }
  52. return tokenString, nil
  53. }