Java Code Examples for org.alfresco.repo.security.authentication.AuthenticationUtil#getFullyAuthenticatedUser()

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#getFullyAuthenticatedUser() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AlfrescoScriptVirtualContext.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Map<String, String> createPlaceHolders()
{
    Map<String, String> newPlaceholders = new HashMap<>();
    String user = AuthenticationUtil.getFullyAuthenticatedUser();

    newPlaceholders.put(CURRENT_USER_PH,
                        user);

    String[] paths = createQNamePaths();

    // the actual path will contain the ISO9075 encoded qname path
    // this was reverted from a dual placeholder implementation (see CM-523)
    newPlaceholders.put(ACTUAL_PATH_PH,
                        paths[1]);

    // newPlaceholders.put(ACTUAL_ISO9075_PATH_PH,
    // paths[1]);

    return newPlaceholders;
}
 
Example 2
Source File: NodeArchiveServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String getCurrentUser()
{
    String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
    if (currentUser == null)
    {
        throw new AccessDeniedException("No authenticated user; cannot get archived nodes.");
    }

    if (!userNamesAreCaseSensitive
                && !AuthenticationUtil.getSystemUserName().equals(
                            tenantService.getBaseNameUser(currentUser)))
    {
        // user names are not case-sensitive
        currentUser = currentUser.toLowerCase();
    }
    return currentUser;
}
 
Example 3
Source File: ADMRemoteStore.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Get the RunAs user need to execute a Write operation on the given path.
 * 
 * @param path  Document path
 * @return runas user - will be the Full Authenticated User or System as required
 */
protected String getPathRunAsUser(final String path)
{
    // check we actually are the user we are creating a user specific path for
    String runAsUser = AuthenticationUtil.getFullyAuthenticatedUser();
    String userId = null;
    Matcher matcher;
    if ((matcher = USER_PATTERN_1.matcher(path)).matches())
    {
        userId = matcher.group(1);
    }
    else if ((matcher = USER_PATTERN_2.matcher(path)).matches())
    {
        userId = matcher.group(1);
    }
    if (userId != null && userId.equals(runAsUser))
    {
        runAsUser = AuthenticationUtil.getSystemUserName();
    }
    return runAsUser;
}
 
Example 4
Source File: BaseInterpreter.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get current user name
 * 
 * @return  user name
 */
public String getCurrentUserName()
{
    if (username == null)
    {
        return AuthenticationUtil.getFullyAuthenticatedUser();
    }
    return username;
}
 
Example 5
Source File: AuthenticationsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void deleteTicket(String me, Parameters parameters, WithResponse withResponse)
{
    if (!People.DEFAULT_USER.equals(me))
    {
        throw new InvalidArgumentException("Invalid parameter: " + me);
    }

    final String ticket = getTicket(parameters);
    try
    {
        final String ticketUser = ticketComponent.validateTicket(ticket);

        final String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
        // do not go any further if tickets are different
        // or the user is not fully authenticated
        if (currentUser == null || !currentUser.equals(ticketUser))
        {
            throw new NotFoundException(NotFoundException.DEFAULT_MESSAGE_ID, new String[] { ticket });
        }
        else
        {
            // delete the ticket
            authenticationService.invalidateTicket(ticket);
        }
    }
    catch (AuthenticationException e)
    {
        throw new NotFoundException(NotFoundException.DEFAULT_MESSAGE_ID, new String[] { ticket });
    }
}
 
Example 6
Source File: RatingServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class)
public Rating removeRatingByCurrentUser(NodeRef targetNode,
        String ratingScheme)
{
    String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
    return removeRating(targetNode, ratingScheme, currentUser);
}
 
Example 7
Source File: EventsServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void contentGet(NodeRef nodeRef)
{
    NodeInfo nodeInfo = getNodeInfo(nodeRef, NodeContentGetEvent.EVENT_TYPE);
    if(nodeInfo.checkNodeInfo())
    {
        String username = AuthenticationUtil.getFullyAuthenticatedUser();
        String networkId = TenantUtil.getCurrentDomain();

        String name = nodeInfo.getName();
        String objectId = nodeInfo.getNodeId();
        String siteId = nodeInfo.getSiteId();
        String txnId = AlfrescoTransactionSupport.getTransactionId();
        List<String> nodePaths = nodeInfo.getPaths();
        List<List<String>> pathNodeIds = nodeInfo.getParentNodeIds();
        long timestamp = System.currentTimeMillis();
        Long modificationTime = nodeInfo.getModificationTimestamp();
        String nodeType = nodeInfo.getType().toPrefixString(namespaceService);
        Client alfrescoClient = getAlfrescoClient(nodeInfo.getClient());

        Set<String> aspects = nodeInfo.getAspectsAsStrings();
        Map<String, Serializable> properties = nodeInfo.getProperties();

        Event event = new NodeContentGetEvent(nextSequenceNumber(), name, txnId, timestamp, networkId, siteId,
                objectId, nodeType, nodePaths, pathNodeIds, username, modificationTime, alfrescoClient,
                aspects, properties);
        sendEvent(event);
    }
}
 
