Search in sources :

Example 1 with AuthorityService

use of org.alfresco.service.cmr.security.AuthorityService in project alfresco-remote-api by Alfresco.

the class AbstractWorkflowRestApiTest method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    ApplicationContext appContext = getServer().getApplicationContext();
    namespaceService = (NamespaceService) appContext.getBean("NamespaceService");
    workflowService = (WorkflowService) appContext.getBean("WorkflowService");
    MutableAuthenticationService authenticationService = (MutableAuthenticationService) appContext.getBean("AuthenticationService");
    PersonService personService = (PersonService) appContext.getBean("PersonService");
    SearchService searchService = (SearchService) appContext.getBean("SearchService");
    FileFolderService fileFolderService = (FileFolderService) appContext.getBean("FileFolderService");
    nodeService = (NodeService) appContext.getBean("NodeService");
    // for the purposes of the tests make sure workflow engine is enabled/visible.
    WorkflowAdminServiceImpl workflowAdminService = (WorkflowAdminServiceImpl) appContext.getBean("workflowAdminService");
    this.wfTestHelper = new WorkflowTestHelper(workflowAdminService, getEngine(), true);
    AuthorityService authorityService = (AuthorityService) appContext.getBean("AuthorityService");
    personManager = new TestPersonManager(authenticationService, personService, nodeService);
    groupManager = new TestGroupManager(authorityService);
    authenticationComponent = (AuthenticationComponent) appContext.getBean("authenticationComponent");
    dictionaryService = (DictionaryService) appContext.getBean("dictionaryService");
    personManager.createPerson(USER1);
    personManager.createPerson(USER2);
    personManager.createPerson(USER3);
    authenticationComponent.setSystemUserAsCurrentUser();
    groupManager.addUserToGroup(GROUP, USER2);
    packageRef = workflowService.createPackage(null);
    NodeRef companyHome = searchService.selectNodes(nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE), COMPANY_HOME, null, namespaceService, false).get(0);
    contentNodeRef = fileFolderService.create(companyHome, TEST_CONTENT + System.currentTimeMillis(), ContentModel.TYPE_CONTENT).getNodeRef();
    authenticationComponent.clearCurrentSecurityContext();
}
Also used : TestPersonManager(org.alfresco.repo.security.person.TestPersonManager) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ApplicationContext(org.springframework.context.ApplicationContext) PersonService(org.alfresco.service.cmr.security.PersonService) SearchService(org.alfresco.service.cmr.search.SearchService) AuthorityService(org.alfresco.service.cmr.security.AuthorityService) WorkflowAdminServiceImpl(org.alfresco.repo.workflow.WorkflowAdminServiceImpl) FileFolderService(org.alfresco.service.cmr.model.FileFolderService) MutableAuthenticationService(org.alfresco.service.cmr.security.MutableAuthenticationService) WorkflowTestHelper(org.alfresco.repo.workflow.WorkflowTestHelper) TestGroupManager(org.alfresco.repo.security.person.TestGroupManager)

Example 2 with AuthorityService

use of org.alfresco.service.cmr.security.AuthorityService in project acs-community-packaging by Alfresco.

the class ScriptCommandProcessor method validateArguments.

/**
 * @see org.alfresco.web.app.servlet.command.CommandProcessor#validateArguments(javax.servlet.ServletContext, java.lang.String, java.util.Map, java.lang.String[])
 */
