aboutsummaryrefslogtreecommitdiff
path: root/src/sessions/sessions.go
blob: 34fe91c185fbf0a149bb523d01ac8d42770b71c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package sessions

import (
	"net/http"
	"sync"

	"github.com/google/uuid"
)

type sessionvalues map[string]any

type Session struct {
	id     string
	values sessionvalues
	mu     *sync.Mutex
}

type SessionCtxKey string

var _sessions map[string]Session

func NewSession(w http.ResponseWriter, values map[string]any) Session {
	token := uuid.NewString()

	// set secure cookie in http.ResponseWriter
	// TODO make secure
	http.SetCookie(w, &http.Cookie{
		Name:  "session_token",
		Value: token,
	})

	// create session and store
	s := Session{
		id:     token,
		values: sessionvalues(values),
	}
	_sessions[token] = s
	return s
}

func GetSession(id string) (Session, bool) {
	s, ok := _sessions[id]
	return s, ok
}

func (s *Session) Id() string {
	return s.id
}

func (s *Session) Get(key string) interface{} {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.values[key]
}

func (s *Session) Set(key string, value interface{}) bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.values[key] = value
	return true
}