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.

74 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. c.SetToken(u.AccessToken)
  28. return u, nil
  29. } else if status == http.StatusBadRequest {
  30. return nil, fmt.Errorf("Bad request: %s", env.ErrorMessage)
  31. } else if status == http.StatusUnauthorized {
  32. return nil, fmt.Errorf("Incorrect password.")
  33. } else if status == http.StatusNotFound {
  34. return nil, fmt.Errorf("User does not exist.")
  35. } else if status == http.StatusTooManyRequests {
  36. return nil, fmt.Errorf("Stop repeatedly trying to log in.")
  37. }
  38. return nil, fmt.Errorf("Problem authenticating: %d. %v\n", status, err)
  39. }
  40. // LogOut logs the current user out, making the Client's current access token
  41. // invalid.
  42. func (c *Client) LogOut() error {
  43. env, err := c.delete("/auth/me", nil)
  44. if err != nil {
  45. return err
  46. }
  47. status := env.Code
  48. if status != http.StatusNoContent {
  49. if status == http.StatusNotFound {
  50. return fmt.Errorf("Access token is invalid or doesn't exist")
  51. }
  52. return fmt.Errorf("Unable to log out: %v", env.ErrorMessage)
  53. }
  54. // Logout successful, so update the Client
  55. c.token = ""
  56. return nil
  57. }
  58. func (c *Client) isNotLoggedIn(code int) bool {
  59. if c.token == "" {
  60. return false
  61. }
  62. return code == http.StatusUnauthorized
  63. }