Last active
May 31, 2018 15:39
-
-
Save ahmadshah/29cf4284de74ab1af3fbef6975073050 to your computer and use it in GitHub Desktop.
Golang JWT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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