google.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. "encoding/json"
  8. "fmt"
  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(code string) (*Profile, error) {
  27. conf := g.config()
  28. ctx := context.Background()
  29. token, err := conf.Exchange(ctx, code)
  30. if err != nil {
  31. return nil, err
  32. }
  33. client := conf.Client(ctx, token)
  34. resp, err := client.Get("https://www.googleapis.com/oauth2/v3/userinfo")
  35. if err != nil {
  36. return nil, err
  37. }
  38. defer resp.Body.Close()
  39. var user googleProfile
  40. decoder := json.NewDecoder(resp.Body)
  41. if err := decoder.Decode(&user); err != nil {
  42. return nil, fmt.Errorf("unable to unserialize google profile: %v", err)
  43. }
  44. profile := &Profile{Key: g.GetUserExtraKey(), ID: user.Sub, Username: user.Email}
  45. return profile, nil
  46. }
  47. func (g googleProvider) config() *oauth2.Config {
  48. return &oauth2.Config{
  49. RedirectURL: g.redirectURL,
  50. ClientID: g.clientID,
  51. ClientSecret: g.clientSecret,
  52. Scopes: []string{"email"},
  53. Endpoint: oauth2.Endpoint{
  54. AuthURL: "https://accounts.google.com/o/oauth2/auth",
  55. TokenURL: "https://accounts.google.com/o/oauth2/token",
  56. },
  57. }
  58. }
  59. func newGoogleProvider(clientID, clientSecret, redirectURL string) *googleProvider {
  60. return &googleProvider{clientID: clientID, clientSecret: clientSecret, redirectURL: redirectURL}
  61. }