aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/controller/user.go
blob: 3b3bd07a7d46ae52da8d6bcbde7cdde845d8abb7 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package controller

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

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

func UserDetailPage(c *fiber.Ctx) error {

	var user model.User
	var authenticatedUser model.User
	isSelf := false
	isFollowed := false
	navbarActive := "none"

	isAuthenticated, userID := authentication.AuthGet(c)

	db := database.Get()

	err := db.Model(&user).
		Where("username = ?", c.Params("username")).
		Preload("Followers").
		Find(&user).Error

	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return c.Redirect("/")
		}
	}

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

	if isAuthenticated && user.ID == userID {
		isSelf = true
		navbarActive = "profile"
	}

	if isAuthenticated && !isSelf && user.FollowedBy(userID) {
		isFollowed = true
	}

	return c.Render("users/show", fiber.Map{
		"PageTitle":         user.Name + " — Projecty",
		"FiberCtx":          c,
		"IsSelf":            isSelf,
		"IsFollowed":        isFollowed,
		"User":              user,
		"AuthenticatedUser": authenticatedUser,
		"NavBarActive":      navbarActive,
	}, "layouts/app")
}

func UserDetailFavoritePage(c *fiber.Ctx) error {

	var user model.User
	var authenticatedUser model.User
	isSelf := false
	isFollowed := false
	navbarActive := "none"

	isAuthenticated, userID := authentication.AuthGet(c)

	db := database.Get()

	err := db.Model(&user).
		Where("username = ?", c.Params("username")).
		Preload("Followers").
		Find(&user).Error

	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return c.Redirect("/")
		}
	}

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

	if isAuthenticated && user.ID == userID {
		isSelf = true
		navbarActive = "profile"
	}

	if isAuthenticated && !isSelf && user.FollowedBy(userID) {
		isFollowed = true
	}

	return c.Render("users/show", fiber.Map{
		"PageTitle":         user.Name + " — Projecty",
		"FiberCtx":          c,
		"IsSelf":            isSelf,
		"IsFollowed":        isFollowed,
		"User":              user,
		"AuthenticatedUser": authenticatedUser,
		"NavBarActive":      navbarActive,
		"IsLoadFavorites":   true,
	}, "layouts/app")
}