From b922ddb1b30a26d2c42d63cb8de40753e29a6433 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torjus=20H=C3=A5kestad?= Date: Sun, 22 Oct 2023 22:56:07 +0200 Subject: [PATCH] Add get user endpoint --- model.go | 2 ++ server/server.go | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/model.go b/model.go index ed181ca..64cdf03 100644 --- a/model.go +++ b/model.go @@ -5,6 +5,7 @@ import "golang.org/x/crypto/bcrypt" type User struct { ID string `json:"id"` Username string `json:"username"` + Role string `json:"role"` HashedPassword []byte `json:"-"` } @@ -35,6 +36,7 @@ type ErrorResponse struct { type CreateUserRequest struct { Username string `json:"username"` Password string `json:"password"` + Role string `json:"role"` } type CreateUserResponse struct { diff --git a/server/server.go b/server/server.go index 798d4f9..480927d 100644 --- a/server/server.go +++ b/server/server.go @@ -40,6 +40,7 @@ func NewServer(config *Config) (*UserServer, error) { r.Get("/info", InfoHandler) r.With(verifyAdmin).Post("/", srv.CreateUserHandler) + r.Get("/{identifier}", srv.GetUserHandler) r.Post("/{identifier}/password", srv.SetPasswordHandler) r.Post("/{identifier}/verify", srv.VerifyHandler) @@ -52,6 +53,7 @@ func NewServer(config *Config) (*UserServer, error) { u := users.User{ ID: uuid.Must(uuid.NewRandom()).String(), Username: "admin", + Role: "admin", } password := uuid.Must(uuid.NewRandom()).String() _ = u.SetPassword(password) @@ -148,6 +150,29 @@ func (s *UserServer) CreateUserHandler(w http.ResponseWriter, r *http.Request) { _ = encoder.Encode(&response) } +func (s *UserServer) GetUserHandler(w http.ResponseWriter, r *http.Request) { + identifier := chi.URLParam(r, "identifier") + u, err := s.store.GetUser(identifier) + if err != nil { + switch err { + case store.ErrNoSuchUser: + WriteError(w, users.ErrorResponse{ + Message: fmt.Sprintf("No such user: %s", identifier), + Status: http.StatusNotFound, + }) + return + } + WriteError(w, users.ErrorResponse{ + Message: fmt.Sprintf("Unable to get user: %s", err), + Status: http.StatusInternalServerError, + }) + return + } + + encoder := json.NewEncoder(w) + _ = encoder.Encode(&u) +} + func (s *UserServer) SetPasswordHandler(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) defer r.Body.Close()