Set core and data manager in all templates.
[demoscenemusic.git] / src / main / java / net / pterodactylus / demoscenemusic / page / BasePage.java
index 988fee7..f6f211e 100644 (file)
 package net.pterodactylus.demoscenemusic.page;
 
 import net.pterodactylus.demoscenemusic.core.Core;
+import net.pterodactylus.demoscenemusic.data.User;
 import net.pterodactylus.util.template.Template;
+import net.pterodactylus.util.template.TemplateContext;
 import net.pterodactylus.util.template.TemplateContextFactory;
+import net.pterodactylus.util.web.RedirectException;
 import net.pterodactylus.util.web.TemplatePage;
 
 /**
@@ -29,6 +32,8 @@ import net.pterodactylus.util.web.TemplatePage;
  */
 public class BasePage extends TemplatePage<ServletRequest> {
 
+       private final Core core;
+
        /**
         * @param path
         * @param contentType
@@ -36,8 +41,42 @@ public class BasePage extends TemplatePage<ServletRequest> {
         * @param template
         */
        public BasePage(Core core, TemplateContextFactory templateContextFactory, Template template, String pageName) {
-               super(pageName, "text/html", templateContextFactory, template);
+               super(pageName, "text/html; charset=utf-8", templateContextFactory, template);
+               this.core = core;
        }
 
-}
+       /**
+        * @return the core
+        */
+       public Core getCore() {
+               return core;
+       }
+
+       /**
+        * {@inheritDoc}
+        */
+       @Override
+       protected void processTemplate(TemplateContext templateContext, ServletRequest request) throws RedirectException {
+               super.processTemplate(templateContext, request);
+               User currentUser = (User) request.getServletRequest().getSession().getAttribute("currentUser");
+               templateContext.set("currentUser", currentUser);
+               templateContext.set("core", getCore());
+               templateContext.set("dataManager", getCore().getDataManager());
+               int requiredUserLevel = getRequiredUserLevel();
+               if (((currentUser == null) && (requiredUserLevel > 0)) || ((currentUser != null) && (requiredUserLevel > currentUser.getLevel()))) {
+                       throw new RedirectException("login");
+               }
+       }
 
+       /**
+        * Returns the {@link User#getLevel() user level} that is at least required
+        * to access the given page. If the returned level is {@code 0} (or
+        * smaller), users don’t have to be logged in.
+        *
+        * @return The lowest user level required to view this page
+        */
+       protected int getRequiredUserLevel() {
+               return 0;
+       }
+
+}