From 81ca1bd74bfad653315cfd30aebff2c6c43a7bbf Mon Sep 17 00:00:00 2001 From: Martin Kagamino Lehoux Date: Wed, 24 Dec 2025 19:19:44 +0100 Subject: Implements cookie authentication enhancements Improves cookie authentication by adding error handling for expired and bad format cookies. Enhances user session management through robust checks and logging, ensuring a secure and reliable authentication process. Updates the README to reflect changes in the authentication mechanism. --- kauth/crypto.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'kauth/crypto.go') diff --git a/kauth/crypto.go b/kauth/crypto.go index 117076d..0ab9407 100644 --- a/kauth/crypto.go +++ b/kauth/crypto.go @@ -5,15 +5,42 @@ import ( "crypto/cipher" "crypto/rand" "encoding/base64" + "encoding/hex" "errors" + "os" "github.com/martinlehoux/kagamigo/kcore" + "golang.org/x/exp/slog" ) var ( ErrEncryptedTooShort = errors.New("encrypted text is too short") + ErrCookieBadLength = errors.New("cookie secret must be 32 bytes") ) +// Generate a random 32-byte secret for cookies +func GenerateCookieSecret() []byte { + secret := make([]byte, 32) + _, err := rand.Read(secret) + kcore.Expect(err, "failed to generate random bytes") + return secret +} + +func LoadCookieSecret(cookieSecretString string) []byte { + cookiesSecret, err := hex.DecodeString(cookieSecretString) + if err != nil { + err = kcore.Wrap(err, "error decoding cookie secret") + slog.Error(err.Error()) + os.Exit(1) + } + if len(cookiesSecret) != 32 { + slog.Error(ErrCookieBadLength.Error()) + os.Exit(1) + } + slog.Info("cookie secret loaded") + return cookiesSecret +} + func encrypt(secret []byte, plainText string) string { block, err := aes.NewCipher(secret) kcore.Expect(err, "error creating AES cipher") -- cgit v1.3