feat: register route + repo accessing
This commit is contained in:
@ -1,21 +1,29 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"gitea.local/admin/hspguard/internal/repository"
|
||||
"gitea.local/admin/hspguard/internal/web"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type UserHandler struct{}
|
||||
type UserHandler struct {
|
||||
repo *repository.Queries
|
||||
}
|
||||
|
||||
func NewUserHandler() *UserHandler {
|
||||
return &UserHandler{}
|
||||
func NewUserHandler(repo *repository.Queries) *UserHandler {
|
||||
return &UserHandler{
|
||||
repo: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *UserHandler) RegisterRoutes(router chi.Router, api chi.Router) {
|
||||
router.Get("/login", h.loginPage)
|
||||
router.Get("/register", h.registerPage)
|
||||
api.Post("/register", h.register)
|
||||
}
|
||||
|
||||
func (h *UserHandler) loginPage(w http.ResponseWriter, r *http.Request) {
|
||||
@ -33,3 +41,54 @@ func (h *UserHandler) registerPage(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
web.RenderTemplate(w, "register", data)
|
||||
}
|
||||
|
||||
type RegisterParams struct {
|
||||
FullName string `json:"full_name"`
|
||||
Email string `json:"email"`
|
||||
PhoneNumber string `json:"phone"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func (h *UserHandler) register(w http.ResponseWriter, r *http.Request) {
|
||||
var params RegisterParams
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
if err := decoder.Decode(¶ms); err != nil {
|
||||
web.Error(w, "failed to parse request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if params.Email == "" || params.FullName == "" || params.Password == "" {
|
||||
web.Error(w, "missing required fields", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
_, err := h.repo.FindUserEmail(context.Background(), params.Email)
|
||||
if err == nil {
|
||||
web.Error(w, "user with provided email already exists", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
id, err := h.repo.InsertUser(context.Background(), repository.InsertUserParams{
|
||||
FullName: params.FullName,
|
||||
Email: params.Email,
|
||||
PasswordHash: params.Password,
|
||||
IsAdmin: false,
|
||||
})
|
||||
if err != nil {
|
||||
web.Error(w, "failed to create new user", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
encoder := json.NewEncoder(w)
|
||||
|
||||
type Response struct {
|
||||
Id string `json:"id"`
|
||||
}
|
||||
|
||||
if err := encoder.Encode(Response{
|
||||
Id: id.String(),
|
||||
}); err != nil {
|
||||
web.Error(w, "failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user