auth.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // username is the email of the user.
  28. func GenerateAccessToken(username string, userID int32, expirationTime time.Time, secret string) (string, error) {
  29. return generateToken(username, userID, AccessTokenAudienceName, expirationTime, []byte(secret))
  30. }
  31. // generateToken generates a jwt token.
  32. func generateToken(username string, userID int32, audience string, expirationTime time.Time, secret []byte) (string, error) {
  33. registeredClaims := jwt.RegisteredClaims{
  34. Issuer: Issuer,
  35. Audience: jwt.ClaimStrings{audience},
  36. IssuedAt: jwt.NewNumericDate(time.Now()),
  37. Subject: fmt.Sprint(userID),
  38. }
  39. if expirationTime.After(time.Now()) {
  40. registeredClaims.ExpiresAt = jwt.NewNumericDate(expirationTime)
  41. }
  42. // Declare the token with the HS256 algorithm used for signing, and the claims.
  43. token := jwt.NewWithClaims(jwt.SigningMethodHS256, &ClaimsMessage{
  44. Name: username,
  45. RegisteredClaims: registeredClaims,
  46. })
  47. token.Header["kid"] = KeyID
  48. // Create the JWT string.
  49. tokenString, err := token.SignedString(secret)
  50. if err != nil {
  51. return "", err
  52. }
  53. return tokenString, nil
  54. }