Mercurial > gemma
comparison pkg/auth/middleware.go @ 414:c1047fd04a3a
Moved project specific Go packages to new pkg folder.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Wed, 15 Aug 2018 17:30:50 +0200 |
parents | auth/middleware.go@a7b2db8b3d18 |
children | 62c909dd3098 |
comparison
equal
deleted
inserted
replaced
413:a9440a4826aa | 414:c1047fd04a3a |
---|---|
1 package auth | |
2 | |
3 import ( | |
4 "context" | |
5 "net/http" | |
6 "strings" | |
7 ) | |
8 | |
9 type contextType int | |
10 | |
11 const ( | |
12 sessionKey contextType = iota | |
13 tokenKey | |
14 ) | |
15 | |
16 func GetSession(req *http.Request) (*Session, bool) { | |
17 session, ok := req.Context().Value(sessionKey).(*Session) | |
18 return session, ok | |
19 } | |
20 | |
21 func GetToken(req *http.Request) (string, bool) { | |
22 token, ok := req.Context().Value(tokenKey).(string) | |
23 return token, ok | |
24 } | |
25 | |
26 func SessionMiddleware(next http.Handler) http.Handler { | |
27 | |
28 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { | |
29 | |
30 auth := req.Header.Get("X-Gemma-Auth") | |
31 | |
32 token := strings.TrimSpace(auth) | |
33 if token == "" { | |
34 http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) | |
35 return | |
36 } | |
37 | |
38 session := ConnPool.Session(token) | |
39 if session == nil { | |
40 http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) | |
41 return | |
42 } | |
43 | |
44 ctx := req.Context() | |
45 ctx = context.WithValue(ctx, sessionKey, session) | |
46 ctx = context.WithValue(ctx, tokenKey, token) | |
47 req = req.WithContext(ctx) | |
48 | |
49 next.ServeHTTP(rw, req) | |
50 }) | |
51 } | |
52 | |
53 func SessionChecker(next http.Handler, check func(*Session) bool) http.Handler { | |
54 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { | |
55 claims, ok := GetSession(req) | |
56 if !ok || !check(claims) { | |
57 http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) | |
58 return | |
59 } | |
60 next.ServeHTTP(rw, req) | |
61 }) | |
62 } | |
63 | |
64 func HasRole(roles ...string) func(*Session) bool { | |
65 return func(session *Session) bool { | |
66 for _, r1 := range roles { | |
67 if session.Roles.Has(r1) { | |
68 return true | |
69 } | |
70 } | |
71 return false | |
72 } | |
73 } | |
74 | |
75 func EnsureRole(roles ...string) func(http.Handler) http.Handler { | |
76 return func(handler http.Handler) http.Handler { | |
77 return SessionMiddleware(SessionChecker(handler, HasRole(roles...))) | |
78 } | |
79 } |