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.

73 lines
1.7 KiB

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