Example 8
Source File: EventsServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void nodeCheckedOut(NodeRef workingCopyNodeRef)
{
    NodeInfo workingCopyNodeInfo = getNodeInfo(workingCopyNodeRef, NodeCheckedOutEvent.EVENT_TYPE);
    if(workingCopyNodeInfo.checkNodeInfo())
    {
        String username = AuthenticationUtil.getFullyAuthenticatedUser();
        String networkId = TenantUtil.getCurrentDomain();

        String name = workingCopyNodeInfo.getName();
        String objectId = workingCopyNodeInfo.getNodeId();
        String siteId = workingCopyNodeInfo.getSiteId();
        String txnId = AlfrescoTransactionSupport.getTransactionId();
        List<String> nodePaths = workingCopyNodeInfo.getPaths();
        List<List<String>> pathNodeIds = workingCopyNodeInfo.getParentNodeIds();
        long timestamp = System.currentTimeMillis();
        Long modificationTime = workingCopyNodeInfo.getModificationTimestamp();
        String nodeType = workingCopyNodeInfo.getType().toPrefixString(namespaceService);
        Client alfrescoClient = getAlfrescoClient(workingCopyNodeInfo.getClient());
        String workingCopyNodeId = workingCopyNodeInfo.getNodeId();

        Set<String> aspects = workingCopyNodeInfo.getAspectsAsStrings();
        Map<String, Serializable> properties = workingCopyNodeInfo.getProperties();

        Event event = new NodeCheckedOutEvent(nextSequenceNumber(), workingCopyNodeId, name, txnId, timestamp,
                networkId, siteId, objectId, nodeType, nodePaths, pathNodeIds, username, modificationTime,
                alfrescoClient, aspects, properties);
        sendEvent(event);
    }
}
 
Example 9
Source File: EventsServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void nodeUpdated(final NodeRef nodeRef, final Map<String, Property> propertiesAdded,
        final Set<String> propertiesRemoved, final Map<String, Property> propertiesChanged,
        final Set<String> aspectsAdded, final Set<String> aspectsRemoved)
{
    NodeInfo nodeInfo = getNodeInfo(nodeRef, NodeUpdatedEvent.EVENT_TYPE);
    if(nodeInfo.checkNodeInfo())
    {
        String username = AuthenticationUtil.getFullyAuthenticatedUser();
        String networkId = TenantUtil.getCurrentDomain();

        String name = nodeInfo.getName();
        String objectId = nodeInfo.getNodeId();
        String siteId = nodeInfo.getSiteId();
        String txnId = AlfrescoTransactionSupport.getTransactionId();
        List<String> nodePaths = nodeInfo.getPaths();
        List<List<String>> pathNodeIds = nodeInfo.getParentNodeIds();
        long timestamp = System.currentTimeMillis();
        Long modificationTime = nodeInfo.getModificationTimestamp();
        String nodeType = nodeInfo.getType().toPrefixString(namespaceService);
        Client alfrescoClient = getAlfrescoClient(nodeInfo.getClient());

        Set<String> aspects = nodeInfo.getAspectsAsStrings();
        Map<String, Serializable> properties = nodeInfo.getProperties();

        Event event = new NodeUpdatedEvent(nextSequenceNumber(), name, txnId, timestamp, networkId, siteId, objectId, nodeType, nodePaths,
                pathNodeIds, username, modificationTime, propertiesAdded, propertiesRemoved, propertiesChanged,
                aspectsAdded, aspectsRemoved, alfrescoClient, aspects, properties);
        sendEvent(event);
    }
}
 
Example 10
Source File: SiteServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.site.SiteService#canAddMember(java.lang.String,
 *      java.lang.String, java.lang.String)
 */
