forked from mtusi2026/mtusi2026lab3
work 3
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ Store = (*Memory)(nil)
|
||||
|
||||
type Memory struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]Session
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewMemory() *Memory {
|
||||
return &Memory{sessions: make(map[string]Session), now: time.Now}
|
||||
}
|
||||
|
||||
func (m *Memory) Save(_ context.Context, tokenHash []byte, s Session) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.sessions[string(tokenHash)] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Get(_ context.Context, tokenHash []byte) (Session, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
s, ok := m.sessions[string(tokenHash)]
|
||||
if !ok {
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
if !m.now().Before(s.ExpiresAt) {
|
||||
delete(m.sessions, string(tokenHash))
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (m *Memory) Delete(_ context.Context, tokenHash []byte) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.sessions, string(tokenHash))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Ping(context.Context) error { return nil }
|
||||
Reference in New Issue
Block a user