cpolis/cmd/data/sessions.go

67 lines
1.2 KiB
Go
Raw Normal View History

2024-03-03 09:16:49 +01:00
package data
import (
"crypto/rand"
"encoding/gob"
"fmt"
"io"
"os"
"github.com/gorilla/sessions"
)
type CookieStore struct {
sessions.CookieStore
}
func NewKey() ([]byte, error) {
key := make([]byte, 32)
_, err := io.ReadFull(rand.Reader, key)
if err != nil {
return nil, fmt.Errorf("error generating key: %v", err)
}
return key, nil
}
func SaveKey(key []byte, filename string) error {
file, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error creating key file: %v", err)
}
defer file.Close()
file.Chmod(0600)
encoder := gob.NewEncoder(file)
err = encoder.Encode(key)
if err != nil {
return fmt.Errorf("error ecoding key: %v", err)
}
return nil
}
func LoadKey(filename string) ([]byte, error) {
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("error opening key file: %v", err)
}
key := make([]byte, 32)
decoder := gob.NewDecoder(file)
err = decoder.Decode(&key)
if err != nil {
return nil, fmt.Errorf("error decoding key: %v", err)
}
return key, nil
}
func NewCookieStore(key []byte) *CookieStore {
store := sessions.NewCookieStore(key)
store.Options.Secure = true
store.Options.HttpOnly = true
return &CookieStore{*store}
}