aboutsummaryrefslogtreecommitdiffhomepage
path: root/backend/auth/session.go
blob: eaf42e76685eafba563865c8726da737f45c488a (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package auth

import (
	"errors"
	"net/http"

	"github.com/gorilla/sessions"
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/v4"
)

const (
	sessionName      = "feedaka_session"
	sessionUserIDKey = "user_id"
	// Session duration: 7 days
	sessionMaxAge = 7 * 24 * 60 * 60
)

var (
	ErrNoSession         = errors.New("no session found")
	ErrNoUserIDInSession = errors.New("no user_id in session")
)

type SessionConfig struct {
	store *sessions.CookieStore
}

func NewSessionConfig(secret string, useNonSecureCookie bool) *SessionConfig {
	store := sessions.NewCookieStore([]byte(secret))
	store.Options = &sessions.Options{
		Path:     "/",
		MaxAge:   sessionMaxAge,
		HttpOnly: true,
		Secure:   !useNonSecureCookie,
		SameSite: http.SameSiteDefaultMode,
	}

	return &SessionConfig{
		store: store,
	}
}

func (c *SessionConfig) GetStore() *sessions.CookieStore {
	return c.store
}

func (c *SessionConfig) SetUserID(ctx echo.Context, userID int64) error {
	sess, err := session.Get(sessionName, ctx)
	if err != nil {
		return err
	}

	sess.Values[sessionUserIDKey] = userID
	return sess.Save(ctx.Request(), ctx.Response())
}

func (c *SessionConfig) GetUserID(ctx echo.Context) (int64, error) {
	sess, err := session.Get(sessionName, ctx)
	if err != nil {
		return 0, ErrNoSession
	}

	userIDVal, ok := sess.Values[sessionUserIDKey]
	if !ok {
		return 0, ErrNoUserIDInSession
	}

	userID, ok := userIDVal.(int64)
	if !ok {
		return 0, ErrNoUserIDInSession
	}

	return userID, nil
}

func (c *SessionConfig) DestroySession(ctx echo.Context) error {
	sess, err := session.Get(sessionName, ctx)
	if err != nil {
		// If there's no session, nothing to destroy
		return nil
	}

	// Set MaxAge to -1 to delete the session
	sess.Options.MaxAge = -1
	return sess.Save(ctx.Request(), ctx.Response())
}