Add get user endpoint

This commit is contained in:
Torjus Håkestad 2023-10-22 22:56:07 +02:00
parent a6be7e929a
commit b922ddb1b3
2 changed files with 27 additions and 0 deletions

View File

@ -5,6 +5,7 @@ import "golang.org/x/crypto/bcrypt"
type User struct { type User struct {
ID string `json:"id"` ID string `json:"id"`
Username string `json:"username"` Username string `json:"username"`
Role string `json:"role"`
HashedPassword []byte `json:"-"` HashedPassword []byte `json:"-"`
} }
@ -35,6 +36,7 @@ type ErrorResponse struct {
type CreateUserRequest struct { type CreateUserRequest struct {
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Password string `json:"password"`
Role string `json:"role"`
} }
type CreateUserResponse struct { type CreateUserResponse struct {

View File

@ -40,6 +40,7 @@ func NewServer(config *Config) (*UserServer, error) {
r.Get("/info", InfoHandler) r.Get("/info", InfoHandler)
r.With(verifyAdmin).Post("/", srv.CreateUserHandler) r.With(verifyAdmin).Post("/", srv.CreateUserHandler)
r.Get("/{identifier}", srv.GetUserHandler)
r.Post("/{identifier}/password", srv.SetPasswordHandler) r.Post("/{identifier}/password", srv.SetPasswordHandler)
r.Post("/{identifier}/verify", srv.VerifyHandler) r.Post("/{identifier}/verify", srv.VerifyHandler)
@ -52,6 +53,7 @@ func NewServer(config *Config) (*UserServer, error) {
u := users.User{ u := users.User{
ID: uuid.Must(uuid.NewRandom()).String(), ID: uuid.Must(uuid.NewRandom()).String(),
Username: "admin", Username: "admin",
Role: "admin",
} }
password := uuid.Must(uuid.NewRandom()).String() password := uuid.Must(uuid.NewRandom()).String()
_ = u.SetPassword(password) _ = u.SetPassword(password)
@ -148,6 +150,29 @@ func (s *UserServer) CreateUserHandler(w http.ResponseWriter, r *http.Request) {
_ = encoder.Encode(&response) _ = 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) { func (s *UserServer) SetPasswordHandler(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body) decoder := json.NewDecoder(r.Body)
defer r.Body.Close() defer r.Body.Close()