GET user by internal user id

This commit is contained in:
Brad Rydzewski 2020-02-07 09:19:32 -08:00
parent a6a9f69d2f
commit 93e8767f9c
2 changed files with 42 additions and 1 deletions

View file

@ -16,6 +16,7 @@ package users
import (
"net/http"
"strconv"
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/render"
@ -32,6 +33,17 @@ func HandleFind(users core.UserStore) http.HandlerFunc {
user, err := users.FindLogin(r.Context(), login)
if err != nil {
// the client can make a user request by providing
// the user id as opposed to the username. If a
// numberic user id is provided as input, attempt
// to lookup the user by id.
if id, _ := strconv.ParseInt(login, 10, 64); id != 0 {
user, err = users.Find(r.Context(), id)
if err == nil {
render.JSON(w, user, 200)
return
}
}
render.NotFound(w, err)
logger.FromRequest(r).Debugln("api: cannot find user")
} else {

View file

@ -12,8 +12,8 @@ import (
"net/http/httptest"
"testing"
"github.com/drone/drone/mock"
"github.com/drone/drone/core"
"github.com/drone/drone/mock"
"github.com/sirupsen/logrus"
"github.com/go-chi/chi"
@ -77,6 +77,35 @@ func TestUserFind(t *testing.T) {
}
}
func TestUserFindID(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
users := mock.NewMockUserStore(controller)
users.EXPECT().FindLogin(gomock.Any(), "1").Return(nil, sql.ErrNoRows)
users.EXPECT().Find(gomock.Any(), mockUser.ID).Return(mockUser, nil)
c := new(chi.Context)
c.URLParams.Add("user", "1")
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
r = r.WithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, c),
)
HandleFind(users)(w, r)
if got, want := w.Code, 200; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
got, want := &core.User{}, mockUser
json.NewDecoder(w.Body).Decode(got)
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
}
func TestUserFindErr(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()