public boolean validateArguments(ServletContext sc, String command, Map<String, String> args, String[] urlElements) {
    boolean allowed = false;
    String scriptPath = args.get(ARG_SCRIPT_PATH);
    if (scriptPath != null) {
        // resolve path to a node
        this.scriptRef = BaseServlet.resolveNamePath(sc, scriptPath).NodeRef;
        // same for the document context path if specified
        String docPath = args.get(ARG_CONTEXT_PATH);
        if (docPath != null) {
            this.docRef = BaseServlet.resolveNamePath(sc, docPath).NodeRef;
        }
    } else {
        if (urlElements.length < 3) {
            throw new IllegalArgumentException("Not enough URL arguments passed to command servlet.");
        }
        // get NodeRef to the node script to execute
        StoreRef storeRef = new StoreRef(urlElements[0], urlElements[1]);
        this.scriptRef = new NodeRef(storeRef, urlElements[2]);
        if (urlElements.length >= 6) {
            storeRef = new StoreRef(urlElements[3], urlElements[4]);
            this.docRef = new NodeRef(storeRef, urlElements[5]);
        }
    }
    // check we can READ access the nodes specified
    PermissionService ps = Repository.getServiceRegistry(sc).getPermissionService();
    allowed = (ps.hasPermission(this.scriptRef, PermissionService.READ) == AccessStatus.ALLOWED);
    if (this.docRef != null) {
        allowed &= (ps.hasPermission(this.docRef, PermissionService.READ) == AccessStatus.ALLOWED);
    }
    // check to see if user is allowed to execute arbituary javascript
    // by default only an admin authority can perform this action
    ConfigService configService = Application.getConfigService(sc);
    ClientConfigElement configElement = (ClientConfigElement) configService.getGlobalConfig().getConfigElement("client");
    boolean allowScriptExecute = configElement.getAllowUserScriptExecute();
    AuthorityService authService = Repository.getServiceRegistry(sc).getAuthorityService();
    allowed &= (allowScriptExecute || authService.isAdminAuthority(AuthenticationUtil.getFullyAuthenticatedUser()));
    return allowed;
}
Also used : PermissionService(org.alfresco.service.cmr.security.PermissionService) StoreRef(org.alfresco.service.cmr.repository.StoreRef) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ConfigService(org.springframework.extensions.config.ConfigService) AuthorityService(org.alfresco.service.cmr.security.AuthorityService) ClientConfigElement(org.alfresco.web.config.ClientConfigElement)

Example 3 with AuthorityService

use of org.alfresco.service.cmr.security.AuthorityService in project acs-community-packaging by Alfresco.

the class BaseAssociationEditor method getAvailableOptions.

/**
 * Retrieves the available options for the current association
 *
 * @param context Faces Context
 * @param contains The contains part of the query
 */
