Socialify

Folder ..

Viewing csrf.go
27 lines (24 loc) • 507.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
package middleware

import (
	"majin/internal/utils"
	"time"

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

func CSRFMiddleware(secure bool) fiber.Handler {
	return func(c *fiber.Ctx) error {
		if c.Method() == "GET" {
			csrfToken := utils.GenerateToken()
			c.Cookie(&fiber.Cookie{
				Name:     "_csrf",
				Value:    csrfToken,
				Path:     "/",
				HTTPOnly: true,
				SameSite: "Lax",
				Secure:   secure,
				MaxAge:   int(time.Hour.Seconds()),
			})
			c.Locals("_csrf", csrfToken)
		}
		return c.Next()
	}
}