-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
373 lines (346 loc) · 10 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package main
import (
"bytes"
"crypto/tls"
"encoding/gob"
"encoding/json"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
)
type AuthResponse struct {
AccessToken string `json:"access_token"`
Expiry int `json:"expires_in"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
Error string `json:"error"`
ErrorDesc string `json:"error_description"`
ClientID string `json:"client_id"`
}
type AuthServerResponse struct {
AuthServer struct {
URL string `json:"url"`
} `json:"auth-server"`
App struct {
Name string `json:"name"`
} `json:"app"`
}
var (
// key must be 16, 24 or 32 bytes long (AES-128, AES-192 or AES-256)
keyVal = os.Getenv("COOKIE_KEY")
key = []byte(keyVal)
store = sessions.NewCookieStore(key)
uaaServer = os.Getenv("UAA_SERVER")
uiSslCert = os.Getenv("UI_SSL_CERT")
uiSslKey = os.Getenv("UI_SSL_KEY")
cookieName = os.Getenv("COOKIE_NAME")
clientID = os.Getenv("CLIENT_ID")
clientSecret = os.Getenv("CLIENT_SECRET")
uiUrl = os.Getenv("UI_URL") //used for callback url
httpsPort = os.Getenv("HTTPS_PORT")
)
type ServerInfo struct {
App struct {
Version string `json:"version"`
} `json:"app"`
Links struct {
Uaa string `json:"uaa"`
Passwd string `json:"passwd"`
Login string `json:"login"`
Register string `json:"register"`
} `json:"links"`
ZoneName string `json:"zone_name"`
EntityID string `json:"entityID"`
CommitID string `json:"commit_id"`
IDPDefinitions map[string]string `json:"idpDefinitions"`
Prompts map[string][]string `json:"prompts"`
Timestamp string `json:"timestamp"`
}
type CredentialPageData struct {
PageTitle string
ServerInfo ServerInfo
UserName string
Flash Flash
}
/*
Function that will validate JWT
*/
func ValidateToken(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
session := GetSession(w, req, cookieName)
accessToken, setbool := session.Values["access_token"].(string)
if setbool == true && accessToken == "" {
RedirectLogin(w, req)
//return
} else if setbool == false {
RedirectLogin(w, req)
} else {
var p jwt.Parser
token, _, _ := p.ParseUnverified(accessToken, &jwt.StandardClaims{})
if err := token.Claims.Valid(); err != nil {
//invalid
RedirectLogin(w, req)
//return
} else {
//valid
next(w, req)
//return
}
}
//RedirectLogin(w, r)
return
})
}
/*
Main
*/
func main() {
keyValVar := flag.String("cookie-key", "", "Must be 16, 24 or 32 bytes long (AES-128, AES-192 or AES-256)")
cookieNameVar := flag.String("cookie-name", "auth-cookie", "Name of the cookie to use (auth-cookie)")
uaaServerVar := flag.String("uaa-server", "", "URL of CredHub server to target (https://<ip-or-host>:<port>)")
uiSslCertVar := flag.String("ui-ssl-cert", "", "SSL certificate for the web frontend (server.crt)")
uiSslKeyVar := flag.String("ui-ssl-key", "", "SSL certificate key for the web frontend (server.key)")
clientIDVar := flag.String("client-id", "", "Client ID that has uaa authorization")
clientSecretVar := flag.String("client-secret", "", "Secret for the Client ID")
uiUrlVar := flag.String("ui-url", "", "URL of this UI (https://<ip-or-host>:<port>)")
httpsPortVar := flag.String("https-port", "", "HTTPS port to listen on")
flag.Parse()
if len(os.Getenv("UAA_SERVER")) == 0 {
if *uaaServerVar != "" {
uaaServer = *uaaServerVar
} else {
log.Fatalln("CREDHUB_SERVER not set")
}
}
if len(os.Getenv("COOKIE_NAME")) == 0 {
if *cookieNameVar != "" {
cookieName = *cookieNameVar
} else {
log.Fatalln("COOKIE_NAME not set")
}
}
if len(os.Getenv("COOKIE_KEY")) == 0 {
if *keyValVar != "" {
keyVal = *keyValVar
key = []byte(keyVal)
store = sessions.NewCookieStore(key)
} else {
log.Fatalln("COOKIE_NAME not set")
}
}
if len(os.Getenv("UI_SSL_CERT")) == 0 {
if *uiSslCertVar != "" {
uiSslCert = *uiSslCertVar
} else {
log.Fatalln("UI_SSL_CERT not set")
}
}
if len(os.Getenv("UI_SSL_KEY")) == 0 {
if *uiSslKeyVar != "" {
uiSslKey = *uiSslKeyVar
} else {
log.Fatalln("UI_SSL_KEY not set")
}
}
if len(os.Getenv("CLIENT_ID")) == 0 {
if *clientIDVar != "" {
clientID = *clientIDVar
} else {
log.Fatalln("CLIENT_ID not set")
}
}
if len(os.Getenv("CLIENT_SECRET")) == 0 {
if *clientSecretVar != "" {
clientSecret = *clientSecretVar
} else {
clientSecret = "" //allow empty secret?
//log.Fatalln("CLIENT_SECRET not set")
}
}
if len(os.Getenv("UI_URL")) == 0 {
if *uiUrlVar != "" {
uiUrl = *uiUrlVar
} else {
log.Fatalln("UI_URL not set")
}
}
if len(os.Getenv("HTTPS_PORT")) == 0 {
if *httpsPortVar != "" {
httpsPort = *httpsPortVar
} else {
httpsPort = "8443"
}
}
gob.Register(Flash{})
log.SetFlags(log.Ldate | log.Ltime)
store.Options = &sessions.Options{
Path: "/",
MaxAge: 86400,
HttpOnly: true,
}
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //ignore cert for now FIX: add uaa certificate as environment variables on startup
r := mux.NewRouter()
r.HandleFunc("/login", Login)
r.HandleFunc("/login/callback", LoginCallback)
r.HandleFunc("/logout", Logout)
r.HandleFunc("/favicon.ico", FaviconHandler)
r.HandleFunc("/", ValidateToken(DisplayUAAInfo))
r.HandleFunc("/list/users", ValidateToken(ListUsers))
r.HandleFunc("/list/clients", ValidateToken(ListOAuthClients))
r.HandleFunc("/list/zones", ValidateToken(ListZones))
r.HandleFunc("/list/providers", ValidateToken(ListProviders))
r.HandleFunc("/list/groups/external", ValidateToken(ListExternalGroups))
err := http.ListenAndServeTLS(":"+httpsPort, uiSslCert, uiSslKey, LogRequest(r))
if err != nil {
fmt.Println(err)
}
}
/*
Function used to print requests to log
*/
func LogRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
/*
turn map into string for json display in view
*/
func MapToString(mapVal map[string]interface{}) string {
retBytes, _ := json.Marshal(mapVal)
return string(retBytes)
}
/*
Function that takes an api query string, makes the request to UAA and returns a byte array, flash message and the user name(from JWT) for displaying on pages
*/
func ClientRequest(w http.ResponseWriter, r *http.Request, apiQuery string) ([]byte, Flash, string) {
session := GetSession(w, r, cookieName)
accessToken := session.Values["access_token"].(string)
var netClient = &http.Client{
Timeout: time.Second * 10,
}
req, _ := http.NewRequest("GET", uaaServer+apiQuery, bytes.NewBuffer([]byte("")))
req.Header.Add("authorization", "bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, reqErr := netClient.Do(req)
if reqErr != nil {
fmt.Println(reqErr)
http.Error(w, "Error", http.StatusBadRequest)
return []byte(""), Flash{}, ""
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
uaaRespBytes := []byte(body)
flashsession := GetSession(w, r, "flash-cookie")
flashes := flashsession.Flashes()
flash := Flash{
Display: false,
}
if len(flashes) > 0 {
flash = flashes[0].(Flash)
}
var p jwt.Parser
claims := jwt.MapClaims{}
_, _, _ = p.ParseUnverified(accessToken, claims)
userNameVal := ""
if val, ok := claims["user_name"]; ok {
userNameVal = val.(string)
} else {
userNameVal = claims["client_id"].(string)
}
return uaaRespBytes, flash, userNameVal
}
/*
Make a client request to UAA and display the info on a page
*/
func DisplayUAAInfo(w http.ResponseWriter, r *http.Request) {
apiQuery := "/info"
uaaRespBytes, flash, userNameVal := ClientRequest(w, r, apiQuery)
uaaResp := ServerInfo{}
if uaaServErr := json.Unmarshal([]byte(uaaRespBytes), &uaaResp); uaaServErr != nil {
fmt.Println(uaaServErr)
}
data := CredentialPageData{
PageTitle: "UAA Info",
ServerInfo: uaaResp,
UserName: userNameVal,
Flash: flash,
}
tmpl := template.Must(template.ParseFiles("templates/uaainfo.html", "templates/base.html"))
tmpl.ExecuteTemplate(w, "base", data)
}
/*
Function that will return a blank page
*/
func ReturnBlank(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, "")
}
/*
Function that will redirect user to /
*/
func RedirectHome(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusSeeOther)
}
/*
Function that will redirect user to log in page
*/
func RedirectLogin(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
/*
Function return the facivon
*/
func FaviconHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "favicon.ico")
}
/*
Function to get a session
*/
func GetSession(w http.ResponseWriter, r *http.Request, sessionCookie string) *sessions.Session {
session, err := store.Get(r, sessionCookie)
if err != nil {
fmt.Printf("session error")
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
return session
}
/*
Function to add a flash message to sessions
*/
func AddFlash(w http.ResponseWriter, r *http.Request, flashMessage string, flashType string) {
flashsession := GetSession(w, r, "flash-cookie")
flash := Flash{
Type: flashType,
Message: flashMessage,
Display: true,
}
flashsession.AddFlash(flash)
flashsession.Save(r, w)
}
/*
Function that will check error type
*/
func CheckError(w http.ResponseWriter, r *http.Request, responseBody []byte, defaultFlashMessage string, defaultFlashType string) {
var rawJson map[string]interface{}
json.Unmarshal(responseBody, &rawJson)
for a, b := range rawJson {
// Currently only looks for error types, but could add an else for generic errors if there are any
if a == "error" {
AddFlash(w, r, b.(string), "danger")
return
}
}
AddFlash(w, r, defaultFlashMessage, defaultFlashType)
return
}