1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-25 14:44:06 +00:00

113 lines
1.9 KiB
Go
Raw Normal View History

2020-11-06 19:43:57 +01:00
package session
2020-11-06 19:32:56 +01:00
import (
"fmt"
"time"
"github.com/gofiber/fiber/v2"
2020-11-06 19:43:57 +01:00
"github.com/gofiber/fiber/v2/internal/storage/memory"
2020-11-06 19:32:56 +01:00
"github.com/gofiber/fiber/v2/utils"
)
type Config struct {
// Possible values:
// - "header:<name>"
// - "query:<name>"
// - "param:<name>"
// - "form:<name>"
// - "cookie:<name>"
//
// Optional. Default value "cookie:_csrf".
// TODO: When to override Cookie.Value?
KeyLookup string
// Optional. Session ID generator function.
//
// Default: utils.UUID
KeyGenerator func() string
// Optional. Cookie to set values on
//
// NOTE: Value, MaxAge and Expires will be overriden by the session ID and expiration
// TODO: Should this be a pointer, if yes why?
Cookie fiber.Cookie
// Allowed session duration
//
// Optional. Default: 24 hours
Expiration time.Duration
// Store interface
2020-11-06 19:43:57 +01:00
// Optional. Default: memory.New()
Storage fiber.Storage
2020-11-06 19:32:56 +01:00
}
var ConfigDefault = Config{
Cookie: fiber.Cookie{
Value: "session_id",
},
Expiration: 30 * time.Minute,
KeyGenerator: utils.UUID,
}
2020-11-06 19:43:57 +01:00
type Store struct {
Config
2020-11-06 19:32:56 +01:00
}
2020-11-06 19:43:57 +01:00
func New(config ...Config) *Store {
2020-11-06 19:32:56 +01:00
cfg := ConfigDefault
if len(config) > 0 {
cfg = config[0]
}
2020-11-06 19:43:57 +01:00
if cfg.Storage == nil {
cfg.Storage = memory.New()
2020-11-06 19:32:56 +01:00
}
2020-11-06 19:43:57 +01:00
return &Store{
cfg,
2020-11-06 19:32:56 +01:00
}
}
2020-11-06 19:43:57 +01:00
func (s *Store) Get(c *fiber.Ctx) *Session {
2020-11-06 19:32:56 +01:00
var fresh bool
// Get ID from cookie
2020-11-06 19:43:57 +01:00
id := c.Cookies(s.Cookie.Name)
2020-11-06 19:32:56 +01:00
// If no ID exist, create new one
if len(id) == 0 {
2020-11-06 19:43:57 +01:00
id = s.KeyGenerator()
2020-11-06 19:32:56 +01:00
fresh = true
}
// Create session object
sess := &Session{
2020-11-06 19:43:57 +01:00
ctx: c,
config: s,
fresh: fresh,
db: acquireDB(),
id: id,
2020-11-06 19:32:56 +01:00
}
// Fetch existing data
if !fresh {
2020-11-06 19:43:57 +01:00
raw, err := s.Storage.Get(id)
2020-11-06 19:32:56 +01:00
// Set data
if err == nil {
_, err := sess.db.UnmarshalMsg(raw)
if err != nil {
fmt.Println(err)
}
}
}
// Return session object
return sess
}
2020-11-06 19:43:57 +01:00
func (s *Store) Reset() error {
return s.Storage.Reset()
2020-11-06 19:32:56 +01:00
}