001package org.tynamo.security.internal;
002
003import java.io.IOException;
004import java.util.List;
005
006import javax.servlet.http.HttpServletResponse;
007
008import org.apache.shiro.util.StringUtils;
009import org.apache.tapestry5.ExceptionHandlerAssistant;
010import org.apache.tapestry5.internal.services.PageResponseRenderer;
011import org.apache.tapestry5.internal.services.RequestPageCache;
012import org.apache.tapestry5.internal.structure.Page;
013import org.apache.tapestry5.services.Response;
014import org.tynamo.security.internal.services.LoginContextService;
015import org.tynamo.security.services.SecurityService;
016
017public class SecurityExceptionHandlerAssistant implements ExceptionHandlerAssistant {
018        private final SecurityService securityService;
019        private final LoginContextService loginContextService;
020        private final Response response;
021        private final PageResponseRenderer renderer;
022        private final RequestPageCache pageCache;
023
024        public SecurityExceptionHandlerAssistant(final SecurityService securityService,
025                final LoginContextService pageService, final RequestPageCache pageCache, final Response response,
026                final PageResponseRenderer renderer) {
027                this.securityService =securityService;
028                this.loginContextService = pageService;
029                this.pageCache = pageCache;
030                this.response = response;
031                this.renderer = renderer;
032        }
033        @Override
034        public Object handleRequestException(Throwable exception, List<Object> exceptionContext) throws IOException {
035                if (securityService.isAuthenticated()) {
036                        String unauthorizedPage = loginContextService.getUnauthorizedPage();
037                        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
038                        if (!StringUtils.hasText(unauthorizedPage)) return null;
039
040                        Page page = pageCache.get(unauthorizedPage);
041                        renderer.renderPageResponse(page);
042                        return null;
043                }
044
045        loginContextService.saveRequest();
046                return loginContextService.getLoginPage();
047        }
048}