protected void getAvailableOptions(FacesContext context, String contains) {
    AssociationDefinition assocDef = getAssociationDefinition(context);
    if (assocDef != null) {
        // find and show all the available options for the current association
        String type = assocDef.getTargetClass().getName().toString();
        if (type.equals(ContentModel.TYPE_AUTHORITY_CONTAINER.toString())) {
            UserTransaction tx = null;
            try {
                tx = Repository.getUserTransaction(context, true);
                tx.begin();
                String safeContains = null;
                if (contains != null && contains.length() > 0) {
                    safeContains = Utils.remove(contains.trim(), "\"");
                    safeContains = safeContains.toLowerCase();
                }
                // get all available groups
                AuthorityService authorityService = Repository.getServiceRegistry(context).getAuthorityService();
                Set<String> groups = authorityService.getAllAuthoritiesInZone(AuthorityService.ZONE_APP_DEFAULT, AuthorityType.GROUP);
                this.availableOptions = new ArrayList<NodeRef>(groups.size());
                // get the NodeRef for each matching group
                AuthorityDAO authorityDAO = (AuthorityDAO) FacesContextUtils.getRequiredWebApplicationContext(context).getBean("authorityDAO");
                if (authorityDAO != null) {
                    List<String> matchingGroups = new ArrayList<String>();
                    String groupDisplayName;
                    for (String group : groups) {
                        // get display name, if not present strip prefix from group id
                        groupDisplayName = authorityService.getAuthorityDisplayName(group);
                        if (groupDisplayName == null || groupDisplayName.length() == 0) {
                            groupDisplayName = group.substring(PermissionService.GROUP_PREFIX.length());
                        }
                        // otherwise just add the group name to the sorted set
                        if (safeContains != null) {
                            if (groupDisplayName.toLowerCase().indexOf(safeContains) != -1) {
                                matchingGroups.add(group);
                            }
                        } else {
                            matchingGroups.add(group);
                        }
                    }
                    // sort the group names
                    Collections.sort(matchingGroups, new SimpleStringComparator());
                    // go through the sorted set and get the NodeRef for each group
                    for (String groupName : matchingGroups) {
                        NodeRef groupRef = authorityDAO.getAuthorityNodeRefOrNull(groupName);
                        if (groupRef != null) {
                            this.availableOptions.add(groupRef);
                        }
                    }
                }
                // commit the transaction
                tx.commit();
            } catch (Throwable err) {
                Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC), err.getMessage()), err);
                this.availableOptions = Collections.<NodeRef>emptyList();
                try {
                    if (tx != null) {
                        tx.rollback();
                    }
                } catch (Exception tex) {
                }
            }
        } else if (type.equals(ContentModel.TYPE_PERSON.toString())) {
            List<Pair<QName, String>> filter = (contains != null && contains.trim().length() > 0) ? Utils.generatePersonFilter(contains.trim()) : null;
            // Always sort by last name, then first name
            List<Pair<QName, Boolean>> sort = new ArrayList<Pair<QName, Boolean>>();
            sort.add(new Pair<QName, Boolean>(ContentModel.PROP_LASTNAME, true));
            sort.add(new Pair<QName, Boolean>(ContentModel.PROP_FIRSTNAME, true));
            // Log the filtering
            if (logger.isDebugEnabled())
                logger.debug("Query filter: " + filter);
            // How many to limit too?
            int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults();
            if (maxResults <= 0) {
                maxResults = Utils.getPersonMaxResults();
            }
            List<PersonInfo> persons = Repository.getServiceRegistry(context).getPersonService().getPeople(filter, true, sort, new PagingRequest(maxResults, null)).getPage();
            // Save the results
            List<NodeRef> nodes = new ArrayList<NodeRef>(persons.size());
            for (PersonInfo person : persons) {
                nodes.add(person.getNodeRef());
            }
            this.availableOptions = nodes;
        } else {
            // for all other types/aspects perform a lucene search
            StringBuilder query = new StringBuilder("+TYPE:\"");
            if (assocDef.getTargetClass().isAspect()) {
                query = new StringBuilder("+ASPECT:\"");
            } else {
                query = new StringBuilder("+TYPE:\"");
            }
            query.append(type);
            query.append("\"");
            if (contains != null && contains.trim().length() != 0) {
                String safeContains = null;
                if (contains != null && contains.length() > 0) {
                    safeContains = Utils.remove(contains.trim(), "\"");
                    safeContains = safeContains.toLowerCase();
                }
                query.append(" AND +@");
                String nameAttr = Repository.escapeQName(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "name"));
                query.append(nameAttr);
                query.append(":\"*" + safeContains + "*\"");
            }
            int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults();
            if (logger.isDebugEnabled()) {
                logger.debug("Query: " + query.toString());
                logger.debug("Max results size: " + maxResults);
            }
            SearchParameters searchParams = new SearchParameters();
            searchParams.addStore(Repository.getStoreRef());
            searchParams.setLanguage(SearchService.LANGUAGE_LUCENE);
            searchParams.setQuery(query.toString());
            if (maxResults > 0) {
                searchParams.setLimit(maxResults);
                searchParams.setLimitBy(LimitBy.FINAL_SIZE);
            }
            ResultSet results = null;
            try {
                results = Repository.getServiceRegistry(context).getSearchService().query(searchParams);
                this.availableOptions = results.getNodeRefs();
            } catch (SearcherException se) {
                logger.info("Search failed for: " + query, se);
                Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_QUERY));
            } finally {
                if (results != null) {
                    results.close();
                }
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("Found " + this.availableOptions.size() + " available options");
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) PersonInfo(org.alfresco.service.cmr.security.PersonService.PersonInfo) QName(org.alfresco.service.namespace.QName) AuthorityService(org.alfresco.service.cmr.security.AuthorityService) ArrayList(java.util.ArrayList) AuthorityDAO(org.alfresco.repo.security.authority.AuthorityDAO) SearcherException(org.alfresco.repo.search.SearcherException) AbortProcessingException(javax.faces.event.AbortProcessingException) IOException(java.io.IOException) PagingRequest(org.alfresco.query.PagingRequest) NodeRef(org.alfresco.service.cmr.repository.NodeRef) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) SearcherException(org.alfresco.repo.search.SearcherException) ResultSet(org.alfresco.service.cmr.search.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) Pair(org.alfresco.util.Pair)

