package objects
import (
"errors"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
type JWT struct {
secretKey []byte
refreshKey []byte
tokenExpire time.Duration
}
func NewJWT(secretKey, refreshKey string, tokenExpire time.Duration) *JWT {
return &JWT{
secretKey: []byte(secretKey),
refreshKey: []byte(refreshKey),
tokenExpire: tokenExpire,
}
}
type Claims struct {
UserID int64 `json:"userid"`
jwt.StandardClaims
}
func (j *JWT) GenerateToken(userID int64) (string, error) {
// Create the Claims
claims := Claims{
UserID: userID,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(j.tokenExpire).Unix(),
Issuer: "my_app",
},
}
// Create the token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Sign the token with the secret key
tokenString, err := token.SignedString(j.secretKey)
if err != nil {
return "", err
}
return tokenString, nil
}
func (j *JWT) GenerateRefreshToken() (string, error) {
// Create the Claims
claims := jwt.StandardClaims{
ExpiresAt: time.Now().Add(24 * time.Hour).Unix(), // Refresh token will expire after 1 day
Issuer: "my_app",
}
// Create the token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Sign the token with the refresh key
refreshTokenString, err := token.SignedString(j.refreshKey)
if err != nil {
return "", err
}
return refreshTokenString, nil
}
func (j *JWT) ValidateToken(tokenString string) (int64, error) {
// Parse the token
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return j.secretKey, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
return 0, errors.New("invalid token signature")
}
return 0, err
}
// Check if the token is valid
claims, ok := token.Claims.(*Claims)
if !ok || !token.Valid {
return 0, errors.New("invalid token claims")
}
return claims.UserID, nil
}
func (j *JWT) ParseToken(tokenString string) (*Claims, error) {
// Parse the token
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return j.secretKey, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
return nil, errors.New("invalid token signature")
}
return nil, err
}
// Check if the token is valid
claims, ok := token.Claims.(*Claims)
if !ok || !token.Valid {
return nil, errors.New("invalid token claims")
}
return claims, nil
}