Bootstrapped the creation and loading of session keys to lighten main.

This commit is contained in:
2025-04-16 08:21:02 +01:00
parent 0a21973237
commit 4bb3b58ddb
8 changed files with 95 additions and 13 deletions

61
bootstrap/session.go Normal file
View File

@@ -0,0 +1,61 @@
package bootstrap
import (
"crypto/rand"
"os"
securityhandlers "synlotto-website/handlers/security"
helpers "synlotto-website/helpers/session"
"synlotto-website/logging"
"synlotto-website/models"
)
func InitSession(cfg *models.Config) error {
authPath := cfg.Session.AuthKeyPath
encPath := cfg.Session.EncryptionKeyPath
if _, err := os.Stat(authPath); os.IsNotExist(err) {
logging.Info("⚠️ Auth key not found, creating: %s", authPath)
key, err := generateRandomBytes(32)
if err != nil {
return err
}
encoded := helpers.EncodeKey(key)
err = os.WriteFile(authPath, []byte(encoded), 0600)
if err != nil {
return err
}
}
if _, err := os.Stat(encPath); os.IsNotExist(err) {
logging.Info("⚠️ Encryption key not found, creating: %s", encPath)
key, err := generateRandomBytes(32)
if err != nil {
return err
}
encoded := helpers.EncodeKey(key)
err = os.WriteFile(encPath, []byte(encoded), 0600)
if err != nil {
return err
}
}
return securityhandlers.LoadSessionKeys(
authPath,
encPath,
cfg.Session.Name,
cfg.HttpServer.ProductionMode,
)
}
func generateRandomBytes(length int) ([]byte, error) {
b := make([]byte, length)
_, err := rand.Read(b)
if err != nil {
logging.Error("failed to generate random bytes: %w", err)
return nil, err
}
return b, nil
}