public boolean canAddMember(final String shortName, final String authorityName, final String role)
{
    final NodeRef siteNodeRef = getSiteNodeRef(shortName);
    if (siteNodeRef == null)
    {
        throw new SiteDoesNotExistException(shortName);
    }

    // Get the user's current role
    final String currentRole = getMembersRole(shortName, authorityName);

    // Get the visibility of the site
    SiteVisibility visibility = getSiteVisibility(siteNodeRef);

    // If we are ...
    // -- the current user has change permissions rights on the site
    // or we are ...
    // -- referring to a public site and
    // -- the role being set is consumer and
    // -- the user being added is ourselves and
    // -- the member does not already have permissions
    // ... then we can set the permissions as system user
    final String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
    return ((permissionService.hasPermission(siteNodeRef, PermissionService.CHANGE_PERMISSIONS) == AccessStatus.ALLOWED)
                || isSiteAdmin(currentUserName) || (SiteVisibility.PUBLIC.equals(visibility)
                && role.equals(SiteModel.SITE_CONSUMER) && authorityName.equals(currentUserName) && currentRole == null));
}
 
Example 11
Source File: EventsServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void nodeUnFavourited(NodeRef nodeRef)
{
    NodeInfo nodeInfo = getNodeInfo(nodeRef, NodeUnFavouritedEvent.EVENT_TYPE);
    if(nodeInfo.checkNodeInfo())
    {
        String username = AuthenticationUtil.getFullyAuthenticatedUser();
        String networkId = TenantUtil.getCurrentDomain();

        String name = nodeInfo.getName();
        String objectId = nodeInfo.getNodeId();
        String siteId = nodeInfo.getSiteId();
        String txnId = AlfrescoTransactionSupport.getTransactionId();
        List<String> nodePaths  = nodeInfo.getPaths();
        List<List<String>> pathNodeIds = nodeInfo.getParentNodeIds();
        long timestamp = System.currentTimeMillis();
        Long modificationTime = nodeInfo.getModificationTimestamp();
        String nodeType = nodeInfo.getType().toPrefixString(namespaceService);

        Set<String> aspects = nodeInfo.getAspectsAsStrings();
        Map<String, Serializable> properties = nodeInfo.getProperties();

        Client alfrescoClient = getAlfrescoClient(nodeInfo.getClient());

        NodeUnFavouritedEvent event = new NodeUnFavouritedEvent(nextSequenceNumber(), name, txnId, timestamp, networkId, siteId, objectId, nodeType, nodePaths,
                pathNodeIds, username, modificationTime, alfrescoClient, aspects, properties);
        sendEvent(event);
    }
}
 
Example 12
Source File: CustomModelsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Checks the current user access rights and throws
 * {@link PermissionDeniedException} if the user is not a member of the
 * ALFRESCO_MODEL_ADMINISTRATORS group
 */
private void validateCurrentUser()
{
    String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
    if (!customModelService.isModelAdmin(currentUser))
    {
        throw new PermissionDeniedException();
    }
}
 
Example 13
Source File: AbstractEventsService.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
    public void afterRollback()
    {
        String txnId = AlfrescoTransactionSupport.getTransactionId();
        long timestamp = System.currentTimeMillis();
        String networkId = TenantUtil.getCurrentDomain();
        String username = AuthenticationUtil.getFullyAuthenticatedUser();
        Client alfrescoClient = getAlfrescoClient(null);

        Event event = new TransactionRolledBackEvent(nextSequenceNumber(), txnId, networkId, timestamp, username,
                alfrescoClient);

        if (logger.isDebugEnabled())
        {
            logger.debug("sendEvent "+event);
        }

        try
        {
            messageProducer.send(event);
        }
        catch (MessagingException e)
        {
//			throw new AlfrescoRuntimeException("Failed to send event", e);
            // TODO just log for now. How to deal with no running ActiveMQ?
            logger.error("Failed to send event " + event, e);
        }
        finally
        {
            TxnEvents events = (TxnEvents)AlfrescoTransactionSupport.getResource(EVENTS_KEY);
            if(events != null)
            {
                events.clear();
            }
        }
    }
 
Example 14
Source File: ScriptTaskListener.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Checks a valid Fully Authenticated User is set.
 * If none is set then attempts to set the task assignee as the Fully Authenticated User.
 * @param delegateTask the delegate task
 * @return <code>true</code> if the Fully Authenticated User was changed, otherwise <code>false</code>.
 */
