Add 'mock/' from commit '2041d3ce6377da091eca17cf9d8ad176a3024616'
git-subtree-dir: mock git-subtree-mainline:8216d7c706git-subtree-split:2041d3ce63
This commit is contained in:
59
mock/model/authtoken.go
Normal file
59
mock/model/authtoken.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type AuthToken struct {
|
||||
SignedToken string `json:"jwt"`
|
||||
token jwt.Token
|
||||
}
|
||||
|
||||
type TokenGenerationError struct {
|
||||
message string
|
||||
}
|
||||
|
||||
func (e *TokenGenerationError) Error() string {
|
||||
return e.message
|
||||
}
|
||||
|
||||
// Create a struct to hold your custom claims
|
||||
type customClaims struct {
|
||||
Username string `json:"username"`
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
const signingKey = "nDjYmTjoPrAGzuyhHz6Dq5bqcRrEZJc5Ls3SQcdylBI="
|
||||
|
||||
func NewAuthToken(username string) (*AuthToken, error) {
|
||||
claims := customClaims{
|
||||
Username: username,
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
ExpiresAt: time.Now().Add(time.Hour * 24 * 5).Unix(), // 5 days
|
||||
},
|
||||
}
|
||||
|
||||
// Create a new JWT token
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
if token == nil {
|
||||
log.Error().Msg("Error creating Jwt Token")
|
||||
return nil, &TokenGenerationError{"Error creating Jwt Token"}
|
||||
}
|
||||
|
||||
// Sign the token with the specified signing key
|
||||
decodedSigningKey, _ := base64.StdEncoding.DecodeString(signingKey)
|
||||
signedToken, err := token.SignedString(decodedSigningKey)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Error signing Jwt Token")
|
||||
return nil, &TokenGenerationError{"Error signing Jwt Token"}
|
||||
}
|
||||
|
||||
return &AuthToken{
|
||||
SignedToken: signedToken,
|
||||
token: *token,
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user