Skip to content
This repository has been archived by the owner on Dec 10, 2024. It is now read-only.

Commit

Permalink
Implement GET API for SSH Key of given user
Browse files Browse the repository at this point in the history
I've recently implemented this API in GitLab and will be available in
GitLab 14.9 and is already deployed on gitlab.com
  • Loading branch information
timofurrer committed Mar 13, 2022
1 parent bbf334f commit b0fce3c
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
20 changes: 20 additions & 0 deletions users.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,26 @@ func (s *UsersService) GetSSHKey(key int, options ...RequestOptionFunc) (*SSHKey
return k, resp, err
}

// GetSSHKeyForUser gets a single key for a given user.
//
// GitLab API docs: https://docs.gitlab.com/ee/api/users.html#single-ssh-key-for-given-user
func (s *UsersService) GetSSHKeyForUser(user int, key int, options ...RequestOptionFunc) (*SSHKey, *Response, error) {
u := fmt.Sprintf("users/%d/keys/%d", user, key)

req, err := s.client.NewRequest(http.MethodGet, u, nil, options)
if err != nil {
return nil, nil, err
}

k := new(SSHKey)
resp, err := s.client.Do(req, k)
if err != nil {
return nil, resp, err
}

return k, resp, err
}

// AddSSHKeyOptions represents the available AddSSHKey() options.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#add-ssh-key
Expand Down
36 changes: 36 additions & 0 deletions users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"fmt"
"net"
"net/http"
"reflect"
"testing"
"time"

Expand Down Expand Up @@ -612,3 +613,38 @@ func TestGetMemberships(t *testing.T) {
want := []*UserMembership{{SourceID: 1, SourceName: "Project one", SourceType: "Project", AccessLevel: 20}, {SourceID: 3, SourceName: "Group three", SourceType: "Namespace", AccessLevel: 20}}
assert.Equal(t, want, memberships)
}

func TestGetSingleSSHKeyForUser(t *testing.T) {
mux, server, client := setup(t)
defer teardown(server)

mux.HandleFunc("/api/v4/users/1/keys/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, http.MethodGet)
fmt.Fprint(w, `
{
"id": 1,
"title": "Public key",
"key": "ssh-rsa AAAA...",
"created_at": "2014-08-01T14:47:39.080Z"
}
`)
})

sshKey, _, err := client.Users.GetSSHKeyForUser(1, 1)
if err != nil {
t.Errorf("Users.GetSSHKeyForUser returned an error: %v", err)
}

wantCreatedAt := time.Date(2014, 8, 1, 14, 47, 39, 80000000, time.UTC)

want := &SSHKey{
ID: 1,
Title: "Public key",
Key: "ssh-rsa AAAA...",
CreatedAt: &wantCreatedAt,
}

if !reflect.DeepEqual(want, sshKey) {
t.Errorf("Users.GetSSHKeyForUser returned %+v, want %+v", sshKey, want)
}
}

0 comments on commit b0fce3c

Please sign in to comment.