Example 4 with AuthorityService

use of org.alfresco.service.cmr.security.AuthorityService in project acs-community-packaging by Alfresco.

the class AuthenticationHelper method getUser.

/**
 * Attempts to retrieve the User object stored in the current session.
 *
 * @param sc
 *            the servlet context
 * @param httpRequest
 *            The HTTP request
 * @param httpResponse
 *            The HTTP response
 * @return The User object representing the current user or null if it could not be found
 */
public static User getUser(final ServletContext sc, final HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    // If the remote user mapper is configured, we may be able to map in an externally authenticated user
    String userId = getRemoteUser(sc, httpRequest);
    final WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
    HttpSession session = httpRequest.getSession();
    User user = null;
    // examine the appropriate session to try and find the User object
    SessionUser sessionUser = Application.getCurrentUser(session);
    // been known to leak in but shouldn't now)
    if (sessionUser != null) {
        if (logger.isDebugEnabled())
            logger.debug("SessionUser is: " + sessionUser.getUserName());
        AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
        try {
            auth.validate(sessionUser.getTicket());
            if (sessionUser instanceof User) {
                user = (User) sessionUser;
                setExternalAuth(session, userId != null);
            } else {
                user = setUser(sc, httpRequest, sessionUser.getUserName(), sessionUser.getTicket(), userId != null);
            }
        } catch (AuthenticationException authErr) {
            if (logger.isDebugEnabled())
                logger.debug("An authentication error occured while setting the session user", authErr);
            session.removeAttribute(AUTHENTICATION_USER);
            if (!Application.inPortalServer()) {
                if (logger.isDebugEnabled())
                    logger.debug("Invalidating the session.");
                session.invalidate();
            }
        }
    }
    // If the remote user mapper is configured, we may be able to map in an externally authenticated user
    if (userId != null) {
        AuthorityService authorityService = (AuthorityService) wc.getBean(AUTHORITY_SERVICE);
        // We have a previously-cached user with the wrong identity - replace them
        if (user != null && !authorityService.isGuestAuthority(user.getUserName()) && !user.getUserName().equals(userId)) {
            if (logger.isDebugEnabled())
                logger.debug("We have a previously-cached user with the wrong identity - replace them");
            session.removeAttribute(AUTHENTICATION_USER);
            if (!Application.inPortalServer()) {
                if (logger.isDebugEnabled())
                    logger.debug("Invalidating session.");
                session.invalidate();
            }
            user = null;
        }
        if (user == null) {
            if (logger.isDebugEnabled())
                logger.debug("There are no previously-cached users.");
            // If we have been authenticated by other means, just propagate through the user identity
            AuthenticationComponent authenticationComponent = (AuthenticationComponent) wc.getBean(AUTHENTICATION_COMPONENT);
            try {
                if (logger.isDebugEnabled())
                    logger.debug("We have been authenticated by other means, authenticating the user: " + userId);
                authenticationComponent.setCurrentUser(userId);
                AuthenticationService authenticationService = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
                user = setUser(sc, httpRequest, userId, authenticationService.getCurrentTicket(), true);
            } catch (AuthenticationException authErr) {
                if (logger.isDebugEnabled())
                    logger.debug("An authentication error occured while setting the session user", authErr);
                // Allow for an invalid external user ID to be indicated
                session.removeAttribute(AUTHENTICATION_USER);
                if (!Application.inPortalServer()) {
                    if (logger.isDebugEnabled())
                        logger.debug("Invalidating the session.");
                    session.invalidate();
                }
            }
        }
    }
    return user;
}
Also used : SessionUser(org.alfresco.repo.SessionUser) SessionUser(org.alfresco.repo.SessionUser) User(org.alfresco.web.bean.repository.User) AuthenticationComponent(org.alfresco.repo.security.authentication.AuthenticationComponent) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) AuthorityService(org.alfresco.service.cmr.security.AuthorityService) AuthenticationService(org.alfresco.service.cmr.security.AuthenticationService) WebApplicationContext(org.springframework.web.context.WebApplicationContext)

