forked from go-pkgz/auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
420 lines (371 loc) · 12.8 KB
/
auth.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Package auth provides "social login" with Github, Google, Facebook, Microsoft, Yandex and Battle.net as well as custom auth providers.
package auth
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/go-pkgz/rest"
"github.com/go-pkgz/auth/avatar"
"github.com/go-pkgz/auth/logger"
"github.com/go-pkgz/auth/middleware"
"github.com/go-pkgz/auth/provider"
"github.com/go-pkgz/auth/token"
)
// Client is a type of auth client
type Client struct {
Cid string
Csecret string
}
// Service provides higher level wrapper allowing to construct everything and get back token middleware
type Service struct {
logger logger.L
opts Opts
jwtService *token.Service
providers []provider.Service
authMiddleware middleware.Authenticator
avatarProxy *avatar.Proxy
issuer string
useGravatar bool
}
// Opts is a full set of all parameters to initialize Service
type Opts struct {
SecretReader token.Secret // reader returns secret for given site id (aud), required
ClaimsUpd token.ClaimsUpdater // updater for jwt to add/modify values stored in the token
SecureCookies bool // makes jwt cookie secure
TokenDuration time.Duration // token's TTL, refreshed automatically
CookieDuration time.Duration // cookie's TTL. This cookie stores JWT token
DisableXSRF bool // disable XSRF protection, useful for testing/debugging
DisableIAT bool // disable IssuedAt claim
// optional (custom) names for cookies and headers
JWTCookieName string // default "JWT"
JWTCookieDomain string // default empty
JWTHeaderKey string // default "X-JWT"
XSRFCookieName string // default "XSRF-TOKEN"
XSRFHeaderKey string // default "X-XSRF-TOKEN"
XSRFIgnoreMethods []string // disable XSRF protection for the specified request methods (ex. []string{"GET", "POST")}, default empty
JWTQuery string // default "token"
SendJWTHeader bool // if enabled send JWT as a header instead of cookie
SameSiteCookie http.SameSite // limit cross-origin requests with SameSite cookie attribute
Issuer string // optional value for iss claim, usually the application name, default "go-pkgz/auth"
URL string // root url for the rest service, i.e. http://blah.example.com, required
Validator token.Validator // validator allows to reject some valid tokens with user-defined logic
AvatarStore avatar.Store // store to save/load avatars, required (use avatar.NoOp to disable avatars support)
AvatarResizeLimit int // resize avatar's limit in pixels
AvatarRoutePath string // avatar routing prefix, i.e. "/api/v1/avatar", default `/avatar`
UseGravatar bool // for email based auth (verified provider) use gravatar service
AdminPasswd string // if presented, allows basic auth with user admin and given password
BasicAuthChecker middleware.BasicAuthFunc // user custom checker for basic auth, if one defined then "AdminPasswd" will ignored
AudienceReader token.Audience // list of allowed aud values, default (empty) allows any
AudSecrets bool // allow multiple secrets (secret per aud)
Logger logger.L // logger interface, default is no logging at all
RefreshCache middleware.RefreshCache // optional cache to keep refreshed tokens
}
// NewService initializes everything
func NewService(opts Opts) (res *Service) {
res = &Service{
opts: opts,
logger: opts.Logger,
authMiddleware: middleware.Authenticator{
Validator: opts.Validator,
AdminPasswd: opts.AdminPasswd,
BasicAuthChecker: opts.BasicAuthChecker,
RefreshCache: opts.RefreshCache,
},
issuer: opts.Issuer,
useGravatar: opts.UseGravatar,
}
if opts.Issuer == "" {
res.issuer = "go-pkgz/auth"
}
if opts.Logger == nil {
res.logger = logger.NoOp
}
jwtService := token.NewService(token.Opts{
SecretReader: opts.SecretReader,
ClaimsUpd: opts.ClaimsUpd,
SecureCookies: opts.SecureCookies,
TokenDuration: opts.TokenDuration,
CookieDuration: opts.CookieDuration,
DisableXSRF: opts.DisableXSRF,
DisableIAT: opts.DisableIAT,
JWTCookieName: opts.JWTCookieName,
JWTCookieDomain: opts.JWTCookieDomain,
JWTHeaderKey: opts.JWTHeaderKey,
XSRFCookieName: opts.XSRFCookieName,
XSRFHeaderKey: opts.XSRFHeaderKey,
SendJWTHeader: opts.SendJWTHeader,
JWTQuery: opts.JWTQuery,
Issuer: res.issuer,
AudienceReader: opts.AudienceReader,
AudSecrets: opts.AudSecrets,
SameSite: opts.SameSiteCookie,
})
if opts.SecretReader == nil {
jwtService.SecretReader = token.SecretFunc(func(string) (string, error) {
return "", fmt.Errorf("secrets reader not available")
})
res.logger.Logf("[WARN] no secret reader defined")
}
res.jwtService = jwtService
res.authMiddleware.JWTService = jwtService
res.authMiddleware.L = res.logger
if opts.AvatarStore != nil {
res.avatarProxy = &avatar.Proxy{
Store: opts.AvatarStore,
URL: opts.URL,
RoutePath: opts.AvatarRoutePath,
ResizeLimit: opts.AvatarResizeLimit,
L: res.logger,
}
if res.avatarProxy.RoutePath == "" {
res.avatarProxy.RoutePath = "/avatar"
}
}
return res
}
// Handlers gets http.Handler for all providers and avatars
func (s *Service) Handlers() (authHandler, avatarHandler http.Handler) {
ah := func(w http.ResponseWriter, r *http.Request) {
elems := strings.Split(r.URL.Path, "/")
if len(elems) < 2 {
w.WriteHeader(http.StatusBadRequest)
return
}
// list all providers
if elems[len(elems)-1] == "list" {
list := []string{}
for _, p := range s.providers {
list = append(list, p.Name())
}
rest.RenderJSON(w, list)
return
}
// allow logout without specifying provider
if elems[len(elems)-1] == "logout" {
if len(s.providers) == 0 {
w.WriteHeader(http.StatusBadRequest)
rest.RenderJSON(w, rest.JSON{"error": "providers not defined"})
return
}
s.providers[0].Handler(w, r)
return
}
// show user info
if elems[len(elems)-1] == "user" {
claims, _, err := s.jwtService.Get(r)
if err != nil || claims.User == nil {
w.WriteHeader(http.StatusUnauthorized)
msg := "user is nil"
if err != nil {
msg = err.Error()
}
rest.RenderJSON(w, rest.JSON{"error": msg})
return
}
rest.RenderJSON(w, claims.User)
return
}
// status of logged-in user
if elems[len(elems)-1] == "status" {
claims, _, err := s.jwtService.Get(r)
if err != nil || claims.User == nil {
rest.RenderJSON(w, rest.JSON{"status": "not logged in"})
return
}
rest.RenderJSON(w, rest.JSON{"status": "logged in", "user": claims.User.Name})
return
}
// regular auth handlers
provName := elems[len(elems)-2]
p, err := s.Provider(provName)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
rest.RenderJSON(w, rest.JSON{"error": fmt.Sprintf("provider %s not supported", provName)})
return
}
p.Handler(w, r)
}
return http.HandlerFunc(ah), http.HandlerFunc(s.avatarProxy.Handler)
}
// Middleware returns auth middleware
func (s *Service) Middleware() middleware.Authenticator {
return s.authMiddleware
}
// AddProviderWithUserAttributes adds provider with user attributes mapping
func (s *Service) AddProviderWithUserAttributes(name, cid, csecret string, userAttributes provider.UserAttributes) {
p := provider.Params{
URL: s.opts.URL,
JwtService: s.jwtService,
Issuer: s.issuer,
AvatarSaver: s.avatarProxy,
Cid: cid,
Csecret: csecret,
L: s.logger,
UserAttributes: userAttributes,
}
s.addProviderByName(name, p)
}
func (s *Service) addProviderByName(name string, p provider.Params) {
var prov provider.Provider
switch strings.ToLower(name) {
case "github":
prov = provider.NewGithub(p)
case "google":
prov = provider.NewGoogle(p)
case "facebook":
prov = provider.NewFacebook(p)
case "yandex":
prov = provider.NewYandex(p)
case "battlenet":
prov = provider.NewBattlenet(p)
case "microsoft":
prov = provider.NewMicrosoft(p)
case "twitter":
prov = provider.NewTwitter(p)
case "patreon":
prov = provider.NewPatreon(p)
case "dev":
prov = provider.NewDev(p)
default:
return
}
s.addProvider(prov)
}
func (s *Service) addProvider(prov provider.Provider) {
s.providers = append(s.providers, provider.NewService(prov))
s.authMiddleware.Providers = s.providers
}
// AddProvider adds provider for given name
func (s *Service) AddProvider(name, cid, csecret string) {
p := provider.Params{
URL: s.opts.URL,
JwtService: s.jwtService,
Issuer: s.issuer,
AvatarSaver: s.avatarProxy,
Cid: cid,
Csecret: csecret,
L: s.logger,
UserAttributes: map[string]string{},
}
s.addProviderByName(name, p)
}
// AddDevProvider with a custom host and port
func (s *Service) AddDevProvider(host string, port int) {
p := provider.Params{
URL: s.opts.URL,
JwtService: s.jwtService,
Issuer: s.issuer,
AvatarSaver: s.avatarProxy,
L: s.logger,
Port: port,
Host: host,
}
s.addProvider(provider.NewDev(p))
}
// AddAppleProvider allow SignIn with Apple ID
func (s *Service) AddAppleProvider(appleConfig provider.AppleConfig, privKeyLoader provider.PrivateKeyLoaderInterface) error {
p := provider.Params{
URL: s.opts.URL,
JwtService: s.jwtService,
Issuer: s.issuer,
AvatarSaver: s.avatarProxy,
L: s.logger,
}
// Error checking at create need for catch one when apple private key init
appleProvider, err := provider.NewApple(p, appleConfig, privKeyLoader)
if err != nil {
return fmt.Errorf("an AppleProvider creating failed: %w", err)
}
s.addProvider(appleProvider)
return nil
}
// AddCustomProvider adds custom provider (e.g. https://gopkg.in/oauth2.v3)
func (s *Service) AddCustomProvider(name string, client Client, copts provider.CustomHandlerOpt) {
p := provider.Params{
URL: s.opts.URL,
JwtService: s.jwtService,
Issuer: s.issuer,
AvatarSaver: s.avatarProxy,
Cid: client.Cid,
Csecret: client.Csecret,
L: s.logger,
}
s.addProvider(provider.NewCustom(name, p, copts))
}
// AddDirectProvider adds provider with direct check against data store
// it doesn't do any handshake and uses provided credChecker to verify user and password from the request
func (s *Service) AddDirectProvider(name string, credChecker provider.CredChecker) {
dh := provider.DirectHandler{
L: s.logger,
ProviderName: name,
Issuer: s.issuer,
TokenService: s.jwtService,
CredChecker: credChecker,
AvatarSaver: s.avatarProxy,
}
s.addProvider(dh)
}
// AddDirectProviderWithUserIDFunc adds provider with direct check against data store and sets custom UserIDFunc allows
// to modify user's ID on the client side.
// it doesn't do any handshake and uses provided credChecker to verify user and password from the request
func (s *Service) AddDirectProviderWithUserIDFunc(name string, credChecker provider.CredChecker, ufn provider.UserIDFunc) {
dh := provider.DirectHandler{
L: s.logger,
ProviderName: name,
Issuer: s.issuer,
TokenService: s.jwtService,
CredChecker: credChecker,
AvatarSaver: s.avatarProxy,
UserIDFunc: ufn,
}
s.addProvider(dh)
}
// AddVerifProvider adds provider user's verification sent by sender
func (s *Service) AddVerifProvider(name, msgTmpl string, sender provider.Sender) {
dh := provider.VerifyHandler{
L: s.logger,
ProviderName: name,
Issuer: s.issuer,
TokenService: s.jwtService,
AvatarSaver: s.avatarProxy,
Sender: sender,
Template: msgTmpl,
UseGravatar: s.useGravatar,
}
s.addProvider(dh)
}
// AddCustomHandler adds user-defined self-implemented handler of auth provider
func (s *Service) AddCustomHandler(p provider.Provider) {
s.addProvider(p)
}
// DevAuth makes dev oauth2 server, for testing and development only!
func (s *Service) DevAuth() (*provider.DevAuthServer, error) {
p, err := s.Provider("dev") // peak dev provider
if err != nil {
return nil, fmt.Errorf("dev provider not registered: %w", err)
}
// make and start dev auth server
return &provider.DevAuthServer{Provider: p.Provider.(provider.Oauth2Handler), L: s.logger}, nil
}
// Provider gets provider by name
func (s *Service) Provider(name string) (provider.Service, error) {
for _, p := range s.providers {
if p.Name() == name {
return p, nil
}
}
return provider.Service{}, fmt.Errorf("provider %s not found", name)
}
// Providers gets all registered providers
func (s *Service) Providers() []provider.Service {
return s.providers
}
// TokenService returns token.Service
func (s *Service) TokenService() *token.Service {
return s.jwtService
}
// AvatarProxy returns stored in service
func (s *Service) AvatarProxy() *avatar.Proxy {
return s.avatarProxy
}