Skip to content

Instantly share code, notes, and snippets.

@ahmadshah
Last active May 31, 2018 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmadshah/29cf4284de74ab1af3fbef6975073050 to your computer and use it in GitHub Desktop.
Save ahmadshah/29cf4284de74ab1af3fbef6975073050 to your computer and use it in GitHub Desktop.
Golang JWT
package auth
import (
"errors"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/jinzhu/gorm"
)
const (
DAYSTOEXPIRE = 10
)
type JWT interface {
GenerateToken(UUID string) *Token
ParseToken(tokenString string) (*Token, error)
}
type AuthService struct {
DB *gorm.DB
SigningKey []byte
Issuer string
}
type customClaims struct {
UUID string `json:"id"`
jwt.StandardClaims
}
type Token struct {
TokenString string `json:"token"`
ExpiredAt int64 `json:"expired_at"`
IssuedAt int64 `json:"issued_at;omitempty"`
Issuer string `json:"issuer;omitempty"`
UUID string `json:"-"`
}
var (
InvalidTokenError = errors.New("invalid_auth_token")
)
func (auth AuthService) GenerateToken(UUID string) *Token {
expiredAt := time.Now().Add(time.Hour * 24 * DAYSTOEXPIRE).Unix()
claims := customClaims{
UUID,
jwt.StandardClaims{
ExpiresAt: expiredAt,
IssuedAt: jwt.TimeFunc().Unix(),
Issuer: auth.Issuer,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ts, _ := token.SignedString(auth.SigningKey)
return &Token{
TokenString: ts,
ExpiredAt: expiredAt,
}
}
func (auth AuthService) ParseToken(tokenString string) (*Token, error) {
token, err := jwt.ParseWithClaims(tokenString, &customClaims{}, func(token *jwt.Token) (interface{}, error) {
return auth.SigningKey, nil
})
if err != nil {
return nil, InvalidTokenError
}
if claims, ok := token.Claims.(*customClaims); ok && token.Valid {
t := &Token{
TokenString: tokenString,
ExpiredAt: claims.StandardClaims.ExpiresAt,
IssuedAt: claims.StandardClaims.IssuedAt,
Issuer: claims.StandardClaims.Issuer,
UUID: claims.UUID,
}
return t, nil
} else {
return nil, InvalidTokenError
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment