Compare commits
3 Commits
9057adebdd
...
c3162756ad
Author | SHA1 | Date | |
---|---|---|---|
c3162756ad | |||
2e13d775fa | |||
b545392f27 |
@ -7,6 +7,8 @@ DB_SSLMODE=disable
|
||||
API_KEY=
|
||||
|
||||
# JWT Configuration
|
||||
JWT_SECRET=test
|
||||
JWT_KEY_DIR=keys
|
||||
JWT_KEY_GENERATE=true
|
||||
#JWT_SECRET=test
|
||||
#JWT_KEY_DIR=keys
|
||||
#JWT_KEY_GENERATE=true
|
||||
JWT_TOKEN_DURATION=24h
|
||||
ENVIRONMENT=production
|
1
backend/.gitignore
vendored
Normal file
1
backend/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
keys
|
@ -13,7 +13,8 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
_ "github.com/timetracker/backend/docs" // This line is important for swag to work
|
||||
_ "github.com/timetracker/backend/docs"
|
||||
"github.com/timetracker/backend/internal/api/middleware"
|
||||
"github.com/timetracker/backend/internal/api/routes"
|
||||
"github.com/timetracker/backend/internal/config"
|
||||
"github.com/timetracker/backend/internal/models"
|
||||
@ -60,6 +61,11 @@ func main() {
|
||||
log.Fatalf("Error migrating database: %v", err)
|
||||
}
|
||||
|
||||
// Initialize JWT keys
|
||||
if err := middleware.InitJWTKeys(); err != nil {
|
||||
log.Fatalf("Error initializing JWT keys: %v", err)
|
||||
}
|
||||
|
||||
// Create Gin router
|
||||
r := gin.Default()
|
||||
|
||||
|
@ -8,88 +8,157 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"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
|
||||
signKey *rsa.PrivateKey
|
||||
verifyKey *rsa.PublicKey
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Load .env file
|
||||
_ = godotenv.Load()
|
||||
// InitJWTKeys initializes the JWT keys
|
||||
func InitJWTKeys() error {
|
||||
cfg := config.MustLoadConfig()
|
||||
|
||||
// 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)
|
||||
// If a secret is provided, we'll use HMAC-SHA256, so no need for certificates
|
||||
if cfg.JWTConfig.Secret != "" {
|
||||
println("Using HMAC-SHA256 for JWT")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Generate and store RSA keys if configured
|
||||
if os.Getenv("JWT_KEY_GENERATE") == "true" {
|
||||
keyDir := os.Getenv("JWT_KEY_DIR")
|
||||
if keyDir == "" {
|
||||
keyDir = "./keys"
|
||||
}
|
||||
// Check if keys exist
|
||||
privKeyPath := filepath.Join(cfg.JWTConfig.KeyDir, cfg.JWTConfig.PrivKeyFile)
|
||||
pubKeyPath := filepath.Join(cfg.JWTConfig.KeyDir, cfg.JWTConfig.PubKeyFile)
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
if err := os.MkdirAll(keyDir, 0755); err != nil {
|
||||
panic("failed to create key directory: " + err.Error())
|
||||
}
|
||||
keysExist := fileExists(privKeyPath) && fileExists(pubKeyPath)
|
||||
|
||||
// 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())
|
||||
// Generate keys if they don't exist and KeyGenerate is true
|
||||
if !keysExist && cfg.JWTConfig.KeyGenerate {
|
||||
println("Generating RSA keys")
|
||||
if err := generateRSAKeys(cfg.JWTConfig); err != nil {
|
||||
return fmt.Errorf("failed to generate RSA keys: %w", err)
|
||||
}
|
||||
} else if !keysExist {
|
||||
return errors.New("JWT keys not found and key generation is disabled")
|
||||
}
|
||||
|
||||
// Load keys
|
||||
var err error
|
||||
signKey, err = loadPrivateKey(privKeyPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load private key: %w", err)
|
||||
}
|
||||
|
||||
verifyKey, err = loadPublicKey(pubKeyPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load public key: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// fileExists checks if a file exists
|
||||
func fileExists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
return !os.IsNotExist(err)
|
||||
}
|
||||
|
||||
// generateRSAKeys generates RSA keys and saves them to disk
|
||||
func generateRSAKeys(cfg models.JWTConfig) error {
|
||||
// Create key directory if it doesn't exist
|
||||
if err := os.MkdirAll(cfg.KeyDir, 0700); err != nil {
|
||||
return fmt.Errorf("failed to create key directory: %w", err)
|
||||
}
|
||||
|
||||
// Generate private key
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, cfg.KeyBits)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate private key: %w", err)
|
||||
}
|
||||
|
||||
// Save private key
|
||||
privKeyPath := filepath.Join(cfg.KeyDir, cfg.PrivKeyFile)
|
||||
privKeyFile, err := os.OpenFile(privKeyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create private key file: %w", err)
|
||||
}
|
||||
defer privKeyFile.Close()
|
||||
|
||||
privKeyPEM := &pem.Block{
|
||||
Type: "RSA PRIVATE KEY",
|
||||
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
|
||||
}
|
||||
|
||||
if err := pem.Encode(privKeyFile, privKeyPEM); err != nil {
|
||||
return fmt.Errorf("failed to encode private key: %w", err)
|
||||
}
|
||||
|
||||
// Save public key
|
||||
pubKeyPath := filepath.Join(cfg.KeyDir, cfg.PubKeyFile)
|
||||
pubKeyFile, err := os.OpenFile(pubKeyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create public key file: %w", err)
|
||||
}
|
||||
defer pubKeyFile.Close()
|
||||
|
||||
pubKeyPEM := &pem.Block{
|
||||
Type: "RSA PUBLIC KEY",
|
||||
Bytes: x509.MarshalPKCS1PublicKey(&privateKey.PublicKey),
|
||||
}
|
||||
|
||||
if err := pem.Encode(pubKeyFile, pubKeyPEM); err != nil {
|
||||
return fmt.Errorf("failed to encode public key: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadPrivateKey loads a private key from a file
|
||||
func loadPrivateKey(path string) (*rsa.PrivateKey, error) {
|
||||
keyData, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read private key file: %w", err)
|
||||
}
|
||||
|
||||
block, _ := pem.Decode(keyData)
|
||||
if block == nil {
|
||||
return nil, errors.New("failed to parse PEM block containing the private key")
|
||||
}
|
||||
|
||||
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse private key: %w", err)
|
||||
}
|
||||
|
||||
return privateKey, nil
|
||||
}
|
||||
|
||||
// loadPublicKey loads a public key from a file
|
||||
func loadPublicKey(path string) (*rsa.PublicKey, error) {
|
||||
keyData, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read public key file: %w", err)
|
||||
}
|
||||
|
||||
block, _ := pem.Decode(keyData)
|
||||
if block == nil {
|
||||
return nil, errors.New("failed to parse PEM block containing the public key")
|
||||
}
|
||||
|
||||
publicKey, err := x509.ParsePKCS1PublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse public key: %w", err)
|
||||
}
|
||||
|
||||
return publicKey, nil
|
||||
}
|
||||
|
||||
// Claims represents the JWT claims
|
||||
@ -174,36 +243,60 @@ 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()),
|
||||
},
|
||||
}
|
||||
|
||||
// Create the token
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
cfg := config.MustLoadConfig()
|
||||
var token *jwt.Token
|
||||
var tokenString string
|
||||
var err error
|
||||
|
||||
// Choose signing method based on configuration
|
||||
if cfg.JWTConfig.Secret != "" {
|
||||
// Use HMAC-SHA256 if a secret is provided
|
||||
token = jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, err = token.SignedString([]byte(cfg.JWTConfig.Secret))
|
||||
} else {
|
||||
// Use RSA if no secret is provided
|
||||
token = jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
|
||||
tokenString, err = token.SignedString(signKey)
|
||||
}
|
||||
|
||||
// Sign the token
|
||||
tokenString, err := token.SignedString([]byte(jwtSecret))
|
||||
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
|
||||
}
|
||||
|
||||
// validateToken validates a JWT token and returns the claims
|
||||
func validateToken(tokenString string) (*Claims, error) {
|
||||
cfg := config.MustLoadConfig()
|
||||
|
||||
// Parse the token
|
||||
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
// Validate the signing method
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("unexpected signing method")
|
||||
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (any, error) {
|
||||
// Check which signing method was used
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); ok {
|
||||
// HMAC method was used, validate with secret
|
||||
if cfg.JWTConfig.Secret == "" {
|
||||
return nil, errors.New("HMAC signing method used but no secret configured")
|
||||
}
|
||||
return []byte(cfg.JWTConfig.Secret), nil
|
||||
} else if _, ok := token.Method.(*jwt.SigningMethodRSA); ok {
|
||||
// RSA method was used, validate with public key
|
||||
if verifyKey == nil {
|
||||
return nil, errors.New("RSA signing method used but no public key loaded")
|
||||
}
|
||||
return verifyKey, nil
|
||||
}
|
||||
return []byte(jwtSecret), nil
|
||||
|
||||
return nil, errors.New("unexpected signing method")
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
|
@ -6,6 +6,7 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
"github.com/timetracker/backend/internal/models"
|
||||
@ -14,8 +15,9 @@ import (
|
||||
|
||||
// Config represents the application configuration
|
||||
type Config struct {
|
||||
Database models.DatabaseConfig
|
||||
APIKey string
|
||||
Database models.DatabaseConfig
|
||||
JWTConfig models.JWTConfig
|
||||
APIKey string
|
||||
}
|
||||
|
||||
// LoadConfig loads configuration from environment variables and .env file
|
||||
@ -24,7 +26,8 @@ func LoadConfig() (*Config, error) {
|
||||
_ = godotenv.Load()
|
||||
|
||||
cfg := &Config{
|
||||
Database: models.DefaultDatabaseConfig(),
|
||||
Database: models.DefaultDatabaseConfig(),
|
||||
JWTConfig: models.JWTConfig{},
|
||||
}
|
||||
|
||||
// Load database configuration
|
||||
@ -32,12 +35,50 @@ func LoadConfig() (*Config, error) {
|
||||
return nil, fmt.Errorf("failed to load database config: %w", err)
|
||||
}
|
||||
|
||||
// Load JWT configuration
|
||||
if err := loadJWTConfig(cfg); err != nil {
|
||||
return nil, fmt.Errorf("failed to load JWT config: %w", err)
|
||||
}
|
||||
|
||||
// Load API key
|
||||
cfg.APIKey = getEnv("API_KEY", "")
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// loadJWTConfig loads JWT configuration from environment
|
||||
func loadJWTConfig(cfg *Config) error {
|
||||
cfg.JWTConfig.Secret = getEnv("JWT_SECRET", "")
|
||||
defaultDuration := 24 * time.Hour
|
||||
durationStr := getEnv("JWT_TOKEN_DURATION", defaultDuration.String())
|
||||
|
||||
duration, err := time.ParseDuration(durationStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid JWT_TOKEN_DURATION: %w", err)
|
||||
}
|
||||
cfg.JWTConfig.TokenDuration = duration
|
||||
|
||||
keyGenerateStr := getEnv("JWT_KEY_GENERATE", "true")
|
||||
keyGenerate, err := strconv.ParseBool(keyGenerateStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid JWT_KEY_GENERATE: %w", err)
|
||||
}
|
||||
cfg.JWTConfig.KeyGenerate = keyGenerate
|
||||
|
||||
cfg.JWTConfig.KeyDir = getEnv("JWT_KEY_DIR", "./keys")
|
||||
cfg.JWTConfig.PrivKeyFile = getEnv("JWT_PRIV_KEY_FILE", "jwt.key")
|
||||
cfg.JWTConfig.PubKeyFile = getEnv("JWT_PUB_KEY_FILE", "jwt.key.pub")
|
||||
|
||||
keyBitsStr := getEnv("JWT_KEY_BITS", "2048")
|
||||
keyBits, err := strconv.Atoi(keyBitsStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid JWT_KEY_BITS: %w", err)
|
||||
}
|
||||
cfg.JWTConfig.KeyBits = keyBits
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadDatabaseConfig loads database configuration from environment
|
||||
func loadDatabaseConfig(cfg *Config) error {
|
||||
// Required fields
|
||||
|
13
backend/internal/models/jwt.go
Normal file
13
backend/internal/models/jwt.go
Normal file
@ -0,0 +1,13 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type JWTConfig struct {
|
||||
Secret string `env:"JWT_SECRET" default:""`
|
||||
TokenDuration time.Duration `env:"JWT_TOKEN_DURATION" default:"24h"`
|
||||
KeyGenerate bool `env:"JWT_KEY_GENERATE" default:"true"`
|
||||
KeyDir string `env:"JWT_KEY_DIR" default:"./keys"`
|
||||
PrivKeyFile string `env:"JWT_PRIV_KEY_FILE" default:"jwt.key"`
|
||||
PubKeyFile string `env:"JWT_PUB_KEY_FILE" default:"jwt.key.pub"`
|
||||
KeyBits int `env:"JWT_KEY_BITS" default:"2048"`
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user