private boolean checkFullyAuthenticatedUser(final DelegateTask delegateTask) 
{
    if (AuthenticationUtil.getFullyAuthenticatedUser() == null)
    {
        String userName = delegateTask.getAssignee();
        if (userName != null)
        {
            AuthenticationUtil.setFullyAuthenticatedUser(userName);
            return true;
        }
    }
    return false;
}
 
Example 15
Source File: SitesImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
public CollectionWithPagingInfo<Site> getSites(final Parameters parameters)
    {
        final BeanPropertiesFilter filter = parameters.getFilter();

        Paging paging = parameters.getPaging();
        PagingRequest pagingRequest = Util.getPagingRequest(paging);
//    	pagingRequest.setRequestTotalCountMax(requestTotalCountMax)
        
        List<Pair<QName, Boolean>> sortProps = new ArrayList<Pair<QName, Boolean>>();
        List<SortColumn> sortCols = parameters.getSorting();
        if ((sortCols != null) && (sortCols.size() > 0))
        {
            for (SortColumn sortCol : sortCols)
            {
                QName sortPropQName = SORT_PARAMS_TO_QNAMES.get(sortCol.column);
                if (sortPropQName == null)
                {
                    throw new InvalidArgumentException("Invalid sort field: "+sortCol.column);
                }
                sortProps.add(new Pair<>(sortPropQName, (sortCol.asc ? Boolean.TRUE : Boolean.FALSE)));
            }
        }
        else
        {
            // default sort order
            sortProps.add(new Pair<>(ContentModel.PROP_TITLE, Boolean.TRUE));
        }

        List<FilterProp> filterProps = getFilterPropListOfSites(parameters);

        final PagingResults<SiteInfo> pagingResult = siteService.listSites(filterProps, sortProps, pagingRequest);
        final List<SiteInfo> sites = pagingResult.getPage();
        int totalItems = pagingResult.getTotalResultCount().getFirst();
        final String personId = AuthenticationUtil.getFullyAuthenticatedUser();
        List<Site> page = new AbstractList<Site>()
        {
            @Override
            public Site get(int index)
            {
                SiteInfo siteInfo = sites.get(index);

                String role = null;
                if(filter.isAllowed(Site.ROLE))
                {
                    role = siteService.getMembersRole(siteInfo.getShortName(), personId);
                }
                return new Site(siteInfo, role);
            }

            @Override
            public int size()
            {
                return sites.size();
            }
        };

        return CollectionWithPagingInfo.asPaged(paging, page, pagingResult.hasMoreItems(), totalItems);
    }
 
Example 16
Source File: InviteServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testDontOwerrideModeratedSitePermissions() throws Exception
{
    final String MODERATED_SITE_NAME = RandomStringUtils.randomAlphabetic(6);
    final String siteManager = RandomStringUtils.randomAlphabetic(6);
    final String secondUser = RandomStringUtils.randomAlphabetic(6);
    
    // Create two users
    AuthenticationUtil.runAs(new RunAsWork<Object>()
            {
                public Object doWork() throws Exception
                {
                    createPerson(siteManager, siteManager, siteManager, "");
                    createPerson(secondUser, secondUser, secondUser, "");
                    return null;
                }

            }, AuthenticationUtil.getSystemUserName());
    
    // Create moderated site
    SiteInfo siteInfo = InviteServiceTest.this.siteService.getSite(MODERATED_SITE_NAME);
    if (siteInfo == null)
    {
        siteService.createSite(
            "InviteSitePreset", MODERATED_SITE_NAME,
            MODERATED_SITE_NAME, MODERATED_SITE_NAME, SiteVisibility.MODERATED);
    }
    siteService.setMembership(MODERATED_SITE_NAME, siteManager, SiteModel.SITE_MANAGER);
    String role = siteService.getMembersRole(MODERATED_SITE_NAME, siteManager);
    assertEquals(SiteModel.SITE_MANAGER, role);
    
    // Create request to join to site
    String inviteId = createModeratedInvitation(MODERATED_SITE_NAME, "", secondUser, SiteModel.SITE_CONSUMER);
    
    // Set second user to Collaborator
    siteService.setMembership(MODERATED_SITE_NAME, secondUser, SiteModel.SITE_COLLABORATOR);
    role = siteService.getMembersRole(MODERATED_SITE_NAME, secondUser);
    assertEquals(SiteModel.SITE_COLLABORATOR, role);
    
    final String taskId = getTaskId(inviteId);
    assertNotNull("Cannot find taskId", taskId);
    
    // Accept invitation
    String oldUser = AuthenticationUtil.getFullyAuthenticatedUser();
    AuthenticationUtil.setFullyAuthenticatedUser(siteManager);
    workflowService.endTask(taskId, "approve");
    AuthenticationUtil.setFullyAuthenticatedUser(oldUser);
    
    // Check the role
    role = siteService.getMembersRole(MODERATED_SITE_NAME, secondUser);
    assertEquals(SiteModel.SITE_COLLABORATOR, role);
}
 
