2024-07-14 10:57:40 +00:00
|
|
|
package handler
|
|
|
|
|
|
|
|
import (
|
2024-09-11 09:17:28 +00:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2024-09-11 10:21:58 +00:00
|
|
|
"regexp"
|
2024-09-11 09:17:28 +00:00
|
|
|
|
2024-07-14 10:57:40 +00:00
|
|
|
"git.ekzyis.com/ekzyis/delphi.market/server/router/context"
|
|
|
|
"git.ekzyis.com/ekzyis/delphi.market/server/router/pages"
|
|
|
|
"git.ekzyis.com/ekzyis/delphi.market/types"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
)
|
|
|
|
|
|
|
|
func HandleUser(sc context.Context) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
u := c.Get("session").(types.User)
|
2024-09-11 10:21:58 +00:00
|
|
|
return pages.User(&u, nil).Render(context.RenderContext(sc, c), c.Response().Writer)
|
2024-07-14 10:57:40 +00:00
|
|
|
}
|
|
|
|
}
|
2024-09-11 09:17:28 +00:00
|
|
|
|
|
|
|
func HandleUserEdit(sc context.Context) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
var (
|
|
|
|
db = sc.Db
|
|
|
|
ctx = c.Request().Context()
|
|
|
|
u = c.Get("session").(types.User)
|
|
|
|
name = c.FormValue("name")
|
|
|
|
|
|
|
|
maxLength = 16
|
2024-09-11 10:21:58 +00:00
|
|
|
errors types.UserEditError
|
2024-09-11 09:17:28 +00:00
|
|
|
err error
|
|
|
|
)
|
|
|
|
|
|
|
|
if name == "" {
|
2024-09-11 10:21:58 +00:00
|
|
|
errors.Name = "required"
|
2024-09-11 09:17:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if len(name) > maxLength {
|
2024-09-11 10:21:58 +00:00
|
|
|
errors.Name = fmt.Sprintf("%d characters too long", len(name)-maxLength)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !regexp.MustCompile(`^[a-zA-Z0-9_-]+$`).MatchString(name) {
|
|
|
|
errors.Name = "only letters, numbers, _ and - allowed"
|
|
|
|
}
|
|
|
|
|
|
|
|
if errors.Name != "" {
|
|
|
|
c.Response().WriteHeader(http.StatusBadRequest)
|
|
|
|
return pages.User(&u, &errors).Render(context.RenderContext(sc, c), c.Response().Writer)
|
2024-09-11 09:17:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err = db.QueryRowContext(ctx,
|
|
|
|
"UPDATE users SET name = $1 WHERE id = $2 RETURNING name",
|
|
|
|
name, u.Id).Scan(&u.Name); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-09-11 10:21:58 +00:00
|
|
|
return pages.User(&u, &errors).Render(context.RenderContext(sc, c), c.Response().Writer)
|
2024-09-11 09:17:28 +00:00
|
|
|
}
|
|
|
|
}
|