Private
Public Access
1
0

Authentication: Implements authentication

This commit is contained in:
2023-06-18 13:11:51 -07:00
parent 53870e25a9
commit 6bbcf8cc63
8 changed files with 302 additions and 10 deletions

59
model/authtoken.go Normal file
View File

@@ -0,0 +1,59 @@
package model
import (
"encoding/base64"
"log"
"time"
"github.com/dgrijalva/jwt-go"
)
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.Printf("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.Printf("Error signing Jwt Token: %s", err)
return nil, &TokenGenerationError{"Error signing Jwt Token"}
}
return &AuthToken{
SignedToken: signedToken,
token: *token,
}, nil
}