4
0

google.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package oauth2 // import "miniflux.app/v2/internal/oauth2"
  4. import (
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "miniflux.app/v2/internal/model"
  9. "golang.org/x/oauth2"
  10. )
  11. type googleProfile struct {
  12. Sub string `json:"sub"`
  13. Email string `json:"email"`
  14. }
  15. type googleProvider struct {
  16. clientID string
  17. clientSecret string
  18. redirectURL string
  19. }
  20. func (g *googleProvider) GetUserExtraKey() string {
  21. return "google_id"
  22. }
  23. func (g *googleProvider) GetRedirectURL(state string) string {
  24. return g.config().AuthCodeURL(state)
  25. }
  26. func (g *googleProvider) GetProfile(ctx context.Context, code string) (*Profile, error) {
  27. conf := g.config()
  28. token, err := conf.Exchange(ctx, code)
  29. if err != nil {
  30. return nil, err
  31. }
  32. client := conf.Client(ctx, token)
  33. resp, err := client.Get("https://www.googleapis.com/oauth2/v3/userinfo")
  34. if err != nil {
  35. return nil, err
  36. }
  37. defer resp.Body.Close()
  38. var user googleProfile
  39. decoder := json.NewDecoder(resp.Body)
  40. if err := decoder.Decode(&user); err != nil {
  41. return nil, fmt.Errorf("oauth2: unable to unserialize google profile: %v", err)
  42. }
  43. profile := &Profile{Key: g.GetUserExtraKey(), ID: user.Sub, Username: user.Email}
  44. return profile, nil
  45. }
  46. func (g *googleProvider) PopulateUserCreationWithProfileID(user *model.UserCreationRequest, profile *Profile) {
  47. user.GoogleID = profile.ID
  48. }
  49. func (g *googleProvider) PopulateUserWithProfileID(user *model.User, profile *Profile) {
  50. user.GoogleID = profile.ID
  51. }
  52. func (g *googleProvider) UnsetUserProfileID(user *model.User) {
  53. user.GoogleID = ""
  54. }
  55. func (g *googleProvider) config() *oauth2.Config {
  56. return &oauth2.Config{
  57. RedirectURL: g.redirectURL,
  58. ClientID: g.clientID,
  59. ClientSecret: g.clientSecret,
  60. Scopes: []string{"email"},
  61. Endpoint: oauth2.Endpoint{
  62. AuthURL: "https://accounts.google.com/o/oauth2/auth",
  63. TokenURL: "https://accounts.google.com/o/oauth2/token",
  64. },
  65. }
  66. }
  67. func newGoogleProvider(clientID, clientSecret, redirectURL string) *googleProvider {
  68. return &googleProvider{clientID: clientID, clientSecret: clientSecret, redirectURL: redirectURL}
  69. }