本站源代码
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 bitbucket
  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 Bitbucket.
  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 Bitbucket 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 Bitbucket 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. // UnmarshalSession will unmarshal a JSON string into a session.
  44. func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
  45. sess := &Session{}
  46. err := json.NewDecoder(strings.NewReader(data)).Decode(sess)
  47. return sess, err
  48. }
  49. func (s Session) String() string {
  50. return s.Marshal()
  51. }
上海开阖软件有限公司 沪ICP备12045867号-1