Skip to content
This repository has been archived by the owner on Apr 26, 2021. It is now read-only.

Commit

Permalink
Adding support for listing a user keys
Browse files Browse the repository at this point in the history
  • Loading branch information
rochacon committed Apr 18, 2013
1 parent 42e0ac6 commit c2d2446
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
15 changes: 15 additions & 0 deletions api/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,21 @@ func RemoveKey(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Key \"%s\" successfully removed", kName)
}

func ListKeys(w http.ResponseWriter, r *http.Request) {
uName := r.URL.Query().Get(":name")
keys, err := user.ListKeys(uName)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
out, err := json.Marshal(&keys)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(out)
}

func NewUser(w http.ResponseWriter, r *http.Request) {
var usr user.User
if err := parseBody(r.Body, &usr); err != nil {
Expand Down
19 changes: 19 additions & 0 deletions api/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,25 @@ func (s *S) TestRemoveKeyShouldReturnErrorWithLineBreakAtEnd(c *C) {
c.Assert(b, Equals, "User \"Gandalf\" does not exists\n")
}

func (s *S) TestListKeysGivesExpectedSuccessResponse(c *C) {
keys := map[string]string{"key1": "ssh-key somekey gandalf@host1", "key2": "ssh-key somekey gandalf@host2"}
u, err := user.New("Gandalf", keys)
c.Assert(err, IsNil)
defer db.Session.User().RemoveId(u.Name)
url := "/user/Gandalf/keys?:name=Gandalf"
request, err := http.NewRequest("GET", url, nil)
c.Assert(err, IsNil)
recorder := httptest.NewRecorder()
ListKeys(recorder, request)
c.Assert(recorder.Code, Equals, 200)
body, err := ioutil.ReadAll(recorder.Body)
c.Assert(err, IsNil)
var data map[string]string
err = json.Unmarshal(body, &data)
c.Assert(err, IsNil)
c.Assert(data, DeepEquals, keys)
}

func (s *S) TestRemoveUser(c *C) {
u, err := user.New("username", map[string]string{})
c.Assert(err, IsNil)
Expand Down
11 changes: 11 additions & 0 deletions user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,14 @@ func RemoveKey(uName, kName string) error {
}
return removeKey(kContent, uName)
}

// ListKeys lists all user's keys
//
// If the user is not found, returns an error
func ListKeys(uName string) (map[string]string, error) {
var u User
if err := db.Session.User().FindId(uName).One(&u); err != nil {
return nil, fmt.Errorf(`User "%s" does not exists`, uName)
}
return u.Keys, nil
}

0 comments on commit c2d2446

Please sign in to comment.