Add test for api user create
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
Torjus Håkestad 2022-01-22 10:19:18 +01:00
parent 121b0396fa
commit f664c886eb
2 changed files with 66 additions and 1 deletions

View File

@ -220,7 +220,7 @@ func (s *HTTPServer) HandlerAPIUserCreate(w http.ResponseWriter, r *http.Request
}
// TODO: Ensure user does not already exist
user := &users.User{Username: req.Username}
user := &users.User{Username: req.Username, Role: users.RoleUser}
if err := user.SetPassword(req.Password); err != nil {
s.Logger.Warnw("Error setting user password.", "req_id", reqID, "error", err, "remote_addr", r.RemoteAddr)
w.WriteHeader(http.StatusBadRequest)

View File

@ -16,6 +16,7 @@ import (
"git.t-juice.club/torjus/gpaste/api"
"git.t-juice.club/torjus/gpaste/files"
"git.t-juice.club/torjus/gpaste/users"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
)
@ -183,4 +184,68 @@ func TestHandlers(t *testing.T) {
t.Fatalf("Unable to validate received token: %s", err)
}
})
t.Run("User", func(t *testing.T) {
t.Run("Create", func(t *testing.T) {
hs := newServer()
adminPw := "admin"
admin := &users.User{
Username: "admin",
Role: users.RoleAdmin,
}
_ = admin.SetPassword(adminPw)
_ = hs.Users.Store(admin)
token, err := hs.Auth.Login(admin.Username, adminPw)
if err != nil {
t.Fatalf("error getting admin token: %s", err)
}
requestData := &api.RequestAPIUserCreate{
Username: "test",
Password: "test",
}
body := new(bytes.Buffer)
encoder := json.NewEncoder(body)
if err := encoder.Encode(requestData); err != nil {
t.Fatalf("Error encoding data: %s", err)
}
rr := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/user", body)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
hs.Handler.ServeHTTP(rr, req)
if rr.Result().StatusCode != http.StatusAccepted {
t.Fatalf("Create returned wrong status: %s", rr.Result().Status)
}
user, err := hs.Users.Get(requestData.Username)
if err != nil {
t.Fatalf("Unable to get user after create: %s", err)
}
expectedUser := &users.User{
Username: requestData.Username,
Role: users.RoleUser,
}
ignorePW := cmp.FilterPath(func(p cmp.Path) bool {
return p.String() == "HashedPassword"
}, cmp.Ignore())
if diff := cmp.Diff(user, expectedUser, ignorePW); diff != "" {
t.Errorf("User does not match expected: %s", diff)
}
})
})
}
func newServer() *api.HTTPServer {
cfg := &gpaste.ServerConfig{
SigningSecret: "abc123",
Store: &gpaste.ServerStoreConfig{
Type: "memory",
},
URL: "http://localhost:8080",
}
return api.NewHTTPServer(cfg)
}