portfolio/api/handlers/userHandler.go

69 lines
1.3 KiB
Go
Raw Normal View History

2024-05-16 17:59:21 +02:00
package handlers
import (
"context"
"encoding/json"
"net/http"
2024-05-19 17:49:20 +02:00
"portfolio/api/service/bcrypt"
"portfolio/api/service/validate"
2024-09-12 15:34:45 +02:00
"portfolio/api/types"
2024-05-16 17:36:44 +02:00
"portfolio/database/query"
"strconv"
)
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
2024-09-12 15:34:45 +02:00
var u *types.RegisterUser
2024-03-13 15:54:09 +01:00
isHtmx := r.Header.Get("HX-Request")
if isHtmx == "true" {
2024-09-12 15:34:45 +02:00
u = &types.RegisterUser{
2024-03-13 15:54:09 +01:00
Name: r.PostFormValue("name"),
2024-09-12 15:34:45 +02:00
//Role: user.Role(r.PostFormValue("role")),
2024-03-13 15:54:09 +01:00
}
} else {
2025-02-24 00:15:10 +01:00
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
2024-05-19 17:49:20 +02:00
InternalServerErrorHandler(w, err)
2025-02-24 00:15:10 +01:00
return
2024-03-13 15:54:09 +01:00
}
}
2024-09-12 15:34:45 +02:00
u.Password = "123"
2024-03-13 15:54:09 +01:00
if !validate.UserIsValid(u) {
BadRequestHandler(w)
return
}
2024-05-19 17:49:20 +02:00
//hash password
u.Password, _ = bcrypt.HashPassword(u.Password)
2025-02-24 00:15:10 +01:00
if err := query.CreateUser(context.Background(), *u); err != nil {
2024-05-19 17:49:20 +02:00
UnprocessableEntityHandler(w, err)
return
}
2025-02-24 00:15:10 +01:00
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 {
2024-03-13 15:54:09 +01:00
BadRequestHandler(w)
}
User, err := query.GetUser(context.Background(), userID)
if err != nil {
2024-07-04 12:32:48 +02:00
UnprocessableEntityHandler(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
2025-02-24 00:15:10 +01:00
if err = json.NewEncoder(w).Encode(User); err != nil {
2024-07-04 12:32:48 +02:00
InternalServerErrorHandler(w, err)
return
}
}