authorizer/server/sessionstore/in_memory_session.go

75 lines
1.6 KiB
Go
Raw Normal View History

package sessionstore
import (
2022-03-02 12:12:31 +00:00
"strings"
"sync"
)
2022-01-17 06:02:13 +00:00
// InMemoryStore is a simple in-memory store for sessions.
type InMemoryStore struct {
2022-02-28 15:56:49 +00:00
mutex sync.Mutex
sessionStore map[string]map[string]string
stateStore map[string]string
}
2022-01-17 06:02:13 +00:00
// ClearStore clears the in-memory store.
func (c *InMemoryStore) ClearStore() {
2022-01-17 06:02:13 +00:00
c.mutex.Lock()
defer c.mutex.Unlock()
2022-02-28 15:56:49 +00:00
c.sessionStore = map[string]map[string]string{}
}
2022-03-02 12:12:31 +00:00
// GetUserSessions returns all the user session token from the in-memory store.
func (c *InMemoryStore) GetUserSessions(userId string) map[string]string {
2022-01-17 06:02:13 +00:00
// c.mutex.Lock()
// defer c.mutex.Unlock()
2022-03-02 12:12:31 +00:00
res := map[string]string{}
for k, v := range c.stateStore {
split := strings.Split(v, "@")
if split[1] == userId {
res[k] = split[0]
}
}
2022-03-02 12:12:31 +00:00
return res
}
2022-03-02 12:12:31 +00:00
// DeleteAllUserSession deletes all the user sessions from in-memory store.
func (c *InMemoryStore) DeleteAllUserSession(userId string) {
// c.mutex.Lock()
// defer c.mutex.Unlock()
2022-03-02 12:12:31 +00:00
sessions := GetUserSessions(userId)
for k := range sessions {
RemoveState(k)
}
}
2022-02-28 15:56:49 +00:00
// SetState sets the state in the in-memory store.
func (c *InMemoryStore) SetState(key, state string) {
2022-01-17 06:02:13 +00:00
c.mutex.Lock()
defer c.mutex.Unlock()
2022-02-28 15:56:49 +00:00
c.stateStore[key] = state
}
2022-02-28 15:56:49 +00:00
// GetState gets the state from the in-memory store.
func (c *InMemoryStore) GetState(key string) string {
2022-01-17 06:02:13 +00:00
c.mutex.Lock()
defer c.mutex.Unlock()
state := ""
2022-02-28 15:56:49 +00:00
if stateVal, ok := c.stateStore[key]; ok {
state = stateVal
}
return state
}
2022-02-28 15:56:49 +00:00
// RemoveState removes the state from the in-memory store.
func (c *InMemoryStore) RemoveState(key string) {
2022-01-17 06:02:13 +00:00
c.mutex.Lock()
defer c.mutex.Unlock()
2022-02-28 15:56:49 +00:00
delete(c.stateStore, key)
}