forked from spazzymoto/echo-scs-session
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
78 lines (61 loc) · 1.68 KB
/
session.go
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
package session
import (
"time"
"github.com/alexedwards/scs/v2"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type Config struct {
Skipper middleware.Skipper
SessionManager *scs.SessionManager
}
var DefaultSessionConfig = Config{
Skipper: middleware.DefaultSkipper,
}
func LoadAndSave(sessionManager *scs.SessionManager) echo.MiddlewareFunc {
c := DefaultSessionConfig
c.SessionManager = sessionManager
return LoadAndSaveWithConfig(c)
}
func LoadAndSaveWithConfig(config Config) echo.MiddlewareFunc {
if config.Skipper == nil {
config.Skipper = DefaultSessionConfig.Skipper
}
if config.SessionManager == nil {
panic("Session middleware requires a session manager")
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
return next(c)
}
c.Response().Header().Add("Vary", "Cookie")
ctx := c.Request().Context()
var token string
cookie, err := c.Cookie(config.SessionManager.Cookie.Name)
if err == nil {
token = cookie.Value
}
ctx, err = config.SessionManager.Load(ctx, token)
if err != nil {
return err
}
c.SetRequest(c.Request().WithContext(ctx))
c.Response().Before(func() {
switch config.SessionManager.Status(ctx) {
case scs.Modified:
token, expiry, err := config.SessionManager.Commit(ctx)
if err != nil {
panic(err)
}
config.SessionManager.WriteSessionCookie(ctx, c.Response().Writer, token, expiry)
case scs.Destroyed:
config.SessionManager.WriteSessionCookie(ctx, c.Response().Writer, "", time.Time{})
default:
// session might not exist yet
}
})
return next(c)
}
}
}