This repository has been archived by the owner on Feb 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
/
casauth.go
85 lines (72 loc) · 1.84 KB
/
casauth.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
package api
import (
"net/http"
"net/url"
"strings"
gc "gopkg.in/cas.v2"
"github.com/wtg/shuttletracker"
"github.com/wtg/shuttletracker/auth"
"github.com/wtg/shuttletracker/log"
)
// CASClient stores the local cas client and an instance of the database
type CASClient struct {
cas auth.AuthenticationService
us shuttletracker.UserService
authenticate bool
}
// CreateCASClient creates an authentication service CASClient using a cas url and database
func CreateCASClient(url *url.URL, us shuttletracker.UserService, authenticate bool) *CASClient {
client := gc.NewClient(&gc.Options{
URL: url,
Store: nil,
})
cli := &CASClient{
cas: &auth.CAS{
CAS: client,
},
us: us,
authenticate: authenticate,
}
return cli
}
// InjectMocks allows mock interfaces to be used
func InjectMocks(cli auth.AuthenticationService, us shuttletracker.UserService, auth bool) *CASClient {
c := &CASClient{
cas: cli,
us: us,
authenticate: auth,
}
return c
}
func (cli *CASClient) logout(w http.ResponseWriter, r *http.Request) {
cli.cas.Logout(w, r)
}
func (cli *CASClient) casauth(next http.Handler) http.Handler {
return cli.cas.HandleFunc(func(w http.ResponseWriter, r *http.Request) {
if !cli.authenticate {
// don't authenticate
next.ServeHTTP(w, r)
return
}
if !cli.cas.Authenticated(r) {
_, err := w.Write([]byte("redirecting to cas;"))
if err != nil {
log.WithError(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
cli.cas.Login(w, r)
} else {
auth, err := cli.us.UserExists(strings.ToLower(cli.cas.Username(r)))
if err != nil {
log.WithError(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
auth = false
}
if auth {
next.ServeHTTP(w, r)
return
}
http.Error(w, "unauthenticated", 401)
}
})
}