本站源代码
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.

64 lines
1.5KB

  1. package gitea
  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 Gitea.
  10. type Session struct {
  11. AuthURL string
  12. AccessToken string
  13. RefreshToken string
  14. ExpiresAt time.Time
  15. }
  16. var _ goth.Session = &Session{}
  17. // GetAuthURL will return the URL set by calling the `BeginAuth` function on the Gitea provider.
  18. func (s Session) GetAuthURL() (string, error) {
  19. if s.AuthURL == "" {
  20. return "", errors.New(goth.NoAuthUrlErrorMessage)
  21. }
  22. return s.AuthURL, nil
  23. }
  24. // Authorize the session with Gitea and return the access token to be stored for future use.
  25. func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
  26. p := provider.(*Provider)
  27. token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code"))
  28. if err != nil {
  29. return "", err
  30. }
  31. if !token.Valid() {
  32. return "", errors.New("Invalid token received from provider")
  33. }
  34. s.AccessToken = token.AccessToken
  35. s.RefreshToken = token.RefreshToken
  36. s.ExpiresAt = token.Expiry
  37. return token.AccessToken, err
  38. }
  39. // Marshal the session into a string
  40. func (s Session) Marshal() string {
  41. b, _ := json.Marshal(s)
  42. return string(b)
  43. }
  44. func (s Session) String() string {
  45. return s.Marshal()
  46. }
  47. // UnmarshalSession wil unmarshal a JSON string into a session.
  48. func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
  49. s := &Session{}
  50. err := json.NewDecoder(strings.NewReader(data)).Decode(s)
  51. return s, err
  52. }
上海开阖软件有限公司 沪ICP备12045867号-1