Bootstrapped the creation and loading of session keys to lighten main.
This commit is contained in:
61
bootstrap/session.go
Normal file
61
bootstrap/session.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user