-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathssgo.go
174 lines (154 loc) · 4.86 KB
/
ssgo.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
package ssgo
import (
"fmt"
"math/rand"
"net/http"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
)
//Like an http.HandleFunc, but accepts a credentials object as a third argument.
type AuthenticatedHandler func(w http.ResponseWriter, r *http.Request, credentials *Credentials)
//Core interface for working with a third-party website
type SSO interface {
//Redirect the request to the provider's authorization page
RedirectToLogin(w http.ResponseWriter, r *http.Request)
//Handle callback from authorization page. This needs to be hosted at the url that is registered with the provider.
ExchangeCodeForToken(w http.ResponseWriter, r *http.Request)
//Lookup the credentials for a given request from the cookie. Will return nil if no valid cookie is found.
LookupToken(r *http.Request) *Credentials
//Basic http handler that looks up the token for you and provides credentials to your handler. Credentials may be nil.
Handle(handler AuthenticatedHandler) http.HandlerFunc
//Select a handler based on whether the user has a valid cookie or not.
Route(loggedOut http.HandlerFunc, loggedIn AuthenticatedHandler) http.HandlerFunc
ClearCookie(w http.ResponseWriter)
}
type sso struct {
conf *oauth2.Config
states map[string]time.Time
site string
authOpts []oauth2.AuthCodeOption
}
//Container for a user's oauth credentials
type Credentials struct {
// Shortname of site they are authenticated with
Site string
// Oauth token for user.
Token *oauth2.Token
// Http client with oauth credentials ready to go.
Client *http.Client
}
func NewGithub(clientId, clientSecret string, scopes ...string) SSO {
return newSSO(clientId, clientSecret, "", "github", github.Endpoint, scopes, nil)
}
func NewReddit(clientId, clientSecret, redirectUri string, scopes ...string) SSO {
endpoint := oauth2.Endpoint{
AuthURL: "https://www.reddit.com/api/v1/authorize",
TokenURL: "https://www.reddit.com/api/v1/access_token",
}
return newSSO(clientId, clientSecret, redirectUri, "reddit", endpoint, scopes, []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("duration", "permanent")})
}
func newSSO(clientId, clientSecret, redirectUri, site string, endpoint oauth2.Endpoint, scopes []string, opts []oauth2.AuthCodeOption) SSO {
conf := oauth2.Config{}
conf.Endpoint = endpoint
conf.ClientID = clientId
conf.ClientSecret = clientSecret
conf.Scopes = scopes
if redirectUri != "" {
conf.RedirectURL = redirectUri
}
s := &sso{
conf: &conf,
states: map[string]time.Time{},
site: site,
authOpts: opts,
}
EnsureBoltBucketExists(s.bucketName())
return s
}
func (s *sso) RedirectToLogin(w http.ResponseWriter, r *http.Request) {
state := randSeq(10)
s.states[state] = time.Now()
http.Redirect(w, r, s.conf.AuthCodeURL(state, s.authOpts...), 302)
}
func (s *sso) ExchangeCodeForToken(w http.ResponseWriter, r *http.Request) {
var err error
defer func() {
url := "/"
if err != nil {
url += "?ssoError=" + err.Error()
}
http.Redirect(w, r, url, 302)
}()
state := r.FormValue("state")
if _, ok := s.states[state]; state == "" || !ok {
err = fmt.Errorf("bad-state")
return
}
code := r.FormValue("code")
if code == "" {
err = fmt.Errorf("no-code")
return
}
tok, err := s.conf.Exchange(oauth2.NoContext, code)
if err != nil {
return
}
cookieVal := randSeq(25)
err = StoreBoltJson(s.bucketName(), cookieVal, tok)
if err != nil {
return
}
http.SetCookie(w, &http.Cookie{Name: s.cookieName(), Value: cookieVal, Path: "/", Expires: time.Now().Add(90 * 24 * time.Hour)})
}
func (s *sso) ClearCookie(w http.ResponseWriter) {
c := &http.Cookie{Name: s.cookieName(), Value: "", Path: "/", Expires: time.Now().Add(-1 * time.Hour), MaxAge: -1}
http.SetCookie(w, c)
}
func (s *sso) LookupToken(r *http.Request) *Credentials {
cookie, err := r.Cookie(s.cookieName())
if err != nil {
return nil
}
tok := oauth2.Token{}
err = LookupBoltJson(s.bucketName(), cookie.Value, &tok)
if err != nil || tok.AccessToken == "" {
return nil
}
return &Credentials{
Site: s.site,
Token: &tok,
Client: s.conf.Client(oauth2.NoContext, &tok),
}
}
func (s *sso) Handle(handler AuthenticatedHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tok := s.LookupToken(r)
handler(w, r, tok)
}
}
func (s *sso) Route(loggedOut http.HandlerFunc, loggedIn AuthenticatedHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tok := s.LookupToken(r)
if tok == nil {
loggedOut(w, r)
} else {
loggedIn(w, r, tok)
}
}
}
func (s *sso) bucketName() string {
return s.site + "Tokens"
}
func (s *sso) cookieName() string {
return s.site + "Tok"
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
var r = rand.New(rand.NewSource(time.Now().UnixNano()))
func randSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[r.Intn(len(letters))]
}
return string(b)
}