aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/controller/htmx/setting.go
blob: 28c138c8b0a32d613ba5c2caa8f1982e6c362c6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package HTMXController

import (
	"projecty/cmd/web/model"
	"projecty/internal"
	"projecty/internal/authentication"
	"projecty/internal/database"
	"projecty/internal/helper"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
)

func SettingPage(c *fiber.Ctx) error {

	var authenticatedUser model.User

	isAuthenticated, userID := authentication.AuthGet(c)

	if isAuthenticated {
		db := database.Get()
		db.Model(&authenticatedUser).
			Where("id = ?", userID).
			First(&authenticatedUser)
	}

	return c.Render("settings/htmx-setting-page", fiber.Map{
		"PageTitle":         "Settings",
		"NavBarActive":      "settings",
		"FiberCtx":          c,
		"AuthenticatedUser": authenticatedUser,
	}, "layouts/app-htmx")

}

func SettingAction(c *fiber.Ctx) error {

	var errorBag []string
	validate := internal.NewValidator()

	isAuthenticated, userID := authentication.AuthGet(c)
	if !isAuthenticated {
		return helper.HTMXRedirectTo("/sign-in", "/htmx/sign-in", c)
	}

	user := &model.User{
		ID:       userID,
		Image:    c.FormValue("image"),
		Name:     c.FormValue("name"),
		Bio:      c.FormValue("bio"),
		Email:    c.FormValue("email"),
		Password: c.FormValue("password"),
	}

	err := validate.Validate(user)
	if err != nil {
		for _, err := range err.(validator.ValidationErrors) {
			errorBag = append(errorBag, internal.ErrorMessage(err.Field(), err.Tag()))
		}

		return c.Render("settings/partials/form-message", fiber.Map{
			"IsOob":  true,
			"Errors": errorBag,
		}, "layouts/app-htmx")
	}

	if user.Password != "" {
		user.HashPassword()
	}

	db := database.Get()
	db.Model(user).Updates(user)

	return c.Render("settings/partials/htmx-form-message", fiber.Map{
		"IsOob":             true,
		"SuccessMessages":   []string{"Data successfully saved."},
		"NavBarActive":      "settings",
		"FiberCtx":          c,
		"AuthenticatedUser": user,
	}, "layouts/app-htmx")
}