-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (88 loc) · 2.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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"os"
"fmt"
"log"
"strings"
"io/ioutil"
"net/http"
"encoding/json"
"github.com/go-martini/martini"
gooauth2 "github.com/golang/oauth2"
"github.com/martini-contrib/oauth2"
"github.com/martini-contrib/sessions"
)
type User struct {
User_id string
User_name string
Email string
}
type Vcap struct {
Uris []string
}
func oauth_get(url string, tokens oauth2.Tokens) []byte {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer " + tokens.Access())
client := http.Client{}
res, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
body, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
return body
}
func main() {
var v Vcap
err := json.Unmarshal([]byte(os.Getenv("VCAP_APPLICATION")), &v)
if err != nil {
log.Fatal(err)
}
m := martini.Classic()
app_uri := v.Uris[0]
cfhost := strings.SplitAfterN(app_uri, ".", 2)[1]
oauthOpts := &gooauth2.Options{
ClientID: os.Getenv("CLIENT_ID"),
ClientSecret: os.Getenv("CLIENT_SECRET"),
RedirectURL: "https://" + app_uri + "/oauth2callback",
Scopes: []string{""},
}
cf := oauth2.NewOAuth2Provider(
oauthOpts,
"https://login." + cfhost + "/oauth/authorize",
"http://uaa." + cfhost + "/oauth/token",
)
m.Get("/oauth2error", func() string {
log.Fatal("oAuth error")
return "oAuth error :("
})
m.Handlers(
sessions.Sessions("session", sessions.NewCookieStore([]byte("secret123"))),
cf,
oauth2.LoginRequired,
martini.Logger(),
martini.Static("public"),
)
m.Get("/", func(tokens oauth2.Tokens) string {
if tokens.IsExpired() {
return "Not logged in, or the access token is expired"
}
// oAuth user information from the UAA
body := oauth_get("http://uaa." + cfhost + "/userinfo", tokens)
var u User
err := json.Unmarshal(body, &u)
if err != nil {
log.Fatal(err)
}
// Example actual API call to get the list of spaces the user belongs to
space_body := oauth_get("http://api." + cfhost + "/v2/users/" + u.User_id + "/spaces", tokens)
return fmt.Sprintf("User ID: %s\n\nSpaces info: %s", u.User_id, space_body)
})
m.Run()
}