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.

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