package middlewares import ( "fmt" "time" "git.readonly.ch/bouzoure/pop-camarades/helpers" "git.readonly.ch/bouzoure/pop-camarades/models" "github.com/gofiber/fiber/v2" ) type TemplatesGlobals struct { LoggedIn bool TotpVerified bool UserID uint UserEmail string UserFullname string UserIsAdmin bool TimeStart time.Time ColorMode string AllowMembersPage bool AllowContactsPage bool CacheBusting string } func TemplatesMiddleware(c *fiber.Ctx) error { globals := TemplatesGlobals{} globals.TimeStart = c.Context().Time() sess, err := helpers.GetSessionStore(c) if err != nil { return err } globals.ColorMode = "auto" colorMode := sess.Get("color-mode") if colorMode == "dark" || colorMode == "light" { globals.ColorMode = colorMode.(string) } userid := sess.Get("userid") if userid != nil { switch userid.(type) { case uint: default: return fmt.Errorf("type error, userid should be uint") } globals.LoggedIn = true globals.UserID = userid.(uint) db, err := helpers.GetDatabase() if err != nil { return err } var user models.User result := db.First(&user, "id = ?", globals.UserID) if result.Error == nil { globals.UserEmail = user.Email globals.UserFullname = user.Name globals.UserIsAdmin = user.IsAdmin } showMember, _ := helpers.PermissionsGetSections( userid.(uint), "show_member", ) showArchivedMember, _ := helpers.PermissionsGetSections( userid.(uint), "show_archived_member", ) if len(showMember) > 0 || len(showArchivedMember) > 0 { globals.AllowMembersPage = true } showContact, _ := helpers.PermissionsGetSections( userid.(uint), "show_contact", ) showArchivedContact, _ := helpers.PermissionsGetSections( userid.(uint), "show_archived_contact", ) if len(showContact) > 0 || len(showArchivedContact) > 0 { globals.AllowContactsPage = true } } totpVerified := sess.Get("totp-verified") if totpVerified != nil { globals.TotpVerified = true } config, err := helpers.GetConfig() if err != nil { return err } // Use the git commit tag for cache busting // If we're in dev mode, just use the unix timestamp if config.DevMode { globals.CacheBusting = fmt.Sprintf("%d", time.Now().UnixMilli()) } else { globals.CacheBusting = helpers.GetVCSRevision() } c.Bind(fiber.Map{ "Globals": globals, }) return c.Next() }