2024-04-02 23:48:31 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/gorilla/securecookie"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2024-10-31 13:50:13 +00:00
|
|
|
// GenerateSecretKey generates a new secret key for sessions
|
|
|
|
// Returns the key and a boolean indicating if the key was generated
|
|
|
|
func GenerateSecretKey(filePath string) ([]byte, bool) {
|
2024-04-02 23:48:31 +00:00
|
|
|
key, err := os.ReadFile(filePath)
|
|
|
|
if err == nil {
|
2024-10-31 13:50:13 +00:00
|
|
|
return key, false
|
2024-04-02 23:48:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
key = securecookie.GenerateRandomKey(32)
|
|
|
|
if key == nil {
|
|
|
|
log.Fatal().Msg("Failed to generate a new key for sessions")
|
|
|
|
}
|
|
|
|
|
|
|
|
err = os.WriteFile(filePath, key, 0600)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal().Err(err).Msgf("Failed to save the key to %s", filePath)
|
|
|
|
}
|
|
|
|
|
2024-10-31 13:50:13 +00:00
|
|
|
return key, true
|
2024-04-02 23:48:31 +00:00
|
|
|
}
|