forked from go-cas/cas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cas-chi.go
94 lines (78 loc) · 1.76 KB
/
cas-chi.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
package main
import (
"bytes"
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"github.com/go-chi/chi"
"github.com/shenshouer/cas"
)
var casURL = "http://[Your CAS SERVER URL]"
type templateBinding struct {
Username string
Attributes cas.UserAttributes
}
func main() {
url, _ := url.Parse(casURL)
client := cas.NewClient(&cas.Options{URL: url})
root := chi.NewRouter()
root.Use(client.Handler)
server := &http.Server{
Addr: ":9999",
Handler: client.Handle(root),
}
root.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/html")
tmpl, err := template.New("index.html").Parse(index_html)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, error_500, err)
return
}
binding := &templateBinding{
Username: cas.Username(r),
Attributes: cas.Attributes(r),
}
html := new(bytes.Buffer)
if err := tmpl.Execute(html, binding); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, error_500, err)
return
}
html.WriteTo(w)
})
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
const index_html = `<!DOCTYPE html>
<html>
<head>
<title>Welcome {{.Username}}</title>
</head>
<body>
<h1>Welcome {{.Username}} <a href="/logout">Logout</a></h1>
<p>Your attributes are:</p>
<ul>{{range $key, $values := .Attributes}}
<li>{{$len := len $values}}{{$key}}:{{if gt $len 1}}
<ul>{{range $values}}
<li>{{.}}</li>{{end}}
</ul>
{{else}} {{index $values 0}}{{end}}</li>{{end}}
</ul>
</body>
</html>
`
const error_500 = `<!DOCTYPE html>
<html>
<head>
<title>Error 500</title>
</head>
<body>
<h1>Error 500</h1>
<p>%v</p>
</body>
</html>
`