token_generator.go 624 B

123456789101112131415161718192021222324252627282930313233
  1. package rest
  2. import (
  3. "time"
  4. "git.ali33.ru/fcg-xvii/go-tools/json"
  5. "github.com/dgrijalva/jwt-go"
  6. )
  7. func NewTokenGenerator(secret string) *TokenGenerator {
  8. return &TokenGenerator{
  9. secret: secret,
  10. }
  11. }
  12. type TokenGenerator struct {
  13. secret string
  14. }
  15. func (s *TokenGenerator) Generate(m json.Map, expire int64) (string, error) {
  16. token := jwt.New(jwt.SigningMethodHS256)
  17. claims := token.Claims.(jwt.MapClaims)
  18. for key, val := range m {
  19. claims[key] = val
  20. }
  21. if expire > 0 {
  22. claims["exp"] = time.Now().Add(time.Minute * 30).Unix()
  23. }
  24. tokenString, err := token.SignedString(s.secret)
  25. return tokenString, err
  26. }