This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
/
sessions.go
129 lines (108 loc) · 3.9 KB
/
sessions.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package middleware
import (
"context"
"net/http"
"sync"
"time"
"github.com/google/exposure-notifications-verification-server/pkg/controller"
"github.com/google/exposure-notifications-verification-server/pkg/render"
"github.com/google/exposure-notifications-server/pkg/logging"
"github.com/gorilla/sessions"
"go.uber.org/zap"
)
const (
// sessionName is the name of the session.
sessionName = "verification-server-session"
)
// RequireSession retrieves or creates a new session and stores it on the
// request's context for future retrieval. It also ensures the flash data is
// populated in the template map. Any handler that wants to utilize sessions
// should use this middleware.
func RequireSession(ctx context.Context, store sessions.Store, h *render.Renderer) func(http.Handler) http.Handler {
logger := logging.FromContext(ctx).Named("middleware.RequireSession")
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Get or create a session from the store.
session, err := store.Get(r, sessionName)
if err != nil {
logger.Errorw("failed to get session", "error", err)
// We couldn't get a session (invalid cookie, can't talk to redis,
// whatever). According to the spec, this can return an error but can never
// return an empty session. We intentionally discard the error to ensure we
// have a session.
session, _ = store.New(r, sessionName)
}
// Save the flash in the template map.
m := controller.TemplateMapFromContext(ctx)
m["flash"] = controller.Flash(session)
ctx = controller.WithTemplateMap(ctx, m)
// Save the session on the context.
ctx = controller.WithSession(ctx, session)
*r = *r.WithContext(ctx)
// Ensure the session is saved at least once. This is passed to the
// before-first-byte writer AND called after the middleware executes to
// ensure the session is always sent.
var once sync.Once
saveSession := func() error {
var err error
once.Do(func() {
session := controller.SessionFromContext(ctx)
if session != nil {
controller.StoreSessionLastActivity(session, time.Now())
err = session.Save(r, w)
}
})
return err
}
bfbw := &beforeFirstByteWriter{
w: w,
before: saveSession,
logger: logger,
}
next.ServeHTTP(bfbw, r)
// Ensure the session is saved - this will happen if no bytes were
// written (perhaps due to a redirect or empty body).
if err := saveSession(); err != nil {
controller.InternalError(w, r, h, err)
return
}
})
}
}
// beforeFirstByteWriter is a custom http.ResponseWriter with a hook to run
// before the first byte is written. This is useful if you want to store a
// cookie or some other information that must be sent before any body bytes.
type beforeFirstByteWriter struct {
w http.ResponseWriter
before func() error
logger *zap.SugaredLogger
}
func (w *beforeFirstByteWriter) Header() http.Header {
return w.w.Header()
}
func (w *beforeFirstByteWriter) WriteHeader(c int) {
if err := w.before(); err != nil {
w.logger.Errorw("failed to invoke before() in beforeFirstByteWriter", "error", err)
}
w.w.WriteHeader(c)
}
func (w *beforeFirstByteWriter) Write(b []byte) (int, error) {
if err := w.before(); err != nil {
return 0, err
}
return w.w.Write(b)
}