2021-03-25 05:15:01 +00:00
|
|
|
package goscrobble
|
|
|
|
|
|
|
|
import (
|
2021-03-25 23:21:28 +00:00
|
|
|
"time"
|
2021-03-25 05:15:01 +00:00
|
|
|
|
|
|
|
"github.com/dgrijalva/jwt-go"
|
|
|
|
)
|
|
|
|
|
|
|
|
// JwtToken - Store token from .env
|
|
|
|
var JwtToken []byte
|
|
|
|
|
2021-03-25 23:21:28 +00:00
|
|
|
// JwtExpiry - Expiry in seconds
|
|
|
|
var JwtExpiry time.Duration
|
|
|
|
|
2021-03-29 07:56:34 +00:00
|
|
|
type CustomClaims struct {
|
|
|
|
Username string `json:"username"`
|
|
|
|
Email string `json:"email"`
|
2021-03-31 08:40:20 +00:00
|
|
|
Admin bool `json:"admin"`
|
2021-03-25 05:15:01 +00:00
|
|
|
jwt.StandardClaims
|
|
|
|
}
|
|
|
|
|
2021-03-29 07:56:34 +00:00
|
|
|
func generateJWTToken(user User) (string, error) {
|
|
|
|
atClaims := jwt.MapClaims{}
|
|
|
|
atClaims["sub"] = user.UUID
|
|
|
|
atClaims["username"] = user.Username
|
|
|
|
atClaims["email"] = user.Email
|
2021-03-31 08:40:20 +00:00
|
|
|
atClaims["admin"] = user.Admin
|
2021-03-29 07:56:34 +00:00
|
|
|
atClaims["iat"] = time.Now().Unix()
|
|
|
|
atClaims["exp"] = time.Now().Add(JwtExpiry).Unix()
|
|
|
|
at := jwt.NewWithClaims(jwt.SigningMethodHS512, atClaims)
|
|
|
|
token, err := at.SignedString(JwtToken)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return token, nil
|
|
|
|
}
|
|
|
|
|
2021-03-25 05:15:01 +00:00
|
|
|
// verifyToken - Verifies the JWT is valid
|
2021-03-29 07:56:34 +00:00
|
|
|
func verifyJWTToken(token string) (CustomClaims, error) {
|
2021-03-25 05:15:01 +00:00
|
|
|
// Initialize a new instance of `Claims`
|
2021-03-29 07:56:34 +00:00
|
|
|
claims := CustomClaims{}
|
|
|
|
_, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) {
|
2021-03-25 05:15:01 +00:00
|
|
|
return JwtToken, nil
|
|
|
|
})
|
|
|
|
|
2021-03-29 07:56:34 +00:00
|
|
|
// Verify Signature
|
2021-03-25 05:15:01 +00:00
|
|
|
if err != nil {
|
2021-03-29 07:56:34 +00:00
|
|
|
return claims, err
|
2021-03-25 05:15:01 +00:00
|
|
|
}
|
2021-03-29 07:56:34 +00:00
|
|
|
|
|
|
|
// Verify expiry
|
|
|
|
err = claims.Valid()
|
|
|
|
if err != nil {
|
|
|
|
return claims, err
|
2021-03-25 05:15:01 +00:00
|
|
|
}
|
|
|
|
|
2021-03-29 07:56:34 +00:00
|
|
|
return claims, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func getClaims(token *jwt.Token) CustomClaims {
|
|
|
|
claims, _ := token.Claims.(CustomClaims)
|
|
|
|
return claims
|
2021-03-25 05:15:01 +00:00
|
|
|
}
|