Socialify

Folder ..

Viewing auth.go
71 lines (55 loc) • 1.8 KB

 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
package controllers

import (
	"majin/internal/auth"
	"majin/templates"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/session"
)

func LoginView(c *fiber.Ctx) error {
	if auth.IsAuthenticated(c) {
		return c.Redirect("/mail")
	}
	return templates.Login().Render(c.Context(), c.Response().BodyWriter())
}

func Login(c *fiber.Ctx) error {
	store, ok := c.Locals("session").(*session.Store)
	if !ok {
		return c.Status(fiber.StatusInternalServerError).SendString("Session initialization error")
	}

	sess, err := store.Get(c)
	if err != nil {
		return c.Status(fiber.StatusInternalServerError).SendString("Session creation error")
	}

	email := c.FormValue("email")
	password := c.FormValue("password")

	if email == "[email protected]" && password == "[email protected]" {
		sess.Set("email", email)
		sess.Set("password", password)
		c.Locals("authenticated", true)

		if err := sess.Save(); err != nil {
			return c.Status(fiber.StatusInternalServerError).SendString("Session save error")
		}

		if c.Get("HX-Request") == "true" {
			return templates.Mail().Render(c.Context(), c.Response().BodyWriter())
		}

		return c.Redirect("/mail")
	}

	return c.Status(fiber.StatusUnauthorized).SendString("Invalid credentials")
}

func Logout(c *fiber.Ctx) error {
	store, ok := c.Locals("session").(*session.Store)
	if !ok {
		return c.Status(fiber.StatusInternalServerError).SendString("Session initialization error")
	}

	sess, err := store.Get(c)
	if err != nil {
		return c.Status(fiber.StatusInternalServerError).SendString("Session retrieval error")
	}

	if err := sess.Destroy(); err != nil {
		return c.Status(fiber.StatusInternalServerError).SendString("Logout failed")
	}

	if c.Get("HX-Request") == "true" {
		return templates.Login().Render(c.Context(), c.Response().BodyWriter())
	}

	return c.Redirect("/login")
}