Go client for the Write.as API https://developers.write.as
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.

77 lines
1.8 KiB

  1. package writeas
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. )
  7. // LogIn authenticates a user with Write.as.
  8. // See https://developers.write.as/docs/api/#authenticate-a-user
  9. func (c *Client) LogIn(ctx context.Context, username, pass string) (*AuthUser, error) {
  10. u := &AuthUser{}
  11. up := struct {
  12. Alias string `json:"alias"`
  13. Pass string `json:"pass"`
  14. }{
  15. Alias: username,
  16. Pass: pass,
  17. }
  18. env, err := c.post(ctx, "/auth/login", up, u)
  19. if err != nil {
  20. return nil, err
  21. }
  22. var ok bool
  23. if u, ok = env.Data.(*AuthUser); !ok {
  24. return nil, fmt.Errorf("Wrong data returned from API.")
  25. }
  26. status := env.Code
  27. if status != http.StatusOK {
  28. if status == http.StatusBadRequest {
  29. return nil, fmt.Errorf("Bad request: %s", env.ErrorMessage)
  30. } else if status == http.StatusUnauthorized {
  31. return nil, fmt.Errorf("Incorrect password.")
  32. } else if status == http.StatusNotFound {
  33. return nil, fmt.Errorf("User does not exist.")
  34. } else if status == http.StatusTooManyRequests {
  35. return nil, fmt.Errorf("Too many log in attempts in a short period of time.")
  36. }
  37. return nil, fmt.Errorf("Problem authenticating: %d. %v\n", status, err)
  38. }
  39. c.SetToken(u.AccessToken)
  40. return u, nil
  41. }
  42. // LogOut logs the current user out, making the Client's current access token
  43. // invalid.
  44. func (c *Client) LogOut(ctx context.Context) error {
  45. env, err := c.delete(ctx, "/auth/me", nil)
  46. if err != nil {
  47. return err
  48. }
  49. status := env.Code
  50. if status != http.StatusNoContent {
  51. if status == http.StatusNotFound {
  52. return fmt.Errorf("Access token is invalid or doesn't exist")
  53. }
  54. return fmt.Errorf("Unable to log out: %v", env.ErrorMessage)
  55. }
  56. // Logout successful, so update the Client
  57. c.token = ""
  58. return nil
  59. }
  60. func (c *Client) isNotLoggedIn(code int) bool {
  61. if c.token == "" {
  62. return false
  63. }
  64. return code == http.StatusUnauthorized
  65. }