Example 17
Source File: SiteMembershipRequestsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void approveSiteMembershipRequest(String siteId, String inviteeId, SiteMembershipApproval siteMembershipApproval)
{
    SiteInfo siteInfo = sites.validateSite(siteId);
    if (siteInfo == null)
    {
        throw new EntityNotFoundException(siteId);
    }

    // Set the site id to the short name (to deal with case sensitivity issues with
    // using the siteId from the url)
    siteId = siteInfo.getShortName();

    // Validate invitation.
    Invitation invitation = getSiteInvitation(inviteeId, siteId);
    if (invitation == null || !(invitation instanceof ModeratedInvitation))
    {
        throw new RelationshipResourceNotFoundException(siteId, inviteeId);
    }

    ModeratedInvitation moderatedInvitation = (ModeratedInvitation) invitation;
    ResourceType resourceType = moderatedInvitation.getResourceType();

    if (!resourceType.equals(ResourceType.WEB_SITE) || !SiteVisibility.MODERATED.equals(siteInfo.getVisibility()))
    {
        // note: security, no indication that this has a different visibility
        throw new RelationshipResourceNotFoundException(siteId, inviteeId);
    }

    try
    {
        invitationService.approve(invitation.getInviteId(), "");
    }
    catch (InvitationExceptionForbidden ex)
    {
        throw new PermissionDeniedException();
    }

    // Workflow doesn't allow changing the role, so a new update may be required if
    // approval role differs from default one.
    if (siteMembershipApproval != null && !(siteMembershipApproval.getRole() == null || siteMembershipApproval.getRole().isEmpty()))
    {
        String role = siteMembershipApproval.getRole();

        // Check if role chosen by moderator differs from the invite role.
        if (!moderatedInvitation.getRoleName().equals(role))
        {
            String currentUserId = AuthenticationUtil.getFullyAuthenticatedUser();

            // Update invitation with new role.
            try
            {
                addSiteMembership(invitation.getInviteeUserName(), siteId, role, currentUserId);
            }
            catch (UnknownAuthorityException e)
            {
                logger.debug("addSiteMember:  UnknownAuthorityException " + siteId + " person " + invitation.getInviteId() + " role " + role);
                throw new InvalidArgumentException("Unknown role '" + role + "'");
            }
        }
    }
}
 
Example 18
Source File: SiteFeedRetrieverWebScript.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status)
{
    // retrieve requested format
    String format = req.getFormat();
    if (format == null || format.length() == 0)
    {
        format = getDescription().getDefaultFormat();
    }
    
    String extensionPath = req.getExtensionPath();
    String[] extParts = extensionPath == null ? new String[1] : extensionPath.split("/");
    
    String siteId = null;
    if (extParts.length == 1)
    {
       siteId = extParts[0];
    }
    else
    {
        throw new AlfrescoRuntimeException("Unexpected extension: " + extensionPath);
    }
    
    // map feed collection format to feed entry format (if not the same), eg.
    //     atomfeed -> atomentry
    //     atom     -> atomentry
    if (format.equals("atomfeed") || format.equals("atom"))
    {
       format = "atomentry";
    }
    
    Map<String, Object> model = new HashMap<String, Object>();
    
    try
    {
        List<String> feedEntries = activityService.getSiteFeedEntries(siteId);
        
        
        if (format.equals(FeedTaskProcessor.FEED_FORMAT_JSON))
        { 
            model.put("feedEntries", feedEntries);
            model.put("siteId", siteId);
        }
        else
        {
            List<Map<String, Object>> activityFeedModels = new ArrayList<Map<String, Object>>();
            try
            { 
                for (String feedEntry : feedEntries)
                {
                    activityFeedModels.add(JSONtoFmModel.convertJSONObjectToMap(feedEntry));
                }
            }
            catch (JSONException je)
            {    
                throw new AlfrescoRuntimeException("Unable to get user feed entries: " + je.getMessage());
            }
            
            model.put("feedEntries", activityFeedModels);
            model.put("siteId", siteId);
        }
    }
    catch (AccessDeniedException ade)
    {
        // implies that site either does not exist or is private (and current user is not admin or a member) - hence return 401 (unauthorised)
        String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
        status.setCode(Status.STATUS_UNAUTHORIZED);
        logger.warn("Unable to get site feed entries for '" + siteId + "' (site does not exist or is private) - currently logged in as '" + currentUser +"'");
        
        model.put("feedEntries", null);
        model.put("siteId", "");
    }
    
    return model;
}
 
