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.

session.go 1.3KB

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