55 lines
1.5 KiB
Go
55 lines
1.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"git.keircn.com/keiran/termbox/internal/db"
|
|
"github.com/labstack/echo/v4"
|
|
)
|
|
|
|
func HandleRoot(c echo.Context) error {
|
|
return c.String(http.StatusOK, "Hello, World!")
|
|
}
|
|
|
|
func HandleRegister(c echo.Context) error {
|
|
var req db.CreateUserRequest
|
|
if err := c.Bind(&req); err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid request body"})
|
|
}
|
|
|
|
if req.Username == "" || req.Password == "" {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Username and password are required"})
|
|
}
|
|
|
|
user, err := db.CreateUser(c.Request().Context(), req)
|
|
if err != nil {
|
|
return c.JSON(http.StatusConflict, map[string]string{"error": "Username already exists"})
|
|
}
|
|
|
|
return c.JSON(http.StatusCreated, map[string]any{
|
|
"message": "User created successfully",
|
|
"user": user,
|
|
})
|
|
}
|
|
|
|
func HandleLogin(c echo.Context) error {
|
|
var req db.LoginRequest
|
|
if err := c.Bind(&req); err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid request body"})
|
|
}
|
|
|
|
if req.Username == "" || req.Password == "" {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Username and password are required"})
|
|
}
|
|
|
|
user, err := db.ValidateUserCredentials(c.Request().Context(), req.Username, req.Password)
|
|
if err != nil {
|
|
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "Invalid credentials"})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, map[string]any{
|
|
"message": "Login successful",
|
|
"user": user,
|
|
})
|
|
}
|