feat: Update database models and DTOs to use bytea for ULIDWrapper and add JWT configuration to environment

This commit is contained in:
2025-03-11 23:11:49 +00:00
parent c08da6fc92
commit 9057adebdd
19 changed files with 315 additions and 327 deletions
@@ -1,23 +1,97 @@
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/models"
)
// JWT configuration
const (
// This should be moved to environment variables in production
jwtSecret = "your-secret-key-change-in-production"
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"`