google.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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(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("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) config() *oauth2.Config {
  47. return &oauth2.Config{
  48. RedirectURL: g.redirectURL,
  49. ClientID: g.clientID,
  50. ClientSecret: g.clientSecret,
  51. Scopes: []string{"email"},
  52. Endpoint: oauth2.Endpoint{
  53. AuthURL: "https://accounts.google.com/o/oauth2/auth",
  54. TokenURL: "https://accounts.google.com/o/oauth2/token",
  55. },
  56. }
  57. }
  58. func newGoogleProvider(clientID, clientSecret, redirectURL string) *googleProvider {
  59. return &googleProvider{clientID: clientID, clientSecret: clientSecret, redirectURL: redirectURL}
  60. }