forked from go-bootstrap/go-bootstrap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middlewares.go
46 lines (37 loc) · 1.22 KB
/
middlewares.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
// Package middlewares provides common middleware handlers.
package middlewares
import (
"net/http"
"github.com/gorilla/context"
"github.com/gorilla/sessions"
"github.com/jmoiron/sqlx"
)
func SetDB(db *sqlx.DB) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
context.Set(req, "db", db)
next.ServeHTTP(res, req)
})
}
}
func SetSessionStore(sessionStore sessions.Store) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
context.Set(req, "sessionStore", sessionStore)
next.ServeHTTP(res, req)
})
}
}
// MustLogin is a middleware that checks existence of current user.
func MustLogin(next http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
sessionStore := context.Get(req, "sessionStore").(sessions.Store)
session, _ := sessionStore.Get(req, "$GO_BOOTSTRAP_PROJECT_NAME-session")
userRowInterface := session.Values["user"]
if userRowInterface == nil {
http.Redirect(res, req, "/login", 302)
return
}
next.ServeHTTP(res, req)
})
}