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.

51 lines
1.2 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. func (c *Client) isNotLoggedIn(code int) bool {
  40. if c.token == "" {
  41. return false
  42. }
  43. return code == http.StatusUnauthorized
  44. }