List of usage examples for org.springframework.web.context WebApplicationContext getBean
Object getBean(String name) throws BeansException;
From source file:org.alfresco.web.app.Application.java
/** * Returns the Guest Home folder name name * /*from w w w . j a v a2 s . c o m*/ * @param context The spring context * @return The Guest Home folder name */ private static String getGuestHomeFolderName(WebApplicationContext context) { if (guestHomeFolderName == null) { ImporterBootstrap bootstrap = (ImporterBootstrap) context.getBean(BEAN_IMPORTER_BOOTSTRAP); Properties configuration = bootstrap.getConfiguration(); guestHomeFolderName = configuration.getProperty("spaces.guest_home.childname"); } return guestHomeFolderName; }
From source file:org.alfresco.web.app.ContextListener.java
/** * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) *//* w ww .j a v a 2 s . com*/ public void contextInitialized(ServletContextEvent event) { // make sure that the spaces store in the repository exists this.servletContext = event.getServletContext(); WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); // If no context has been initialised, exit silently so config changes can be made if (ctx == null) { return; } ServiceRegistry registry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY); TransactionService transactionService = registry.getTransactionService(); NodeService nodeService = registry.getNodeService(); SearchService searchService = registry.getSearchService(); NamespaceService namespaceService = registry.getNamespaceService(); AuthenticationContext authenticationContext = (AuthenticationContext) ctx.getBean("authenticationContext"); // repo bootstrap code for our client UserTransaction tx = null; NodeRef companySpaceNodeRef = null; try { tx = transactionService.getUserTransaction(); tx.begin(); authenticationContext.setSystemUserAsCurrentUser(); // get and setup the initial store ref and root path from config StoreRef storeRef = Repository.getStoreRef(servletContext); // get root path String rootPath = Application.getRootPath(servletContext); // Extract company space id and store it in the Application object companySpaceNodeRef = Repository.getCompanyRoot(nodeService, searchService, namespaceService, storeRef, rootPath); Application.setCompanyRootId(companySpaceNodeRef.getId()); // commit the transaction tx.commit(); } catch (Throwable e) { // rollback the transaction try { if (tx != null) { tx.rollback(); } } catch (Exception ex) { } logger.error("Failed to initialise ", e); throw new AlfrescoRuntimeException("Failed to initialise ", e); } finally { try { authenticationContext.clearCurrentSecurityContext(); } catch (Exception ex) { } } }
From source file:org.alfresco.web.app.portlet.AlfrescoFacesPortlet.java
/** * Called by the portlet container to allow the portlet to process an action request. */// w w w . j a v a 2 s . c o m public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException { Application.setInPortalServer(true); try { // Set the current locale I18NUtil.setLocale(getLanguage(request.getPortletSession())); boolean isMultipart = PortletFileUpload.isMultipartContent(request); // NOTE: Due to filters not being called within portlets we can not make use // of the MyFaces file upload support, therefore we are using a pure // portlet request/action to handle file uploads until there is a // solution. if (isMultipart) { if (logger.isDebugEnabled()) logger.debug("Handling multipart request..."); PortletSession session = request.getPortletSession(); // get the file from the request and put it in the session DiskFileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload upload = new PortletFileUpload(factory); List<FileItem> fileItems = upload.parseRequest(request); Iterator<FileItem> iter = fileItems.iterator(); FileUploadBean bean = new FileUploadBean(); while (iter.hasNext()) { FileItem item = iter.next(); String filename = item.getName(); if (item.isFormField() == false) { if (logger.isDebugEnabled()) logger.debug("Processing uploaded file: " + filename); // workaround a bug in IE where the full path is returned // IE is only available for Windows so only check for the Windows path separator int idx = filename.lastIndexOf('\\'); if (idx == -1) { // if there is no windows path separator check for *nix idx = filename.lastIndexOf('/'); } if (idx != -1) { filename = filename.substring(idx + File.separator.length()); } File tempFile = TempFileProvider.createTempFile("alfresco", ".upload"); item.write(tempFile); bean.setFile(tempFile); bean.setFileName(filename); bean.setFilePath(tempFile.getAbsolutePath()); session.setAttribute(FileUploadBean.FILE_UPLOAD_BEAN_NAME, bean, PortletSession.PORTLET_SCOPE); } } // Set the VIEW_ID parameter to tell the faces portlet bridge to treat the request // as a JSF request, this will send us back to the previous page we came from. String lastViewId = (String) request.getPortletSession().getAttribute(SESSION_LAST_VIEW_ID); if (lastViewId != null) { response.setRenderParameter(VIEW_ID, lastViewId); } } else { SessionUser sessionUser = (SessionUser) request.getPortletSession() .getAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE); User user = sessionUser instanceof User ? (User) sessionUser : null; if (user != null) { // setup the authentication context try { WebApplicationContext ctx = (WebApplicationContext) getPortletContext() .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); AuthenticationService auth = (AuthenticationService) ctx.getBean("AuthenticationService"); auth.validate(user.getTicket()); // save last username into portlet preferences, get from LoginBean state LoginBean loginBean = (LoginBean) request.getPortletSession() .getAttribute(AuthenticationHelper.LOGIN_BEAN); if (loginBean != null) { // TODO: Need to login to the Portal to get a user here to store prefs against // so not really a suitable solution as they get thrown away at present! // Also would need to store prefs PER user - so auto login for each...? String oldValue = request.getPreferences().getValue(PREF_ALF_USERNAME, null); if (oldValue == null || oldValue.equals(loginBean.getUsernameInternal()) == false) { if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) { request.getPreferences().setValue(PREF_ALF_USERNAME, loginBean.getUsernameInternal()); request.getPreferences().store(); } } } // do the normal JSF processing super.processAction(request, response); } catch (AuthenticationException authErr) { // remove User object as it's now useless request.getPortletSession().removeAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE); } } else { // do the normal JSF processing as we may be on the login page super.processAction(request, response); } } } catch (Throwable e) { if (getErrorPage() != null) { handleError(request, response, e); } else { logger.warn("No error page configured, re-throwing exception"); if (e instanceof PortletException) { throw (PortletException) e; } else if (e instanceof IOException) { throw (IOException) e; } else { throw new PortletException(e); } } } finally { Application.setInPortalServer(false); } }
From source file:org.alfresco.web.app.portlet.AlfrescoFacesPortlet.java
/** * @see org.apache.myfaces.portlet.MyFacesGenericPortlet#facesRender(javax.portlet.RenderRequest, javax.portlet.RenderResponse) *///from w ww . j a v a2 s .co m protected void facesRender(RenderRequest request, RenderResponse response) throws PortletException, IOException { Application.setInPortalServer(true); try { // Set the current locale I18NUtil.setLocale(getLanguage(request.getPortletSession())); if (request.getParameter(ERROR_OCCURRED) != null) { String errorPage = getErrorPage(); if (logger.isDebugEnabled()) logger.debug("An error has occurred, redirecting to error page: " + errorPage); response.setContentType("text/html"); PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(errorPage); dispatcher.include(request, response); } else { WebApplicationContext ctx = (WebApplicationContext) getPortletContext() .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); AuthenticationService auth = (AuthenticationService) ctx.getBean("AuthenticationService"); // if we have no User object in the session then an HTTP Session timeout must have occured // use the viewId to check that we are not already on the login page PortletSession session = request.getPortletSession(); String viewId = request.getParameter(VIEW_ID); // keep track of last view id so we can use it as return page from multi-part requests request.getPortletSession().setAttribute(SESSION_LAST_VIEW_ID, viewId); SessionUser sessionUser = (SessionUser) request.getPortletSession() .getAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE); User user = sessionUser instanceof User ? (User) sessionUser : null; if (user == null && (viewId == null || viewId.equals(getLoginPage()) == false)) { if (portalGuestAuthenticate(ctx, session, auth) != null) { if (logger.isDebugEnabled()) logger.debug("Guest access successful."); // perform the forward to the page processed by the Faces servlet response.setContentType("text/html"); request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true"); // get the start location as configured by the web-client config ConfigService configService = (ConfigService) ctx.getBean("webClientConfigService"); ClientConfigElement configElement = (ClientConfigElement) configService.getGlobalConfig() .getConfigElement("client"); if (NavigationBean.LOCATION_MYALFRESCO.equals(configElement.getInitialLocation())) { nonFacesRequest(request, response, "/jsp/dashboards/container.jsp"); } else { nonFacesRequest(request, response, FacesHelper.BROWSE_VIEW_ID); } } else { if (logger.isDebugEnabled()) logger.debug("No valid User login, requesting login page. ViewId: " + viewId); // set last used username as special session value used by the LoginBean session.setAttribute(AuthenticationHelper.SESSION_USERNAME, request.getPreferences().getValue(PREF_ALF_USERNAME, null)); // login page is the default portal page response.setContentType("text/html"); request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true"); nonFacesRequest(request, response); } } else { if (session.getAttribute(AuthenticationHelper.SESSION_INVALIDATED) != null) { // remove the username preference value as explicit logout was requested by the user if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) { request.getPreferences().reset(PREF_ALF_USERNAME); } session.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED); } try { if (user != null) { if (logger.isDebugEnabled()) logger.debug("Validating ticket: " + user.getTicket()); // setup the authentication context auth.validate(user.getTicket()); } // do the normal JSF processing super.facesRender(request, response); } catch (AuthenticationException authErr) { // ticket is no longer valid! if (logger.isDebugEnabled()) logger.debug("Invalid ticket, requesting login page."); // remove User object as it's now useless session.removeAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE); // login page is the default portal page response.setContentType("text/html"); request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true"); nonFacesRequest(request, response); } catch (Throwable e) { if (getErrorPage() != null) { handleError(request, response, e); } else { logger.warn("No error page configured, re-throwing exception"); if (e instanceof PortletException) { throw (PortletException) e; } else if (e instanceof IOException) { throw (IOException) e; } else { throw new PortletException(e); } } } } } } finally { Application.setInPortalServer(false); } }
From source file:org.alfresco.web.app.servlet.AlfrescoX509ServletFilter.java
@Override protected boolean checkEnforce(ServletContext servletContext) throws IOException { /*//from ww w . jav a 2s.c o m * Get the secureComms setting from the global properties bean. */ WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); Properties globalProperties = (Properties) wc.getBean(BEAN_GLOBAL_PROPERTIES); String prop = globalProperties.getProperty(SECURE_COMMS); if (logger.isDebugEnabled()) { logger.debug("secureComms:" + prop); } /* * Return true or false based on the property. This will switch on/off X509 enforcement in the X509ServletFilterBase. */ if (prop == null || "none".equals(prop)) { return false; } else { return true; } }
From source file:org.alfresco.web.app.servlet.AuthenticationHelper.java
/** * Helper to authenticate the current user using session based Ticket information. * <p>//from w w w . j a va2 s .c o m * User information is looked up in the Session. If found the ticket is retrieved and validated. * If no User info is found or the ticket is invalid then a redirect is performed to the login page. * * @param forceGuest True to force a Guest login attempt * @param allowGuest True to allow the Guest user if no user object represent * * @return AuthenticationStatus result. */ public static AuthenticationStatus authenticate(ServletContext sc, HttpServletRequest req, HttpServletResponse res, boolean forceGuest, boolean allowGuest) throws IOException { if (logger.isDebugEnabled()) logger.debug("Authenticating the current user using session based Ticket information."); // retrieve the User object User user = getUser(sc, req, res); HttpSession session = req.getSession(); // get the login bean if we're not in the portal LoginBean loginBean = null; if (Application.inPortalServer() == false) { if (logger.isDebugEnabled()) logger.debug("We're not in the portal, getting the login bean."); loginBean = (LoginBean) session.getAttribute(LOGIN_BEAN); } // setup the authentication context WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE); if (logger.isDebugEnabled()) logger.debug("Force guest is: " + forceGuest); if (user == null || forceGuest) { if (logger.isDebugEnabled()) logger.debug("The user is null."); // Check for the session invalidated flag - this is set by the Logout action in the LoginBean // it signals a forced Logout and means we should not immediately attempt a relogin as Guest. // The attribute is removed from the session by the login.jsp page after the Cookie containing // the last stored username string is cleared. if (session.getAttribute(AuthenticationHelper.SESSION_INVALIDATED) == null) { if (logger.isDebugEnabled()) logger.debug("The session is not invalidated."); Cookie authCookie = getAuthCookie(req); if (allowGuest == true && (authCookie == null || forceGuest)) { if (logger.isDebugEnabled()) logger.debug("No previous authentication or forced Guest - attempt Guest access."); try { auth.authenticateAsGuest(); // if we get here then Guest access was allowed and successful setUser(sc, req, AuthenticationUtil.getGuestUserName(), auth.getCurrentTicket(), false); // Set up the thread context setupThread(sc, req, res, true); // remove the session invalidated flag session.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED); if (logger.isDebugEnabled()) logger.debug("Successfully authenticated as guest."); // it is the responsibilty of the caller to handle the Guest return status return AuthenticationStatus.Guest; } catch (AuthenticationException guestError) { if (logger.isDebugEnabled()) logger.debug( "An AuthenticationException occurred, expected if Guest access not allowed - continue to login page as usual", guestError); } catch (AccessDeniedException accessError) { // Guest is unable to access either properties on Person AuthenticationService unprotAuthService = (AuthenticationService) wc .getBean(UNPROTECTED_AUTH_SERVICE); unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket()); unprotAuthService.clearCurrentSecurityContext(); logger.warn("Unable to login as Guest: ", accessError); } catch (Throwable e) { // Some other kind of serious failure to report AuthenticationService unprotAuthService = (AuthenticationService) wc .getBean(UNPROTECTED_AUTH_SERVICE); unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket()); unprotAuthService.clearCurrentSecurityContext(); throw new AlfrescoRuntimeException("Failed to authenticate as Guest user.", e); } } } if (logger.isDebugEnabled()) logger.debug("Session invalidated - return to login screen."); return AuthenticationStatus.Failure; } else { if (logger.isDebugEnabled()) logger.debug("The user is: " + user.getUserName()); // set last authentication username cookie value String loginName; if (loginBean != null && (loginName = loginBean.getUsernameInternal()) != null) { if (logger.isDebugEnabled()) logger.debug("Set last authentication username cookie value"); setUsernameCookie(req, res, loginName); } // Set up the thread context setupThread(sc, req, res, true); return AuthenticationStatus.Success; } }
From source file:org.alfresco.web.app.servlet.AuthenticationHelper.java
/** * Helper to authenticate the current user using the supplied Ticket value. * //from w ww . ja va2 s . co m * @return true if authentication successful, false otherwise. */ public static AuthenticationStatus authenticate(ServletContext context, HttpServletRequest httpRequest, HttpServletResponse httpResponse, String ticket) throws IOException { if (logger.isDebugEnabled()) logger.debug("Authenticate the current user using the supplied Ticket value."); // setup the authentication context WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(context); AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE); HttpSession session = httpRequest.getSession(); try { // If we already have a cached user, make sure it is for the right ticket SessionUser user = (SessionUser) session.getAttribute(AuthenticationHelper.AUTHENTICATION_USER); if (user != null && !user.getTicket().equals(ticket)) { if (logger.isDebugEnabled()) logger.debug("Found a previously-cached user with the wrong identity."); session.removeAttribute(AUTHENTICATION_USER); if (!Application.inPortalServer()) { if (logger.isDebugEnabled()) logger.debug("The server is not running in a portal, invalidating session."); session.invalidate(); session = httpRequest.getSession(); } user = null; } // Validate the ticket and associate it with the session auth.validate(ticket); if (user == null) { if (logger.isDebugEnabled()) logger.debug("Ticket is valid; caching a new user in the session."); setUser(context, httpRequest, auth.getCurrentUserName(), ticket, false); } else if (logger.isDebugEnabled()) logger.debug("Ticket is valid; retaining cached user in session."); } catch (AuthenticationException authErr) { if (logger.isDebugEnabled()) logger.debug("An AuthenticationException occured: ", authErr); session.removeAttribute(AUTHENTICATION_USER); if (!Application.inPortalServer()) { if (logger.isDebugEnabled()) logger.debug("The server is not running in a portal, invalidating session."); session.invalidate(); } return AuthenticationStatus.Failure; } catch (Throwable e) { if (logger.isDebugEnabled()) logger.debug("Authentication failed due to unexpected error", e); // Some other kind of serious failure AuthenticationService unprotAuthService = (AuthenticationService) wc.getBean(UNPROTECTED_AUTH_SERVICE); unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket()); unprotAuthService.clearCurrentSecurityContext(); return AuthenticationStatus.Failure; } // As we are authenticating via a ticket, establish the session locale using request headers rather than web client preferences setupThread(context, httpRequest, httpResponse, false); return AuthenticationStatus.Success; }
From source file:org.alfresco.web.app.servlet.AuthenticationHelper.java
/** * Creates an object for an authentication user. * /*www .j ava 2s . c o m*/ * @param wc * the web application context * @param currentUsername * the current user name * @param ticket * a validated ticket * @return the user object */ private static User createUser(final WebApplicationContext wc, final String currentUsername, final String ticket) { if (logger.isDebugEnabled()) logger.debug("Creating an object for " + currentUsername + " with ticket: " + ticket); final ServiceRegistry services = (ServiceRegistry) wc.getBean(ServiceRegistry.SERVICE_REGISTRY); return services.getTransactionService().getRetryingTransactionHelper() .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<User>() { public User execute() throws Throwable { NodeService nodeService = services.getNodeService(); PersonService personService = (PersonService) wc.getBean(PERSON_SERVICE); NodeRef personRef = personService.getPerson(currentUsername); User user = new User(currentUsername, ticket, personRef); NodeRef homeRef = (NodeRef) nodeService.getProperty(personRef, ContentModel.PROP_HOMEFOLDER); if (homeRef == null || !nodeService.exists(homeRef)) { throw new AuthenticationException("Home folder is missing for user " + currentUsername); } user.setHomeSpaceId(homeRef.getId()); return user; } }); }
From source file:org.alfresco.web.app.servlet.AuthenticationHelper.java
/** * For no previous authentication or forced Guest - attempt Guest access * /*from w w w .j a v a 2 s . c o m*/ * @param ctx * WebApplicationContext * @param auth * AuthenticationService */ public static User portalGuestAuthenticate(WebApplicationContext ctx, AuthenticationService auth) { if (logger.isDebugEnabled()) logger.debug("Authenticating the current user as Guest in a portal."); try { auth.authenticateAsGuest(); return createUser(ctx, AuthenticationUtil.getGuestUserName(), auth.getCurrentTicket()); } catch (AuthenticationException guestError) { if (logger.isDebugEnabled()) logger.debug( "An AuthenticationException occurred, expected if Guest access not allowed - continue to login page as usual", guestError); } catch (AccessDeniedException accessError) { // Guest is unable to access either properties on Person AuthenticationService unprotAuthService = (AuthenticationService) ctx.getBean(UNPROTECTED_AUTH_SERVICE); unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket()); unprotAuthService.clearCurrentSecurityContext(); logger.warn("Unable to login as Guest: " + accessError.getMessage()); } catch (Throwable e) { if (logger.isDebugEnabled()) logger.debug("Unexpected error authenticating as Guest in a portal.", e); // Some other kind of serious failure to report AuthenticationService unprotAuthService = (AuthenticationService) ctx.getBean(UNPROTECTED_AUTH_SERVICE); unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket()); unprotAuthService.clearCurrentSecurityContext(); throw new AlfrescoRuntimeException("Failed to authenticate as Guest user.", e); } return null; }
From source file:org.alfresco.web.app.servlet.AuthenticationHelper.java
/** * Gets the remote user mapper if one is configured and active (i.e. external authentication is in use). * @param sc/*w w w .j a v a2 s. c o m*/ * the servlet context * @return the remote user mapper if one is configured and active; otherwise <code>null</code> */ public static RemoteUserMapper getRemoteUserMapper(final ServletContext sc) { final WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); RemoteUserMapper remoteUserMapper = (RemoteUserMapper) wc.getBean(REMOTE_USER_MAPPER); if (remoteUserMapper != null && !(remoteUserMapper instanceof ActivateableBean) || ((ActivateableBean) remoteUserMapper).isActive()) { if (logger.isDebugEnabled()) { logger.debug("Remote user mapper configured and active."); } return remoteUserMapper; } if (logger.isDebugEnabled()) { logger.debug("No active remote user mapper."); } return null; }