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

60 lines
1.4KB

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