aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/controller/htmx/sign-in.go
blob: df600279e90f9e68602bcf40f8f5575a8df02200 (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
package HTMXController

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

	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"
)

func SignInPage(c *fiber.Ctx) error {

	return c.Render("sign-in/htmx-sign-in-page", fiber.Map{
		"PageTitle":    "Sign In",
		"NavBarActive": "sign-in",
		"FiberCtx":     c,
	}, "layouts/app-htmx")

}

func SignInAction(c *fiber.Ctx) error {

	var user model.User
	email := c.FormValue("email")
	password := c.FormValue("password")

	if email == "" || password == "" {

		return c.Render("sign-in/partials/sign-in-form", fiber.Map{
			"Errors": []string{
				"Email or password cannot be null.",
			},
			"IsOob": true,
		}, "layouts/app-htmx")
	}

	db := database.Get()

	db.Model(&user)
	err := db.Where(&model.User{Email: email}).
		First(&user).Error

	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return c.Render("sign-in/partials/sign-in-form", fiber.Map{
				"Errors": []string{
					"Email and password did not match.",
				},
			}, "layouts/app-htmx")
		}
	}

	if !user.CheckPassword(password) {

		return c.Render("sign-in/partials/sign-in-form", fiber.Map{
			"Errors": []string{
				"Email and password did not match.",
			},
		}, "layouts/app-htmx")
	}

	authentication.AuthStore(c, user.ID)

	return helper.HTMXRedirectTo("/", "/htmx/home", c)
}

func SignOut(c *fiber.Ctx) error {

	isAuthenticated, _ := authentication.AuthGet(c)
	if !isAuthenticated {
		return c.Redirect("/")
	}

	authentication.AuthDestroy(c)

	return helper.HTMXRedirectTo("/", "/htmx/home", c)
}