47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/bootdotdev/learn-file-storage-s3-golang-starter/internal/auth"
|
|
"github.com/bootdotdev/learn-file-storage-s3-golang-starter/internal/database"
|
|
)
|
|
|
|
func (cfg *apiConfig) handlerUsersCreate(w http.ResponseWriter, r *http.Request) {
|
|
type parameters struct {
|
|
Password string `json:"password"`
|
|
Email string `json:"email"`
|
|
}
|
|
|
|
decoder := json.NewDecoder(r.Body)
|
|
params := parameters{}
|
|
err := decoder.Decode(¶ms)
|
|
if err != nil {
|
|
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters", err)
|
|
return
|
|
}
|
|
|
|
if params.Password == "" || params.Email == "" {
|
|
respondWithError(w, http.StatusBadRequest, "Email and password are required", nil)
|
|
return
|
|
}
|
|
|
|
hashedPassword, err := auth.HashPassword(params.Password)
|
|
if err != nil {
|
|
respondWithError(w, http.StatusInternalServerError, "Couldn't hash password", err)
|
|
return
|
|
}
|
|
|
|
user, err := cfg.db.CreateUser(database.CreateUserParams{
|
|
Email: params.Email,
|
|
Password: hashedPassword,
|
|
})
|
|
if err != nil {
|
|
respondWithError(w, http.StatusInternalServerError, "Couldn't create user", err)
|
|
return
|
|
}
|
|
|
|
respondWithJSON(w, http.StatusCreated, user)
|
|
}
|