THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.5KB

  1. package google
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "strings"
  6. "time"
  7. "github.com/markbates/goth"
  8. )
  9. // Session stores data during the auth process with Google.
  10. type Session struct {
  11. AuthURL string
  12. AccessToken string
  13. RefreshToken string
  14. ExpiresAt time.Time
  15. }
  16. // GetAuthURL will return the URL set by calling the `BeginAuth` function on the Google provider.
  17. func (s Session) GetAuthURL() (string, error) {
  18. if s.AuthURL == "" {
  19. return "", errors.New(goth.NoAuthUrlErrorMessage)
  20. }
  21. return s.AuthURL, nil
  22. }
  23. // Authorize the session with Google and return the access token to be stored for future use.
  24. func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
  25. p := provider.(*Provider)
  26. token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code"))
  27. if err != nil {
  28. return "", err
  29. }
  30. if !token.Valid() {
  31. return "", errors.New("Invalid token received from provider")
  32. }
  33. s.AccessToken = token.AccessToken
  34. s.RefreshToken = token.RefreshToken
  35. s.ExpiresAt = token.Expiry
  36. return token.AccessToken, err
  37. }
  38. // Marshal the session into a string
  39. func (s Session) Marshal() string {
  40. b, _ := json.Marshal(s)
  41. return string(b)
  42. }
  43. func (s Session) String() string {
  44. return s.Marshal()
  45. }
  46. // UnmarshalSession will unmarshal a JSON string into a session.
  47. func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
  48. sess := &Session{}
  49. err := json.NewDecoder(strings.NewReader(data)).Decode(sess)
  50. return sess, err
  51. }