Initialization of authorization service from the code is now working.
authorErik Brakkee <erik@brakkee.org>
Sat, 21 Sep 2013 16:18:53 +0000 (18:18 +0200)
committerErik Brakkee <erik@brakkee.org>
Sat, 21 Sep 2013 16:18:53 +0000 (18:18 +0200)
pom.xml
src/main/java/org/wamblee/photos/model/plumbing/Initializer.java
src/main/java/org/wamblee/photos/model/plumbing/Producer.java
src/main/java/org/wamblee/photos/security/AuthenticationFilter.java
src/main/java/org/wamblee/photos/security/PageAuthorizationRule.java
src/main/java/org/wamblee/photos/security/PhotoAuthorizationRule.java
src/main/java/org/wamblee/photos/wicket/HomePage.java

diff --git a/pom.xml b/pom.xml
index 6a00ea2c25dc5e9a13654e34363bf0fc8ed8627a..ab055870df09fe3710c557441bbb27a85f9c91a1 100644 (file)
--- a/pom.xml
+++ b/pom.xml
                                <inherited>true</inherited>
                                <groupId>org.apache.maven.plugins</groupId>
                                <artifactId>maven-compiler-plugin</artifactId>
-                               <configuration>
+                               <configuration>                 java
                                        <source>1.6</source>
                                        <target>1.6</target>
                                        <optimize>true</optimize>
                                </plugins>
                        </build>
                </profile>
+        <profile>
+            <id>ide</id>
+            <build>
+                <directory>target-ide</directory>
+            </build>
+        </profile>
        </profiles>
 
        <distributionManagement>
index b5ace148c012cb1b953fdacc1d0f22f13cb0a8f9..850f6f47720b38e49adc7de50972ed5c542b2667 100644 (file)
@@ -25,6 +25,7 @@ import javax.inject.Inject;
 import org.wamblee.inject.InjectorBuilder;
 import org.wamblee.photos.model.Album;
 import org.wamblee.security.authentication.UserAdministration;
+import org.wamblee.security.authorization.AuthorizationService;
 
 /**
  * @author Erik Brakkee
@@ -34,40 +35,44 @@ import org.wamblee.security.authentication.UserAdministration;
 @Startup
 public class Initializer {
 
-    private static final Logger LOGGER = Logger.getLogger(Initializer.class
-        .getName());
+       private static final Logger LOGGER = Logger.getLogger(Initializer.class
+                       .getName());
 
-    /**
-     * We need this helper to do initialization of the beans from within the
-     * post construct method. Injecting these objects into the initializer class
-     * will lead to initialization outside of a transactional context and this
-     * is does not work because and entity manager is required.
-     * 
-     * @author Erik Brakkee
-     * 
-     */
-    public static class Helper {
-        @Inject
-        private UserAdministration userAdmin;
+       /**
+        * We need this helper to do initialization of the beans from within the
+        * post construct method. Injecting these objects into the initializer class
+        * will lead to initialization outside of a transactional context and this
+        * is does not work because and entity manager is required.
+        
+        * @author Erik Brakkee
+        
+        */
+       public static class Helper {
+               @Inject
+               private UserAdministration userAdmin;
 
-        @Inject
-        @AllPhotos
-        private Album album;
+               @Inject
+               private AuthorizationService authorizationService;
 
-        public void init() {
-            userAdmin.getUserCount();
-            album.size();
-        }
-    }
+               @Inject
+               @AllPhotos
+               private Album album;
 
-    @PostConstruct
-    public void scheduleInit() {
-        LOGGER.info("Photo application initializing");
-        // timerService.createTimer(1000, 1000, null);
-        LOGGER.info("Initializing photo application");
-        Helper helper = new Helper();
-        InjectorBuilder.getInjector().inject(helper);
-        helper.init();
-        LOGGER.info("Initialized photo application");
-    }
+               public void init() {
+                       userAdmin.getUserCount();
+                       album.size();
+                       authorizationService.getRules();
+               }
+       }
+
+       @PostConstruct
+       public void scheduleInit() {
+               LOGGER.info("Photo application initializing");
+               // timerService.createTimer(1000, 1000, null);
+               LOGGER.info("Initializing photo application");
+               Helper helper = new Helper();
+               InjectorBuilder.getInjector().inject(helper);
+               helper.init();
+               LOGGER.info("Initialized photo application");
+       }
 }
