login.go 952 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package storageos
  2. import (
  3. "encoding/json"
  4. "errors"
  5. )
  6. var (
  7. // LoginAPIPrefix is a partial path to the HTTP endpoint.
  8. LoginAPIPrefix = "auth/login"
  9. // ErrLoginFailed is the error returned on an unsuccessful login.
  10. ErrLoginFailed = errors.New("failed to get token from API endpoint")
  11. )
  12. // Login attemps to get a token from the API
  13. func (c *Client) Login() (token string, err error) {
  14. resp, err := c.do("POST", LoginAPIPrefix, doOptions{data: struct {
  15. User string `json:"username"`
  16. Pass string `json:"password"`
  17. }{c.username, c.secret}})
  18. if err != nil {
  19. if _, ok := err.(*Error); ok {
  20. return "", ErrLoginFailed
  21. }
  22. return "", err
  23. }
  24. if resp.StatusCode != 200 {
  25. return "", ErrLoginFailed
  26. }
  27. unmarsh := struct {
  28. Token string `json:"token"`
  29. }{}
  30. if err := json.NewDecoder(resp.Body).Decode(&unmarsh); err != nil {
  31. return "", err
  32. }
  33. if unmarsh.Token == "" {
  34. return "", ErrLoginFailed
  35. }
  36. return unmarsh.Token, nil
  37. }