This repository has been archived by the owner on Apr 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
handlers.go
79 lines (67 loc) · 1.99 KB
/
handlers.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
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
"github.com/markbates/goth/providers/cloudfoundry"
)
// Check if the user is logged in, otherwise forward to login page.
func rootHandler(res http.ResponseWriter, req *http.Request) {
s, _ := gothic.Store.Get(req, "uaa-proxy-session")
if s.Values["logged"] != true {
http.Redirect(res, req, "/auth", http.StatusTemporaryRedirect)
return
}
newProxy(s.Values["user_email"].(string)).ServeHTTP(res, req)
}
// Handle auth redirect
// TO FIX: setProviders is called to change the callback url on each request
func authHandler(res http.ResponseWriter, req *http.Request) {
forwardedURL := req.Header.Get(CF_FORWARDED_URL)
if forwardedURL != "" {
parsedURL, _ := url.Parse(forwardedURL)
req.URL.RawQuery = parsedURL.RawQuery
setProviders("https://" + parsedURL.Host + "/auth/callback")
}
gothic.BeginAuthHandler(res, req)
}
// Handle callbacks from oauth.
func callbackHandler(res http.ResponseWriter, req *http.Request) {
user, err := gothic.CompleteUserAuth(res, req)
if err != nil {
fmt.Fprintln(res, err)
return
}
s, err := gothic.Store.Get(req, "uaa-proxy-session")
s.Values["user_email"] = user.Email
s.Values["logged"] = true
gothic.Store.Save(req, res, s)
http.Redirect(res, req, "/", http.StatusTemporaryRedirect)
}
func newProxy(remote_user string) http.Handler {
proxy := &httputil.ReverseProxy{
Director: func(req *http.Request) {
forwardedURL := req.Header.Get(CF_FORWARDED_URL)
parsedURL, err := url.Parse(forwardedURL)
if err != nil {
log.Fatalln(err.Error())
}
req.URL = parsedURL
req.Host = parsedURL.Host
req.Header.Set("X-Auth-User", remote_user)
fmt.Println(req.Header)
},
}
return proxy
}
func setProviders(callbackURL string) {
provider := cloudfoundry.New(c.LoginURL, c.ClientKey, c.ClientSecret, callbackURL, "openid")
provider.Client = DefaultHttpClient()
goth.UseProviders(
provider,
)
}