forked from mnacharov/grafana-datasource-oauth-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
57 lines (49 loc) · 1.37 KB
/
main.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
package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
)
type ForbidViewerProxy struct {
proxy httputil.ReverseProxy
}
func (m ForbidViewerProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("X-ID-Token")
if token == "" {
// grafana alerts goes to datasource without header
m.proxy.ServeHTTP(w, r)
} else {
email, err := GetEmailFromGoogleJWT(token)
if err != nil {
log.Printf("Error getting email from Google JWT: %s\n", err)
http.Error(w, "403 - Wrong JWT Token", http.StatusForbidden)
} else {
orgID := r.Header.Get("X-Grafana-Org-ID")
if isViewer(email, orgID) {
log.Printf("Viewer %s in orgId %s not allowed to use datasource\n", email, orgID)
http.Error(w, "403 - Viewer not allowed to use datasource", http.StatusForbidden)
} else {
m.proxy.ServeHTTP(w, r)
}
}
}
}
func NewForbidViewerProxy() ForbidViewerProxy {
target, err := url.Parse(os.Getenv("PROXY_ORIGIN_SERVER"))
if err != nil {
log.Fatal(err)
}
log.Printf("forwarding to -> %s\n", target)
proxy := httputil.NewSingleHostReverseProxy(target)
d := proxy.Director
proxy.Director = func(r *http.Request) {
d(r) // call default director
r.Host = target.Host // set Host header as expected by target
}
return ForbidViewerProxy{*proxy}
}
func main() {
log.Fatal(http.ListenAndServe(":8989", NewForbidViewerProxy()))
}