token.go 641 B

1234567891011121314151617181920212223242526272829303132
  1. package utils
  2. import (
  3. "context"
  4. "encoding/json"
  5. "github.com/golang-jwt/jwt/v4"
  6. )
  7. const Identify = "user_auth_id"
  8. func GetJwtToken(secretKey string, iat, seconds int64, uid int64) (string, error) {
  9. claims := make(jwt.MapClaims)
  10. claims["exp"] = iat + seconds
  11. claims["iat"] = iat
  12. claims[Identify] = uid
  13. token := jwt.New(jwt.SigningMethodHS256)
  14. token.Claims = claims
  15. return token.SignedString([]byte(secretKey))
  16. }
  17. func GetUid(ctx context.Context) int64 {
  18. if id, ok := ctx.Value(Identify).(json.Number); ok {
  19. i, _ := id.Int64()
  20. return i
  21. }
  22. if id, ok := ctx.Value(Identify).(float64); ok {
  23. return int64(id)
  24. }
  25. return 0
  26. }