Socialify

Folder ..

Viewing helper.go
37 lines (31 loc) • 682.0 B

 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
// internal/template/helper.go
package template

import (
	"context"
	"majin/internal/utils"

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

type TemplateData struct {
	CSRFToken string
}

func GetData(ctx context.Context) TemplateData {
	if fctx, ok := ctx.Value("fiberCtxKey").(*fiber.Ctx); ok {
		// Prioritize locals, then cookie
		csrfToken := fctx.Locals("_csrf")
		if csrfToken != nil {
			return TemplateData{
				CSRFToken: csrfToken.(string),
			}
		}

		cookieToken := fctx.Cookies("_csrf")
		if cookieToken != "" {
			return TemplateData{
				CSRFToken: cookieToken,
			}
		}
	}

	// Generate a new token if none exists
	return TemplateData{
		CSRFToken: utils.GenerateToken(),
	}
}