2019-01-30 16:52:47 +00:00
|
|
|
package provider
|
|
|
|
|
2019-09-18 17:55:52 +01:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
// "net/url"
|
|
|
|
|
|
|
|
"golang.org/x/oauth2"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Providers contains all the implemented providers
|
2019-01-30 16:52:47 +00:00
|
|
|
type Providers struct {
|
2019-04-18 15:07:39 +01:00
|
|
|
Google Google `group:"Google Provider" namespace:"google" env-namespace:"GOOGLE"`
|
2019-09-18 17:55:52 +01:00
|
|
|
OIDC OIDC `group:"OIDC Provider" namespace:"oidc" env-namespace:"OIDC"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// Provider is used to authenticate users
|
|
|
|
type Provider interface {
|
|
|
|
Name() string
|
|
|
|
GetLoginURL(redirectURI, state string) string
|
|
|
|
ExchangeCode(redirectURI, code string) (string, error)
|
|
|
|
GetUser(token string) (User, error)
|
|
|
|
Setup() error
|
2019-01-30 16:52:47 +00:00
|
|
|
}
|
|
|
|
|
2019-09-18 17:55:52 +01:00
|
|
|
type token struct {
|
2019-01-30 16:52:47 +00:00
|
|
|
Token string `json:"access_token"`
|
|
|
|
}
|
|
|
|
|
2019-09-18 17:55:52 +01:00
|
|
|
// User is the authenticated user
|
2019-01-30 16:52:47 +00:00
|
|
|
type User struct {
|
2019-09-18 17:55:52 +01:00
|
|
|
ID string `json:"id"`
|
2019-01-30 16:52:47 +00:00
|
|
|
Email string `json:"email"`
|
|
|
|
Verified bool `json:"verified_email"`
|
|
|
|
Hd string `json:"hd"`
|
|
|
|
}
|
2019-09-18 17:55:52 +01:00
|
|
|
|
|
|
|
// OAuthProvider is a provider using the oauth2 library
|
|
|
|
type OAuthProvider struct {
|
2020-06-11 12:24:51 +01:00
|
|
|
Resource string `long:"resource" env:"RESOURCE" description:"Optional resource indicator"`
|
|
|
|
|
2019-09-18 17:55:52 +01:00
|
|
|
Config *oauth2.Config
|
|
|
|
ctx context.Context
|
|
|
|
}
|
|
|
|
|
|
|
|
// ConfigCopy returns a copy of the oauth2 config with the given redirectURI
|
|
|
|
// which ensures the underlying config is not modified
|
|
|
|
func (p *OAuthProvider) ConfigCopy(redirectURI string) oauth2.Config {
|
|
|
|
config := *p.Config
|
|
|
|
config.RedirectURL = redirectURI
|
|
|
|
return config
|
|
|
|
}
|
|
|
|
|
|
|
|
// OAuthGetLoginURL provides a base "GetLoginURL" for proiders using OAauth2
|
|
|
|
func (p *OAuthProvider) OAuthGetLoginURL(redirectURI, state string) string {
|
|
|
|
config := p.ConfigCopy(redirectURI)
|
2020-06-11 12:24:51 +01:00
|
|
|
|
|
|
|
if p.Resource != "" {
|
|
|
|
return config.AuthCodeURL(state, oauth2.SetAuthURLParam("resource", p.Resource))
|
|
|
|
}
|
|
|
|
|
2019-09-18 17:55:52 +01:00
|
|
|
return config.AuthCodeURL(state)
|
|
|
|
}
|
|
|
|
|
|
|
|
// OAuthExchangeCode provides a base "ExchangeCode" for proiders using OAauth2
|
|
|
|
func (p *OAuthProvider) OAuthExchangeCode(redirectURI, code string) (*oauth2.Token, error) {
|
|
|
|
config := p.ConfigCopy(redirectURI)
|
|
|
|
return config.Exchange(p.ctx, code)
|
|
|
|
}
|