Skip to content

Commit

Permalink
Merge pull request #22 from storageos/add-login-method
Browse files Browse the repository at this point in the history
add login functionality to the client object
  • Loading branch information
JoeReid authored Sep 12, 2017
2 parents 102eaac + 57f972b commit 31e2926
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
46 changes: 46 additions & 0 deletions login.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package storageos

import (
"encoding/json"
"errors"
)

var (
// LoginAPIPrefix is a partial path to the HTTP endpoint.
LoginAPIPrefix = "auth/login"
ErrLoginFailed = errors.New("Failed to get token from API endpoint")
)

// Login attemps to get a token from the API
func (c *Client) Login() (token string, err error) {
resp, err := c.do("POST", LoginAPIPrefix, doOptions{data: struct {
User string `json:"username"`
Pass string `json:"password"`
}{c.username, c.secret}})

if err != nil {
if _, ok := err.(*Error); ok {
return "", ErrLoginFailed
}

return "", err
}

if resp.StatusCode != 200 {
return "", ErrLoginFailed
}

unmarsh := struct {
Token string `json:"token"`
}{}

if err := json.NewDecoder(resp.Body).Decode(&unmarsh); err != nil {
return "", err
}

if unmarsh.Token == "" {
return "", ErrLoginFailed
}

return unmarsh.Token, nil
}
52 changes: 52 additions & 0 deletions login_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package storageos

import (
"net/http"
"testing"
)

func TestLoginOK(t *testing.T) {
client := newTestClient(&FakeRoundTripper{message: `{"token":"superSecretToken"}`, status: http.StatusOK})
client.SetAuth("foo", "bar")

token, err := client.Login()
if err != nil {
t.Error(err)
}

if token != "superSecretToken" {
t.Errorf("Token got garbled: (%v) != (superSecretToken)", token)
}
}

func TestLoginBadCreds(t *testing.T) {
client := newTestClient(&FakeRoundTripper{message: "", status: http.StatusUnauthorized})
client.SetAuth("foo", "bar")

token, err := client.Login()
if err == nil {
t.Error("Expected and error")
}

if err != ErrLoginFailed {
t.Errorf("Expected login failed error got: %v", err)
}

if token != "" {
t.Error("token (%v) incorrectly returned", token)
}
}

func TestLoginEmptyToken(t *testing.T) {
client := newTestClient(&FakeRoundTripper{message: `{"token":""}`, status: http.StatusOK})
client.SetAuth("foo", "bar")

_, err := client.Login()
if err == nil {
t.Error("Expected and error")
}

if err != ErrLoginFailed {
t.Errorf("Expected login failed error got: %v", err)
}
}

0 comments on commit 31e2926

Please sign in to comment.