-
Notifications
You must be signed in to change notification settings - Fork 117
/
auth.go
66 lines (57 loc) · 1.77 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
package auth
import (
"context"
"net/url"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/rilldata/rill/admin"
"github.com/rilldata/rill/admin/server/cookies"
"go.uber.org/zap"
"golang.org/x/oauth2"
)
// AuthenticatorOptions provides options for Authenticator
type AuthenticatorOptions struct {
AuthDomain string
AuthClientID string
AuthClientSecret string
ExternalURL string
FrontendURL string
}
// Authenticator wraps functionality for admin server auth.
// It provides endpoints for login/logout, creates users, issues cookie-based auth tokens, and provides middleware for authenticating requests.
// The implementation was derived from: https://auth0.com/docs/quickstart/webapp/golang/01-login.
type Authenticator struct {
logger *zap.Logger
admin *admin.Service
cookies *cookies.Store
opts *AuthenticatorOptions
oidc *oidc.Provider
oauth2 oauth2.Config
}
// NewAuthenticator creates an Authenticator.
func NewAuthenticator(logger *zap.Logger, adm *admin.Service, cookieStore *cookies.Store, opts *AuthenticatorOptions) (*Authenticator, error) {
oidcProvider, err := oidc.NewProvider(context.Background(), "https://"+opts.AuthDomain+"/")
if err != nil {
return nil, err
}
// Auth callback URL is fixed. See RegisterEndpoints.
redirectURL, err := url.JoinPath(opts.ExternalURL, "/auth/callback")
if err != nil {
return nil, err
}
oauth2Config := oauth2.Config{
ClientID: opts.AuthClientID,
ClientSecret: opts.AuthClientSecret,
RedirectURL: redirectURL,
Endpoint: oidcProvider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "email", "profile"},
}
a := &Authenticator{
logger: logger,
admin: adm,
cookies: cookieStore,
opts: opts,
oidc: oidcProvider,
oauth2: oauth2Config,
}
return a, nil
}