61 lines
1.2 KiB
Go
61 lines
1.2 KiB
Go
|
package config
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
"net/url"
|
||
|
"time"
|
||
|
|
||
|
"github.com/coreos/go-oidc/v3/oidc"
|
||
|
"golang.org/x/oauth2"
|
||
|
)
|
||
|
|
||
|
type OAuth2 struct {
|
||
|
ClientID string
|
||
|
ClientSecret string
|
||
|
ProviderURL string
|
||
|
Scopes []string
|
||
|
|
||
|
provider *oidc.Provider
|
||
|
}
|
||
|
|
||
|
func (o *OAuth2) Load(ctx context.Context) error {
|
||
|
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
|
||
|
defer cancel()
|
||
|
|
||
|
provider, err := oidc.NewProvider(ctx, o.ProviderURL)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
hasOpenIDScope := false
|
||
|
for _, scope := range o.Scopes {
|
||
|
if scope == oidc.ScopeOpenID {
|
||
|
hasOpenIDScope = true
|
||
|
break
|
||
|
}
|
||
|
}
|
||
|
if !hasOpenIDScope {
|
||
|
o.Scopes = append(o.Scopes, oidc.ScopeOpenID)
|
||
|
}
|
||
|
|
||
|
o.provider = provider
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (o OAuth2) GetConfig(postAuthPath string) *oauth2.Config {
|
||
|
params := url.Values{}
|
||
|
params.Add("dest", postAuthPath)
|
||
|
return &oauth2.Config{
|
||
|
ClientID: o.ClientID,
|
||
|
ClientSecret: o.ClientSecret,
|
||
|
RedirectURL: fmt.Sprintf("%s/auth/finish", C.Web.BaseURL),
|
||
|
Endpoint: o.provider.Endpoint(),
|
||
|
Scopes: append([]string{oidc.ScopeOpenID}, o.Scopes...),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (o OAuth2) UserInfo(ctx context.Context, tokenSource oauth2.TokenSource) (*oidc.UserInfo, error) {
|
||
|
return o.provider.UserInfo(ctx, tokenSource)
|
||
|
}
|