feat: Add JWT configuration to environment and refactor JWT middleware to use new config structure
This commit is contained in:
@@ -1,97 +1,17 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/joho/godotenv"
|
||||
"github.com/oklog/ulid/v2"
|
||||
"github.com/timetracker/backend/internal/api/utils"
|
||||
"github.com/timetracker/backend/internal/config"
|
||||
"github.com/timetracker/backend/internal/models"
|
||||
)
|
||||
|
||||
var (
|
||||
jwtSecret string
|
||||
tokenDuration = 24 * time.Hour
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Load .env file
|
||||
_ = godotenv.Load()
|
||||
|
||||
// Get JWT secret from environment
|
||||
jwtSecret = os.Getenv("JWT_SECRET")
|
||||
|
||||
// Generate a random secret if none is provided
|
||||
if jwtSecret == "" {
|
||||
randomBytes := make([]byte, 32)
|
||||
_, err := rand.Read(randomBytes)
|
||||
if err != nil {
|
||||
panic("failed to generate JWT secret: " + err.Error())
|
||||
}
|
||||
jwtSecret = string(randomBytes)
|
||||
}
|
||||
|
||||
// Generate and store RSA keys if configured
|
||||
if os.Getenv("JWT_KEY_GENERATE") == "true" {
|
||||
keyDir := os.Getenv("JWT_KEY_DIR")
|
||||
if keyDir == "" {
|
||||
keyDir = "./keys"
|
||||
}
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
if err := os.MkdirAll(keyDir, 0755); err != nil {
|
||||
panic("failed to create key directory: " + err.Error())
|
||||
}
|
||||
|
||||
// Generate RSA key pair
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
panic("failed to generate RSA key pair: " + err.Error())
|
||||
}
|
||||
|
||||
// Save private key
|
||||
privateKeyFile, err := os.Create(fmt.Sprintf("%s/private.pem", keyDir))
|
||||
if err != nil {
|
||||
panic("failed to create private key file: " + err.Error())
|
||||
}
|
||||
defer privateKeyFile.Close()
|
||||
|
||||
privateKeyPEM := &pem.Block{
|
||||
Type: "RSA PRIVATE KEY",
|
||||
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
|
||||
}
|
||||
|
||||
if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
|
||||
panic("failed to encode private key: " + err.Error())
|
||||
}
|
||||
|
||||
// Save public key
|
||||
publicKeyFile, err := os.Create(fmt.Sprintf("%s/public.pem", keyDir))
|
||||
if err != nil {
|
||||
panic("failed to create public key file: " + err.Error())
|
||||
}
|
||||
defer publicKeyFile.Close()
|
||||
|
||||
publicKeyPEM := &pem.Block{
|
||||
Type: "RSA PUBLIC KEY",
|
||||
Bytes: x509.MarshalPKCS1PublicKey(&privateKey.PublicKey),
|
||||
}
|
||||
|
||||
if err := pem.Encode(publicKeyFile, publicKeyPEM); err != nil {
|
||||
panic("failed to encode public key: " + err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Claims represents the JWT claims
|
||||
type Claims struct {
|
||||
UserID string `json:"userId"`
|
||||
@@ -174,7 +94,7 @@ func GenerateToken(user *models.User, c *gin.Context) (string, error) {
|
||||
Role: user.Role,
|
||||
CompanyID: user.CompanyID.String(),
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(tokenDuration)),
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(config.MustLoadConfig().JWTConfig.TokenDuration)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
NotBefore: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
@@ -183,14 +103,15 @@ func GenerateToken(user *models.User, c *gin.Context) (string, error) {
|
||||
// Create the token
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
|
||||
cfg := config.MustLoadConfig()
|
||||
// Sign the token
|
||||
tokenString, err := token.SignedString([]byte(jwtSecret))
|
||||
tokenString, err := token.SignedString([]byte(cfg.JWTConfig.Secret))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Set the cookie
|
||||
c.SetCookie("jwt", tokenString, int(tokenDuration.Seconds()), "/", "", true, true)
|
||||
c.SetCookie("jwt", tokenString, int(cfg.JWTConfig.TokenDuration.Seconds()), "/", "", true, true)
|
||||
|
||||
return tokenString, nil
|
||||
}
|
||||
@@ -198,12 +119,13 @@ func GenerateToken(user *models.User, c *gin.Context) (string, error) {
|
||||
// validateToken validates a JWT token and returns the claims
|
||||
func validateToken(tokenString string) (*Claims, error) {
|
||||
// Parse the token
|
||||
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (any, error) {
|
||||
// Validate the signing method
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("unexpected signing method")
|
||||
}
|
||||
return []byte(jwtSecret), nil
|
||||
cfg := config.MustLoadConfig()
|
||||
return []byte(cfg.JWTConfig.Secret), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user