forked from applikatoni/applikatoni
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_wrappers.go
85 lines (71 loc) · 1.88 KB
/
handler_wrappers.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
package main
import (
"log"
"net/http"
"github.com/gorilla/context"
"github.com/gorilla/mux"
)
func requireAuthorizedUser(h http.HandlerFunc) http.HandlerFunc {
h = authorizedReaders(h)
h = authenticated(h)
h = applicationScoped(h)
h = authenticate(h)
return h
}
func authenticate(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
currentUser, err := loadUserFromSession(r)
if err != nil {
log.Println("error when trying to get current user", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if currentUser == nil {
currentUser, err = loadUserWithApiToken(r)
if err != nil {
log.Println("error when trying to get current user via Api Token", err)
http.Error(w, "wrong API token", http.StatusInternalServerError)
return
}
}
if currentUser != nil {
context.Set(r, CurrentUser, currentUser)
}
fn(w, r)
}
}
func applicationScoped(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
application, err := findApplication(vars["application"])
if err != nil {
http.Error(w, "application not found", http.StatusNotFound)
return
}
if application != nil {
context.Set(r, CurrentApplication, application)
}
fn(w, r)
}
}
func authenticated(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
currentUser := getCurrentUser(r)
if currentUser == nil {
http.Redirect(w, r, "/oauth2/authorize", http.StatusFound)
} else {
fn(w, r)
}
}
}
func authorizedReaders(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
currentUser := getCurrentUser(r)
application := getCurrentApplication(r)
if application.IsReader(currentUser.Name) {
fn(w, r)
} else {
http.Redirect(w, r, "/", http.StatusFound)
}
}
}