46 lines
1 KiB
Go
46 lines
1 KiB
Go
package api
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"git.ctrlz.es/mgdelacroix/craban/model"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func (a *API) CreateUser(w http.ResponseWriter, r *http.Request) {
|
|
user, _ := UserFromRequest(r)
|
|
if !user.Admin {
|
|
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
body := ParseBody(r)
|
|
username := body.String("username")
|
|
password := body.String("password")
|
|
name := body.String("name")
|
|
mail := body.String("mail")
|
|
admin := body.Bool("admin")
|
|
|
|
newUser := &model.User{
|
|
Username: username,
|
|
Password: password,
|
|
Name: name,
|
|
Mail: mail,
|
|
}
|
|
|
|
if err := newUser.IsValid(); err != nil {
|
|
http.Error(w, fmt.Sprintf("%s: %s", http.StatusText(http.StatusBadRequest), err), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
createdUser, err := a.App.CreateUser(username, password, name, mail, admin)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("user couldn't be created")
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
JSON(w, createdUser, 201)
|
|
}
|