75 lines
1.6 KiB
Go
75 lines
1.6 KiB
Go
// Package session provides session management functionality.
|
|
// It includes session storage, flash messages, and data persistence.
|
|
package session
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
DefaultExpiration = 24 * time.Hour
|
|
IDLength = 32
|
|
)
|
|
|
|
type Session struct {
|
|
ID string `json:"-"`
|
|
UserID int `json:"user_id"`
|
|
Username string `json:"username"`
|
|
Email string `json:"email"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
LastSeen time.Time `json:"last_seen"`
|
|
Data map[string]any `json:"data,omitempty"`
|
|
}
|
|
|
|
func New(userID int, username, email string) *Session {
|
|
return &Session{
|
|
ID: generateID(),
|
|
UserID: userID,
|
|
Username: username,
|
|
Email: email,
|
|
CreatedAt: time.Now(),
|
|
ExpiresAt: time.Now().Add(DefaultExpiration),
|
|
LastSeen: time.Now(),
|
|
Data: make(map[string]any),
|
|
}
|
|
}
|
|
|
|
func (s *Session) IsExpired() bool {
|
|
return time.Now().After(s.ExpiresAt)
|
|
}
|
|
|
|
func (s *Session) Touch() {
|
|
s.LastSeen = time.Now()
|
|
s.ExpiresAt = time.Now().Add(DefaultExpiration)
|
|
}
|
|
|
|
func (s *Session) Set(key string, value any) {
|
|
if s.Data == nil {
|
|
s.Data = make(map[string]any)
|
|
}
|
|
s.Data[key] = value
|
|
}
|
|
|
|
func (s *Session) Get(key string) (any, bool) {
|
|
if s.Data == nil {
|
|
return nil, false
|
|
}
|
|
value, exists := s.Data[key]
|
|
return value, exists
|
|
}
|
|
|
|
func (s *Session) Delete(key string) {
|
|
if s.Data != nil {
|
|
delete(s.Data, key)
|
|
}
|
|
}
|
|
|
|
func generateID() string {
|
|
bytes := make([]byte, IDLength)
|
|
rand.Read(bytes)
|
|
return hex.EncodeToString(bytes)
|
|
}
|