portfolio/api/handlers/userHandler.go
Darius klein 45ccb19245
Some checks failed
build and deploy portfolio / build (pull_request) Successful in 48s
build and deploy portfolio / publish-docs (pull_request) Successful in 4s
build and deploy portfolio / publish-portfolio (pull_request) Failing after 3s
login refactor
2025-05-09 21:31:48 +02:00

68 lines
1.4 KiB
Go

package handlers
import (
"context"
"encoding/json"
"net/http"
"portfolio/api/service/bcrypt"
"portfolio/api/service/validate"
"portfolio/api/types"
"portfolio/database/query"
"strconv"
)
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
var u *types.RegisterUser
if r.Header.Get("HX-Request") == "true" {
u = &types.RegisterUser{
Name: r.PostFormValue("name"),
Password: r.PostFormValue("password"),
Email: r.PostFormValue("email"),
//Role: user.Role(r.PostFormValue("role")),
}
} else {
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
InternalServerErrorHandler(w, err)
return
}
}
if !validate.UserIsValid(u) {
BadRequestHandler(w)
return
}
//hash password
u.Password, _ = bcrypt.HashPassword(u.Password)
if err := query.CreateUser(context.Background(), *u); err != nil {
UnprocessableEntityHandler(w, err)
return
}
w.WriteHeader(http.StatusCreated)
w.Write([]byte("user created"))
}
func GetUserHandler(w http.ResponseWriter, r *http.Request) {
userID, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
BadRequestHandler(w)
}
User, err := query.GetUser(context.Background(), userID)
if err != nil {
UnprocessableEntityHandler(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
if err = json.NewEncoder(w).Encode(User); err != nil {
InternalServerErrorHandler(w, err)
return
}
}