Skip to content

Commit

Permalink
Merge branch 'master' into v2
Browse files Browse the repository at this point in the history
  • Loading branch information
geoffgarside committed Jul 27, 2017
2 parents ec9d178 + 3cccc01 commit 1b87d01
Show file tree
Hide file tree
Showing 2 changed files with 117 additions and 0 deletions.
89 changes: 89 additions & 0 deletions _examples/cas-chi.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
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)

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 := http.ListenAndServe(":9999", root); 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>
`
28 changes: 28 additions & 0 deletions middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package cas

import (
"net/http"

"github.com/golang/glog"
)

func (c *Client) Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if glog.V(2) {
glog.Infof("cas: handling %v request for %v", r.Method, r.URL)
}

setClient(r, c)

if !IsAuthenticated(r) {
RedirectToLogin(w, r)
return
}

if r.URL.Path == "/logout" {
RedirectToLogout(w, r)
return
}
h.ServeHTTP(w, r)
})
}

0 comments on commit 1b87d01

Please sign in to comment.