request not authenticated redirect path. private String notAuthenticatedPath; // The request not authorized redirect path. private String notAuthorizedPath; // Public Methods --------------------------------------------------------- public boolean preCreate(Class extends Page> pageClass, Context context) { // If authentication required, then ensure user is authenticated Authentication authentication = pageClass.getAnnotation(Authentication.class); // TODO: user context check. if (authentication != null && authentication.required()) { sendRedirect(getNotAuthenticatedPath(), context); return false; } // If authorization permission defined, then ensure user is authorized to access the page Authorization authorization = pageClass.getAnnotation(Authorization.class); if (authorization != null) { if (!UserContext.getThreadUserContext().hasPermission(authorization.permission())) { sendRedirect(getNotAuthorizedPath(), context); return false; } } return true; } public boolean postCreate(Page page) { return true; } public boolean preResponse(Page page) { return true; } public void postDestroy(Page page) { } public String getNotAuthenticatedPath() { return notAuthenticatedPath; } public void setNotAuthenticatedPath(String notAuthenticatedPath) { this.notAuthenticatedPath = notAuthenticatedPath; } public String getNotAuthorizedPath() { return notAuthorizedPath; } public void setNotAuthorizedPath(String notAuthorizedPath) { this.notAuthorizedPath = notAuthorizedPath; } // Protected Methods ------------------------------------------------------ protected void sendRedirect(String location, Context context) { if (StringUtils.isNotBlank(location)) { if (location.charAt(0) == '/') { String contextPath = context.getRequest().getContextPath(); // Guard against adding duplicate context path if (!location.startsWith(contextPath + '/')) { location = contextPath + location; } } } location = context.getResponse().encodeRedirectURL(location); try { context.getResponse().sendRedirect(location); } catch (IOException ioe) { throw new RuntimeException(ioe); } } }
// Page class authentication annotation @Retention(RetentionPolicy.RUNTIME) public @interface Authentication { boolean required() default true; }
// Page class authorization annotation @Retention(RetentionPolicy.RUNTIME) public @interface Authorization { String permission(); }