summaryrefslogtreecommitdiffci
path: root/internal/router/handlers/api-v1-email-verify.go
blob: ace1870e17e4bc5347c8bee695537448f16ad923 (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
package handlers

import (
	"html/template"
	"log/slog"

	"github.com/SayaAndy/saya-today-web/internal/router"
	"github.com/gofiber/fiber/v2"
)

type VerifyCodeHandler struct {
	router.BasicHandler
}

func init() {
	router.Routes = append(router.Routes, &VerifyCodeHandler{})
}

func (r *VerifyCodeHandler) Filter() (method string, path string) {
	return "POST", "/api/v1/email/verify"
}

func (r *VerifyCodeHandler) IsTemplated() bool {
	return false
}

func (r *VerifyCodeHandler) TemplatesToInject() []string {
	return []string{"views/partials/personal-page-status.html"}
}

func (r *VerifyCodeHandler) ToCache() router.CacheSetting {
	return router.Disabled
}

func (r *VerifyCodeHandler) ToValidateLang() router.LangSetting {
	return router.InReferer
}

func (r *VerifyCodeHandler) RateLimiter() *fiber.Handler {
	return &router.RateLimiterStrict
}

func (r *VerifyCodeHandler) Render(c *fiber.Ctx, supplements *router.Supplements, lang string, templateMap fiber.Map) (statusCode int, err error) {
	verificationCode := c.FormValue("email_code")
	templateMap["StatusId"] = "verification-message"

	if verificationCode == "" {
		templateMap["Status"] = "Failed"
		templateMap["Message"] = supplements.Localization[lang].UserProfile.VerificationEmpty
		return fiber.StatusUnprocessableEntity, nil
	}

	if err = supplements.Mailer.Verify(verificationCode, lang); err != nil {
		slog.Warn("verification code is invalid", slog.String("verification_code", verificationCode), slog.String("error", err.Error()))
		templateMap["Status"] = "Failed"
		templateMap["Message"] = supplements.Localization[lang].UserProfile.VerificationFailed
		return fiber.StatusUnprocessableEntity, nil
	}

	templateMap["Status"] = "OK"
	templateMap["Message"] = supplements.Localization[lang].UserProfile.VerificationSuccess
	templateMap["DataAttributes"] = map[string]any{
		"hide-verification-panel": template.HTMLAttr("data-code-expiry-time=\"true\""),
	}
	return fiber.StatusOK, nil
}