Example 19
Source File: AlfrescoCmisServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
    public void beforeCall()
    {
        AuthenticationUtil.pushAuthentication();
        if (authentication != null)
        {
            // Use the previously-obtained authentication
            AuthenticationUtil.setFullAuthentication(authentication);
        }
        else
        {
        	CallContext context = getContext();
            if (context == null)
            {
                // Service not opened, yet
                return;
            }
            // Sticky sessions?
            if (connector.openHttpSession())
            {
                // create a session -> set a cookie
                // if the CMIS client supports cookies that might help in clustered environments
                ((HttpServletRequest)context.get(CallContext.HTTP_SERVLET_REQUEST)).getSession();
            }
            
            // Authenticate
            if (authentication != null)
            {
                // We have already authenticated; just reuse the authentication
                AuthenticationUtil.setFullAuthentication(authentication);
            }
            else
            {
                // First check if we already are authenticated
                if (AuthenticationUtil.getFullyAuthenticatedUser() == null)
                {
                    // We have to go to the repo and authenticate
                    String user = context.getUsername();
                    String password = context.getPassword();
                    Authorization auth = new Authorization(user, password);
                    if (auth.isTicket())
                    {
                        connector.getAuthenticationService().validate(auth.getTicket());
                    }
                    else
                    {
                        connector.getAuthenticationService().authenticate(auth.getUserName(), auth.getPasswordCharArray());
                    }
                }
                this.authentication = AuthenticationUtil.getFullAuthentication();
            }
            
//            // TODO: How is the proxy user working.
//            //       Until we know what it is meant to do, it's not available
//            String currentUser = connector.getAuthenticationService().getCurrentUserName();
//            String user = getContext().getUsername();
//            String password = getContext().getPassword();
//            if (currentUser != null && currentUser.equals(connector.getProxyUser()))
//            {
//                if (user != null && user.length() > 0)
//                {
//                    AuthenticationUtil.setFullyAuthenticatedUser(user);
//                }
//            }
        }
    }
 
Example 20
Source File: PublicApiAuthenticatorFactory.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
public boolean authenticate(RequiredAuthentication required, boolean isGuest)
{
    boolean authorized = false;
    try
    {
        String authenticatorKey = servletReq.getHeader(authenticatorKeyHeader);
        String remoteUser = getRemoteUser();
        if (authenticatorKey != null && remoteUser != null)
        {
            // Trusted auth. Validate key and setup authentication context.
            authorized = authenticateViaGateway(required, isGuest, authenticatorKey, remoteUser);
        }
        else
        {
            // Fallback to parent authenticator
            try
            {
                authorized = super.authenticate(required, isGuest);
            }
            catch (AuthenticationException ae)
            {
                // e.g. guest
                if (logger.isDebugEnabled())
                    logger.debug("TenantBasicHttpAuthenticator: required="+required+", isGuest="+isGuest+" - "+ae.getMessage());
            }
        }
        if (authorized)
        {
            // check tenant validity
            final String tenant = servletReq.getTenant();
            final String email = AuthenticationUtil.getFullyAuthenticatedUser();
            try
            {
                authorized = retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Boolean>()
                {
                    public Boolean execute() throws Exception
                    {
                        return tenantAuthentication.authenticateTenant(email, tenant);
                    }
                }, true, false);
            }
            finally
            {
                if (!authorized)
                {
                    listener.authenticationFailed(new TenantCredentials(tenant, email, proxyListener.getOrignalCredentials()));
                    AuthenticationUtil.clearCurrentSecurityContext();
                }
                else
                {
                    listener.userAuthenticated(new TenantCredentials(tenant, email, proxyListener.getOrignalCredentials()));
                }
            }
        }
        return authorized;
    }
    finally
    {
        if (!authorized)
        {
            servletRes.setStatus(401);
            String scheme = useBasicAuth ? "Basic" : "AlfTicket";
            String challenge = scheme + " realm=\"Alfresco " + servletReq.getTenant() + " tenant\"";
            servletRes.setHeader("WWW-Authenticate", challenge);
        }
    }
}