index a3d9c2a74f75525050cfc36887f674e36e4287b1..f14c748f4d79e980aaf96de925ff63ad0f3ff92e 100644 (file)
@@ -73,12 +73,10 @@ import org.wamblee.security.authorization.jpa.JpaAuthorizationService;
 
 /**
  * @author Erik Brakkee
- * 
  */
 public class Producer {
 
-    private static final Logger LOGGER = Logger.getLogger(Producer.class
-        .getName());
+    private static final Logger LOGGER = Logger.getLogger(Producer.class.getName());
 
     private static final String APP_CONFIG_RESOURCE = "META-INF/org.wamblee.photos.properties";
 
@@ -111,16 +109,15 @@ public class Producer {
     @PhotoCache
     private Cache<String, ArrayList<PhotoEntry>> photoCache;
 
-    private Configuration getCOnfiguration() {
+    private Configuration getConfiguration() {
         LOGGER.info("Initializing configuration");
         Configuration config;
         try {
-            config = new Configuration(new ClassPathResource(
-                APP_CONFIG_RESOURCE).getInputStream());
-        catch (IOException e) {
+            config = new Configuration(new ClassPathResource(APP_CONFIG_RESOURCE).getInputStream());
+        }
+        catch (IOException e) {
             throw new RuntimeException(
-                "Could not read application configuration property classpath resource " +
-                    APP_CONFIG_RESOURCE, e);
+                    "Could not read application configuration property classpath resource " + APP_CONFIG_RESOURCE, e);
         }
         return config;
     }
@@ -129,24 +126,20 @@ public class Producer {
     @ApplicationScoped
     public UserAdministration getUserAdmin() {
         LOGGER.info("Initializing user administration");
-        NameValidator passwordvalidator = new RegexpNameValidator(".{5,}",
-            "INVALID_PASSWORD", "Password must have at least 5 characters");
+        NameValidator passwordvalidator =
+                new RegexpNameValidator(".{5,}", "INVALID_PASSWORD", "Password must have at least 5 characters");
         MessageDigester passwordEncoder = new Md5HexMessageDigester();
-        UserSet userset = new JpaUserSet(userCache, passwordvalidator,
-            passwordEncoder, entityManager);
+        UserSet userset = new JpaUserSet(userCache, passwordvalidator, passwordEncoder, entityManager);
         GroupSet groupset = new JpaGroupSet(entityManager);
-        NameValidator uservalidator = new RegexpNameValidator(
-            "[a-zA-Z]+[a-zA-Z0-9]*", "INVALID_USERNAME",
-            "User name must consist of alphanumeric characters only");
-        NameValidator groupvalidator = new RegexpNameValidator(
-            "[a-zA-Z]+[a-zA-Z0-9]*", "INVALID_GROUPNAME",
-            "Group name must consist of alphanumeric characters only");
-
-        UserAdministration admin = new UserAdministrationImpl(userset,
-            groupset, uservalidator, groupvalidator);
-        UserAdminInitializer initializer = new UserAdminInitializer(admin,
-            new String[] { "erik", "admin" }, new String[] { "users",
-                "administrators" }, new String[] { "abc123", "abc123" });
+        NameValidator uservalidator = new RegexpNameValidator("[a-zA-Z]+[a-zA-Z0-9]*", "INVALID_USERNAME",
+                "User name must consist of alphanumeric characters only");
+        NameValidator groupvalidator = new RegexpNameValidator("[a-zA-Z]+[a-zA-Z0-9]*", "INVALID_GROUPNAME",
+                "Group name must consist of alphanumeric characters only");
+
+        UserAdministration admin = new UserAdministrationImpl(userset, groupset, uservalidator, groupvalidator);
+        UserAdminInitializer initializer =
+                new UserAdminInitializer(admin, new String[]{"erik", "admin"}, new String[]{"users", "administrators"},
+                        new String[]{"abc123", "abc123"});
         return admin;
     }
 
@@ -155,10 +148,10 @@ public class Producer {
     @UserCache
     public Cache<String, User> getUserCache() {
         try {
-            InputResource cacheConfig = new ClassPathResource(
-                "META-INF/ehcache.xml");
+            InputResource cacheConfig = new ClassPathResource("META-INF/ehcache.xml");
             return new EhCache(cacheConfig, "users");
-        } catch (IOException e) {
+        }
+        catch (IOException e) {
             throw new RuntimeException("Could not create user cache", e);
         }
     }
@@ -168,11 +161,10 @@ public class Producer {
     @PhotoCache
     public Cache<String, ArrayList<PhotoEntry>> getPhotoCache() {
         try {
-            InputResource cacheConfig = new ClassPathResource(
-                "META-INF/ehcache.xml");
-            return new EhCache<String, ArrayList<PhotoEntry>>(cacheConfig,
-                "photos");
-        } catch (IOException e) {
+            InputResource cacheConfig = new ClassPathResource("META-INF/ehcache.xml");
+            return new EhCache<String, ArrayList<PhotoEntry>>(cacheConfig, "photos");
+        }
+        catch (IOException e) {
             throw new RuntimeException("Could not create photo cache", e);
         }
     }
@@ -180,10 +172,10 @@ public class Producer {
     @Produces
     @ApplicationScoped
     public AuthorizationService getAuthorizationService() {
+        LOGGER.info("Initializing authorization service");
         OperationRegistry registry = new DefaultOperationRegistry(
-            new Operation[] { new AllOperation(), new CreateOperation(),
-                new DeleteOperation(), new ReadOperation(),
-                new WriteOperation() });
+                new Operation[]{new AllOperation(), new CreateOperation(), new DeleteOperation(), new ReadOperation(),
+                        new WriteOperation()});
         UserAccessor userAccessor = new UserAccessor() {
 
             @Override
@@ -195,25 +187,23 @@ public class Producer {
                 return principal.getName();
             }
         };
-        AuthorizationService service = new JpaAuthorizationService("DEFAULT",
-            entityManager, userAccessor, userAdmin, 10000);
+        AuthorizationService service =
+                new JpaAuthorizationService("DEFAULT", entityManager, userAccessor, userAdmin, 10000);
 
         AnyUserCondition anyUserCondition = new AnyUserCondition();
-        GroupUserCondition adminUserCondition = new GroupUserCondition(
-            "administrators");
+        GroupUserCondition adminUserCondition = new GroupUserCondition("administrators");
 
-        PhotoAuthorizationRule photoEntryRule = new PhotoAuthorizationRule();
+        PhotoAuthorizationRule photoEntryRule = new PhotoAuthorizationRule(anyUserCondition);
 
         // Pages that allow access by any authenticated user
-        PageAuthorizationRule anyUserPageRule = new PageAuthorizationRule(
-            AuthorizationResult.GRANTED, anyUserCondition, HomePage.class);
+        PageAuthorizationRule anyUserPageRule =
+                new PageAuthorizationRule(AuthorizationResult.GRANTED, anyUserCondition, HomePage.class);
 
-        PageAuthorizationRule adminPageRule = new PageAuthorizationRule(
-            AuthorizationResult.GRANTED, adminUserCondition);
+        PageAuthorizationRule adminPageRule =
+                new PageAuthorizationRule(AuthorizationResult.GRANTED, adminUserCondition);
 
-        AuthorizationInitializer initializer = new AuthorizationInitializer(
-            service, new AbstractAuthorizationRule[] { photoEntryRule,
-                anyUserPageRule, adminPageRule });
+        AuthorizationInitializer initializer = new AuthorizationInitializer(service,
+                new AbstractAuthorizationRule[]{photoEntryRule, anyUserPageRule, adminPageRule});
 
         return service;
     }
@@ -225,12 +215,13 @@ public class Producer {
         LOGGER.info("Initializing photo album");
 
         try {
-            File dir = new File(getCOnfiguration().getPath());
+            File dir = new File(getConfiguration().getPath());
             Album fileSystemAlbum = new FileSystemAlbum(dir, "/", photoCache);
             Album concurrentAlbum = new ConcurrentAlbum(fileSystemAlbum);
 
             return concurrentAlbum;
-        } catch (IOException e) {
+        }
+        catch (IOException e) {
             throw new RuntimeException("Could not initialize photo album", e);
         }
     }
@@ -246,17 +237,15 @@ public class Producer {
             throw new RuntimeException("No authenticated user");
         }
         String username = userPrincipal.getName();
-        List<User> users = entityManager
-            .createNamedQuery(User.QUERY_FIND_BY_NAME)
-            .setParameter(User.NAME_PARAM, username).getResultList();
+        List<User> users =
+                entityManager.createNamedQuery(User.QUERY_FIND_BY_NAME).setParameter(User.NAME_PARAM, username)
+                        .getResultList();
         if (users.size() > 1) {
-            throw new RuntimeException("More than one user found for '" +
-                username + "'");
+            throw new RuntimeException("More than one user found for '" + username + "'");
         }
         if (users.isEmpty()) {
             throw new RuntimeException("No authenticated user");
         }
         return users.get(0);
     }
-
 }
index 04442f26c5548800ac59800ee969d8b768143dc4..621121e789787b249057c1b802519b712c7606e9 100644 (file)
@@ -43,19 +43,19 @@ public class AuthenticationFilter implements Filter {
         loginPage = aFilterConfig.getInitParameter(LOGINPAGE);
         if (loginPage == null) {
             throw new ServletException("No login page defined! Must specify '" +
-                LOGINPAGE + "' filter init parameter.");
+                    LOGINPAGE + "' filter init parameter.");
         }
         role = aFilterConfig.getInitParameter(REQUIRED_ROLE);
         if (role == null) {
             throw new ServletException("No role name defined! Must specify '" +
-                REQUIRED_ROLE + "' filter init parameter.");
+                    REQUIRED_ROLE + "' filter init parameter.");
         }
         resources = aFilterConfig.getInitParameter(RESOURCES);
     }
 
     @Override
-    public void doFilter(ServletRequest aRequest, ServletResponse aResponse,
-        FilterChain aChain) throws IOException, ServletException {
+    public void doFilter(ServletRequest aRequest, ServletResponse aResponse, FilterChain aChain)
+            throws IOException, ServletException {
 
         HttpServletRequest request = (HttpServletRequest) aRequest;
         String fullPath = request.getRequestURI();
@@ -65,14 +65,11 @@ public class AuthenticationFilter implements Filter {
             relpath = fullPath.substring(contextPath.length());
         }
 
-        if (request.isUserInRole(role) ||
-            (resources != null && relpath != null && relpath
-                .startsWith(resources))) {
+        if (request.isUserInRole(role) || (resources != null && relpath != null && relpath.startsWith(resources))) {
             aChain.doFilter(aRequest, aResponse);
         } else {
             request.getSession().invalidate();
-            request.getRequestDispatcher(loginPage)
-                .forward(aRequest, aResponse);
+            request.getRequestDispatcher(loginPage).forward(aRequest, aResponse);
         }
     }
 
@@ -80,5 +77,4 @@ public class AuthenticationFilter implements Filter {
     public void destroy() {
         // Empty.
     }
-
 }
index b32f5dfe663711f24567e09fa0558e264b46a1e9..97cf8fcac1f1419722f45b69dc178f8ffecd8005 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.wamblee.photos.security;
 
 import javax.persistence.DiscriminatorValue;
@@ -36,26 +35,21 @@ public class PageAuthorizationRule extends UrlAuthorizationRule {
 
     /**
      * Type-safe construction of page authorization rule.
-     * 
-     * @param aResult
-     *            Result.
-     * @param aUserCondition
-     *            User condition.
-     * @param aPageList
-     *            A list of page names.
+     *
+     * @param aResult        Result.
+     * @param aUserCondition User condition.
+     * @param aPageList      A list of page names.
      */
-    public PageAuthorizationRule(AuthorizationResult aResult,
-        UserCondition aUserCondition, Class<? extends BasePage>... aPageList) {
-        super(aResult, aUserCondition, new RegexpPathCondition(
-            getPageRegex(aPageList)), BasePage.class,
-            new IsaOperationCondition(AllOperation.class));
+    public PageAuthorizationRule(AuthorizationResult aResult, UserCondition aUserCondition,
+            Class<? extends BasePage>... aPageList) {
+        super(aResult, aUserCondition, new RegexpPathCondition(getPageRegex(aPageList)), BasePage.class,
+                new IsaOperationCondition(AllOperation.class));
     }
 
     /**
      * Converts a list of page names into a regular expression for the pages.
-     * 
-     * @param aPageList
-     *            List of pages.
+     *
+     * @param aPageList List of pages.
      * @return Regexp matching any of the given pagenames.
      */
     private static String getPageRegex(Class<? extends BasePage>[] aPageList) {
@@ -77,8 +71,12 @@ public class PageAuthorizationRule extends UrlAuthorizationRule {
         super();
     }
 
-    /* (non-Javadoc)
-     * @see org.wamblee.security.authorization.UrlAuthorizationRule#getResourcePath(java.lang.Object)
+    /*
+     * (non-Javadoc)
+     *
+     * @see
+     * org.wamblee.security.authorization.UrlAuthorizationRule#getResourcePath
+     * (java.lang.Object)
      */
     @Override
     protected String getResourcePath(Object aResource) {
index 0fab5c563f3c275cbd74256367c49c262ceb557d..d772e1c92b1d6f34adcdaacf09ddcaa867488a01 100644 (file)
@@ -17,7 +17,6 @@
 package org.wamblee.photos.security;
 
 import java.util.List;
-
 import javax.inject.Inject;
 import javax.persistence.DiscriminatorValue;
 import javax.persistence.Entity;
@@ -31,6 +30,7 @@ import org.wamblee.security.authorization.AuthorizationResult;
 import org.wamblee.security.authorization.Operation;
 import org.wamblee.security.authorization.ReadOperation;
 import org.wamblee.security.authorization.UrlAuthorizationRule;
+import org.wamblee.security.authorization.UserCondition;
 
 /**
  * Authorization rule for photos. A user has access to all albums owned by his
@@ -46,29 +46,39 @@ public class PhotoAuthorizationRule extends UrlAuthorizationRule {
 
     /**
      * Constructs the authorization rule.
-     * 
      */
     public PhotoAuthorizationRule() {
         // Empty.
     }
 
+    public PhotoAuthorizationRule(UserCondition aUserCondition) {
+        super(AuthorizationResult.GRANTED, aUserCondition, null, PhotoEntry.class, null);
+    }
+
     @PostLoad
     public void init() {
         InjectorBuilder.getInjector().inject(this);
     }
 
-    /* (non-Javadoc)
-     * @see org.wamblee.security.authorization.AuthorizationRule#getSupportedTypes()
+    /*
+     * (non-Javadoc)
+     *
+     * @see
+     * org.wamblee.security.authorization.AuthorizationRule#getSupportedTypes()
      */
     public Class[] getSupportedTypes() {
-        return new Class[] { PhotoEntry.class };
+        return new Class[]{PhotoEntry.class};
     }
 
-    /* (non-Javadoc)
-     * @see org.wamblee.security.authorization.AuthorizationRule#isAllowed(java.lang.Object, org.wamblee.security.authorization.Operation, org.wamblee.usermgt.User)
+    /*
+     * (non-Javadoc)
+     *
+     * @see
+     * org.wamblee.security.authorization.AuthorizationRule#isAllowed(java.lang
+     * .Object, org.wamblee.security.authorization.Operation,
+     * org.wamblee.usermgt.User)
      */
-    public AuthorizationResult isAllowed(Object aResource,
-        Operation anOperation, String aUser) {
+    public AuthorizationResult isAllowed(Object aResource, Operation anOperation, String aUser) {
         if (!(aResource instanceof PhotoEntry)) {
             return AuthorizationResult.UNSUPPORTED_RESOURCE;
         }
@@ -93,7 +103,9 @@ public class PhotoAuthorizationRule extends UrlAuthorizationRule {
         return ((PhotoEntry) aResource).getPath();
     }
 
-    /* (non-Javadoc)
+    /*
+     * (non-Javadoc)
+     *
      * @see java.lang.Object#toString()
      */
     @Override
index acc2877089ee1cf209e25cfceea83048fc5cb473..26331e6fec69d83494ca993d8b1aafd61a8c3ba5 100644 (file)
@@ -51,9 +51,8 @@ public class HomePage extends BasePage {
 
     /**
      * Constructor that is invoked when page is invoked without a session.
-     * 
-     * @param parameters
-     *            Page parameters
+     *
+     * @param parameters Page parameters
      */
     public HomePage(final PageParameters parameters) throws Exception {
         super();
@@ -70,15 +69,13 @@ public class HomePage extends BasePage {
         System.out.println("Entries: " + album.size());
         for (int i = 0; i < album.size(); i++) {
             PhotoEntry entry = album.getEntry(i);
-            System.out.println("Entry " + i + " " + entry.getId() + " " +
-                entry.getPath());
+            System.out.println("Entry " + i + " " + entry.getId() + " " + entry.getPath());
         }
 
         System.out.println("Authorized Entries: " + authorized.size());
         for (int i = 0; i < authorized.size(); i++) {
             PhotoEntry entry = authorized.getEntry(i);
-            System.out.println("Entry " + i + " " + entry.getId() + " " +
-                entry.getPath());
+            System.out.println("Entry " + i + " " + entry.getId() + " " + entry.getPath());
         }
     }
 }