Example 5 with AuthorityService

use of org.alfresco.service.cmr.security.AuthorityService in project alfresco-remote-api by Alfresco.

the class BaseCustomModelApiTest method setup.

@Before
public void setup() throws Exception {
    authenticationService = applicationContext.getBean("authenticationService", MutableAuthenticationService.class);
    personService = applicationContext.getBean("personService", PersonService.class);
    customModelService = applicationContext.getBean("customModelService", CustomModelService.class);
    final AuthorityService authorityService = applicationContext.getBean("authorityService", AuthorityService.class);
    this.nonAdminUserName = createUser("nonAdminUser" + System.currentTimeMillis(), "password", null);
    this.customModelAdmin = createUser("customModelAdmin" + System.currentTimeMillis(), "password", null);
    users.add(nonAdminUserName);
    users.add(customModelAdmin);
    // Add 'customModelAdmin' user into 'ALFRESCO_MODEL_ADMINISTRATORS' group
    transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            authorityService.addAuthority(CustomModelServiceImpl.GROUP_ALFRESCO_MODEL_ADMINISTRATORS_AUTHORITY, customModelAdmin);
            return null;
        }
    });
}
Also used : CustomModelService(org.alfresco.service.cmr.dictionary.CustomModelService) PersonService(org.alfresco.service.cmr.security.PersonService) AuthorityService(org.alfresco.service.cmr.security.AuthorityService) MutableAuthenticationService(org.alfresco.service.cmr.security.MutableAuthenticationService) Before(org.junit.Before)

Aggregations

AuthorityService (org.alfresco.service.cmr.security.AuthorityService)5 NodeRef (org.alfresco.service.cmr.repository.NodeRef)3 MutableAuthenticationService (org.alfresco.service.cmr.security.MutableAuthenticationService)2 PersonService (org.alfresco.service.cmr.security.PersonService)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 AbortProcessingException (javax.faces.event.AbortProcessingException)1 HttpSession (javax.servlet.http.HttpSession)1 UserTransaction (javax.transaction.UserTransaction)1 PagingRequest (org.alfresco.query.PagingRequest)1 SessionUser (org.alfresco.repo.SessionUser)1 SearcherException (org.alfresco.repo.search.SearcherException)1 AuthenticationComponent (org.alfresco.repo.security.authentication.AuthenticationComponent)1 AuthenticationException (org.alfresco.repo.security.authentication.AuthenticationException)1 AuthorityDAO (org.alfresco.repo.security.authority.AuthorityDAO)1 TestGroupManager (org.alfresco.repo.security.person.TestGroupManager)1 TestPersonManager (org.alfresco.repo.security.person.TestPersonManager)1 WorkflowAdminServiceImpl (org.alfresco.repo.workflow.WorkflowAdminServiceImpl)1 WorkflowTestHelper (org.alfresco.repo.workflow.WorkflowTestHelper)1