Compare commits
3 Commits
9057adebdd
...
c3162756ad
Author | SHA1 | Date | |
---|---|---|---|
c3162756ad | |||
2e13d775fa | |||
b545392f27 |
@ -7,6 +7,8 @@ DB_SSLMODE=disable
|
|||||||
API_KEY=
|
API_KEY=
|
||||||
|
|
||||||
# JWT Configuration
|
# JWT Configuration
|
||||||
JWT_SECRET=test
|
#JWT_SECRET=test
|
||||||
JWT_KEY_DIR=keys
|
#JWT_KEY_DIR=keys
|
||||||
JWT_KEY_GENERATE=true
|
#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"
|
"github.com/gin-gonic/gin"
|
||||||
swaggerFiles "github.com/swaggo/files"
|
swaggerFiles "github.com/swaggo/files"
|
||||||
ginSwagger "github.com/swaggo/gin-swagger"
|
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/api/routes"
|
||||||
"github.com/timetracker/backend/internal/config"
|
"github.com/timetracker/backend/internal/config"
|
||||||
"github.com/timetracker/backend/internal/models"
|
"github.com/timetracker/backend/internal/models"
|
||||||
@ -60,6 +61,11 @@ func main() {
|
|||||||
log.Fatalf("Error migrating database: %v", err)
|
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
|
// Create Gin router
|
||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
|
|
||||||
|
@ -8,88 +8,157 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/golang-jwt/jwt/v5"
|
"github.com/golang-jwt/jwt/v5"
|
||||||
"github.com/joho/godotenv"
|
|
||||||
"github.com/oklog/ulid/v2"
|
"github.com/oklog/ulid/v2"
|
||||||
"github.com/timetracker/backend/internal/api/utils"
|
"github.com/timetracker/backend/internal/api/utils"
|
||||||
|
"github.com/timetracker/backend/internal/config"
|
||||||
"github.com/timetracker/backend/internal/models"
|
"github.com/timetracker/backend/internal/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
jwtSecret string
|
signKey *rsa.PrivateKey
|
||||||
tokenDuration = 24 * time.Hour
|
verifyKey *rsa.PublicKey
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
// InitJWTKeys initializes the JWT keys
|
||||||
// Load .env file
|
func InitJWTKeys() error {
|
||||||
_ = godotenv.Load()
|
cfg := config.MustLoadConfig()
|
||||||
|
|
||||||
// Get JWT secret from environment
|
// If a secret is provided, we'll use HMAC-SHA256, so no need for certificates
|
||||||
jwtSecret = os.Getenv("JWT_SECRET")
|
if cfg.JWTConfig.Secret != "" {
|
||||||
|
println("Using HMAC-SHA256 for JWT")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// Generate a random secret if none is provided
|
// Check if keys exist
|
||||||
if jwtSecret == "" {
|
privKeyPath := filepath.Join(cfg.JWTConfig.KeyDir, cfg.JWTConfig.PrivKeyFile)
|
||||||
randomBytes := make([]byte, 32)
|
pubKeyPath := filepath.Join(cfg.JWTConfig.KeyDir, cfg.JWTConfig.PubKeyFile)
|
||||||
_, err := rand.Read(randomBytes)
|
|
||||||
|
keysExist := fileExists(privKeyPath) && fileExists(pubKeyPath)
|
||||||
|
|
||||||
|
// 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 {
|
if err != nil {
|
||||||
panic("failed to generate JWT secret: " + err.Error())
|
return fmt.Errorf("failed to load private key: %w", err)
|
||||||
}
|
|
||||||
jwtSecret = string(randomBytes)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate and store RSA keys if configured
|
verifyKey, err = loadPublicKey(pubKeyPath)
|
||||||
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 {
|
if err != nil {
|
||||||
panic("failed to generate RSA key pair: " + err.Error())
|
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
|
// Save private key
|
||||||
privateKeyFile, err := os.Create(fmt.Sprintf("%s/private.pem", keyDir))
|
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 {
|
if err != nil {
|
||||||
panic("failed to create private key file: " + err.Error())
|
return fmt.Errorf("failed to create private key file: %w", err)
|
||||||
}
|
}
|
||||||
defer privateKeyFile.Close()
|
defer privKeyFile.Close()
|
||||||
|
|
||||||
privateKeyPEM := &pem.Block{
|
privKeyPEM := &pem.Block{
|
||||||
Type: "RSA PRIVATE KEY",
|
Type: "RSA PRIVATE KEY",
|
||||||
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
|
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
|
if err := pem.Encode(privKeyFile, privKeyPEM); err != nil {
|
||||||
panic("failed to encode private key: " + err.Error())
|
return fmt.Errorf("failed to encode private key: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save public key
|
// Save public key
|
||||||
publicKeyFile, err := os.Create(fmt.Sprintf("%s/public.pem", keyDir))
|
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 {
|
if err != nil {
|
||||||
panic("failed to create public key file: " + err.Error())
|
return fmt.Errorf("failed to create public key file: %w", err)
|
||||||
}
|
}
|
||||||
defer publicKeyFile.Close()
|
defer pubKeyFile.Close()
|
||||||
|
|
||||||
publicKeyPEM := &pem.Block{
|
pubKeyPEM := &pem.Block{
|
||||||
Type: "RSA PUBLIC KEY",
|
Type: "RSA PUBLIC KEY",
|
||||||
Bytes: x509.MarshalPKCS1PublicKey(&privateKey.PublicKey),
|
Bytes: x509.MarshalPKCS1PublicKey(&privateKey.PublicKey),
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := pem.Encode(publicKeyFile, publicKeyPEM); err != nil {
|
if err := pem.Encode(pubKeyFile, pubKeyPEM); err != nil {
|
||||||
panic("failed to encode public key: " + err.Error())
|
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
|
// Claims represents the JWT claims
|
||||||
@ -174,36 +243,60 @@ func GenerateToken(user *models.User, c *gin.Context) (string, error) {
|
|||||||
Role: user.Role,
|
Role: user.Role,
|
||||||
CompanyID: user.CompanyID.String(),
|
CompanyID: user.CompanyID.String(),
|
||||||
RegisteredClaims: jwt.RegisteredClaims{
|
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()),
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||||
NotBefore: jwt.NewNumericDate(time.Now()),
|
NotBefore: jwt.NewNumericDate(time.Now()),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create the token
|
cfg := config.MustLoadConfig()
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
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 {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the cookie
|
// 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
|
return tokenString, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// validateToken validates a JWT token and returns the claims
|
// validateToken validates a JWT token and returns the claims
|
||||||
func validateToken(tokenString string) (*Claims, error) {
|
func validateToken(tokenString string) (*Claims, error) {
|
||||||
|
cfg := config.MustLoadConfig()
|
||||||
|
|
||||||
// Parse the token
|
// 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
|
// Check which signing method was used
|
||||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); ok {
|
||||||
return nil, errors.New("unexpected signing method")
|
// 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(jwtSecret), nil
|
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 nil, errors.New("unexpected signing method")
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -6,6 +6,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
"github.com/timetracker/backend/internal/models"
|
"github.com/timetracker/backend/internal/models"
|
||||||
@ -15,6 +16,7 @@ import (
|
|||||||
// Config represents the application configuration
|
// Config represents the application configuration
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Database models.DatabaseConfig
|
Database models.DatabaseConfig
|
||||||
|
JWTConfig models.JWTConfig
|
||||||
APIKey string
|
APIKey string
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -25,6 +27,7 @@ func LoadConfig() (*Config, error) {
|
|||||||
|
|
||||||
cfg := &Config{
|
cfg := &Config{
|
||||||
Database: models.DefaultDatabaseConfig(),
|
Database: models.DefaultDatabaseConfig(),
|
||||||
|
JWTConfig: models.JWTConfig{},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load database configuration
|
// Load database configuration
|
||||||
@ -32,12 +35,50 @@ func LoadConfig() (*Config, error) {
|
|||||||
return nil, fmt.Errorf("failed to load database config: %w", err)
|
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
|
// Load API key
|
||||||
cfg.APIKey = getEnv("API_KEY", "")
|
cfg.APIKey = getEnv("API_KEY", "")
|
||||||
|
|
||||||
return cfg, nil
|
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
|
// loadDatabaseConfig loads database configuration from environment
|
||||||
func loadDatabaseConfig(cfg *Config) error {
|
func loadDatabaseConfig(cfg *Config) error {
|
||||||
// Required fields
|
// 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