oidc.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package oauth2 // import "miniflux.app/oauth2"
  5. import (
  6. "context"
  7. "miniflux.app/model"
  8. "github.com/coreos/go-oidc"
  9. "golang.org/x/oauth2"
  10. )
  11. type oidcProvider struct {
  12. clientID string
  13. clientSecret string
  14. redirectURL string
  15. provider *oidc.Provider
  16. }
  17. func (o *oidcProvider) GetUserExtraKey() string {
  18. return "openid_connect_id"
  19. }
  20. func (o *oidcProvider) GetRedirectURL(state string) string {
  21. return o.config().AuthCodeURL(state)
  22. }
  23. func (o *oidcProvider) GetProfile(ctx context.Context, code string) (*Profile, error) {
  24. conf := o.config()
  25. token, err := conf.Exchange(ctx, code)
  26. if err != nil {
  27. return nil, err
  28. }
  29. userInfo, err := o.provider.UserInfo(ctx, oauth2.StaticTokenSource(token))
  30. if err != nil {
  31. return nil, err
  32. }
  33. profile := &Profile{Key: o.GetUserExtraKey(), ID: userInfo.Subject, Username: userInfo.Email}
  34. return profile, nil
  35. }
  36. func (o *oidcProvider) PopulateUserCreationWithProfileID(user *model.UserCreationRequest, profile *Profile) {
  37. user.OpenIDConnectID = profile.ID
  38. }
  39. func (o *oidcProvider) PopulateUserWithProfileID(user *model.User, profile *Profile) {
  40. user.OpenIDConnectID = profile.ID
  41. }
  42. func (o *oidcProvider) UnsetUserProfileID(user *model.User) {
  43. user.OpenIDConnectID = ""
  44. }
  45. func (o *oidcProvider) config() *oauth2.Config {
  46. return &oauth2.Config{
  47. RedirectURL: o.redirectURL,
  48. ClientID: o.clientID,
  49. ClientSecret: o.clientSecret,
  50. Scopes: []string{"openid", "email"},
  51. Endpoint: o.provider.Endpoint(),
  52. }
  53. }
  54. func newOidcProvider(ctx context.Context, clientID, clientSecret, redirectURL, discoveryEndpoint string) (*oidcProvider, error) {
  55. provider, err := oidc.NewProvider(ctx, discoveryEndpoint)
  56. if err != nil {
  57. return nil, err
  58. }
  59. return &oidcProvider{clientID: clientID, clientSecret: clientSecret, redirectURL: redirectURL, provider: provider}, nil
  60. }