Search in sources :

Example 66 with StudioConfiguration

use of org.craftercms.studio.api.v2.utils.StudioConfiguration in project studio by craftercms.

the class HeadersAuthenticationProvider method doAuthenticate.

@Override
public boolean doAuthenticate(HttpServletRequest request, HttpServletResponse response, AuthenticationChain authenticationChain, String username, String password) throws AuthenticationSystemException, UserNotFoundException {
    if (isEnabled()) {
        logger.debug("Authenticating user using authentication headers.");
        RequestContext requestContext = RequestContext.getCurrent();
        if (requestContext != null) {
            String securekeyHeader = request.getHeader(secureKeyHeader);
            logger.debug("Verifying authentication header secure key.");
            if (StringUtils.equals(securekeyHeader, secureKeyHeaderValue)) {
                String usernameHeaderValue = request.getHeader(usernameHeader);
                String firstName = request.getHeader(firstNameHeader);
                String lastName = request.getHeader(lastNameHeader);
                String email = request.getHeader(emailHeader);
                String groups = request.getHeader(groupsHeader);
                try {
                    UserServiceInternal userServiceInternal = authenticationChain.getUserServiceInternal();
                    AuditServiceInternal auditServiceInternal = authenticationChain.getAuditServiceInternal();
                    StudioConfiguration studioConfiguration = authenticationChain.getStudioConfiguration();
                    SiteService siteService = authenticationChain.getSiteService();
                    SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
                    if (userServiceInternal.userExists(-1, usernameHeaderValue)) {
                        User user = userServiceInternal.getUserByIdOrUsername(-1, usernameHeaderValue);
                        user.setFirstName(firstName);
                        user.setLastName(lastName);
                        user.setEmail(email);
                        if (StringUtils.isNoneEmpty(firstName, lastName, email)) {
                            logger.debug("If user already exists in studio DB, update details.");
                            try {
                                userServiceInternal.updateUser(user);
                                AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
                                auditLog.setOperation(OPERATION_UPDATE);
                                auditLog.setActorId(usernameHeaderValue);
                                auditLog.setSiteId(siteFeed.getId());
                                auditLog.setPrimaryTargetId(usernameHeaderValue);
                                auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
                                auditLog.setPrimaryTargetValue(user.getUsername());
                                auditServiceInternal.insertAuditLog(auditLog);
                            } catch (Exception e) {
                                logger.debug("Error updating user " + usernameHeaderValue + " with data from authentication headers", e);
                                throw new AuthenticationSystemException("Error updating user " + usernameHeaderValue + " with data from " + "external authentication provider", e);
                            }
                        }
                    } else {
                        logger.debug("User does not exist in studio db. Adding user " + usernameHeader);
                        try {
                            User user = new User();
                            user.setUsername(usernameHeaderValue);
                            user.setPassword(UUID.randomUUID().toString());
                            user.setFirstName(firstName);
                            user.setLastName(lastName);
                            user.setEmail(email);
                            user.setExternallyManaged(true);
                            user.setEnabled(true);
                            userServiceInternal.createUser(user);
                            AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
                            auditLog.setOperation(OPERATION_CREATE);
                            auditLog.setSiteId(siteFeed.getId());
                            auditLog.setActorId(usernameHeaderValue);
                            auditLog.setPrimaryTargetId(usernameHeaderValue);
                            auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
                            auditLog.setPrimaryTargetValue(user.getUsername());
                            auditServiceInternal.insertAuditLog(auditLog);
                        } catch (UserAlreadyExistsException | ServiceLayerException e) {
                            logger.debug("Error adding user " + usernameHeaderValue + " from authentication " + "headers", e);
                            throw new AuthenticationSystemException("Error adding user " + usernameHeaderValue + " from external " + "authentication provider", e);
                        }
                    }
                } catch (ServiceLayerException e) {
                    logger.debug("Unknown service error", e);
                    throw new AuthenticationSystemException("Unknown service error", e);
                }
                User user = new User();
                user.setUsername(usernameHeaderValue);
                user.setFirstName(firstName);
                user.setLastName(lastName);
                user.setEmail(email);
                user.setGroups(new ArrayList<UserGroup>());
                logger.debug("Update user groups in database.");
                if (StringUtils.isNoneEmpty(groups)) {
                    String[] groupsArray = groups.split(",");
                    for (int i = 0; i < groupsArray.length; i++) {
                        Group g = new Group();
                        try {
                            g.setGroupName(StringUtils.trim(groupsArray[i]));
                            g.setGroupDescription("Externally managed group");
                            g.setOrganization(null);
                            UserGroup ug = new UserGroup();
                            ug.setGroup(g);
                            user.getGroups().add(ug);
                            upsertUserGroup(g.getGroupName(), usernameHeaderValue, authenticationChain);
                        } catch (Exception e) {
                            logger.debug("Error updating user group " + g.getGroupName() + " with data from authentication headers", e);
                        }
                    }
                }
                String token = createToken(user, authenticationChain);
                if (isLogoutEnabled()) {
                    storeAuthentication(new Authentication(usernameHeaderValue, token, AuthenticationType.AUTH_HEADERS, logoutUrl));
                } else {
                    storeAuthentication(new Authentication(usernameHeaderValue, token, AuthenticationType.AUTH_HEADERS));
                }
                return true;
            }
        }
        logger.debug("Unable to authenticate user using authentication headers");
        return false;
    } else {
        logger.debug("Authentication using headers disabled");
        return false;
    }
}
Also used : UserGroup(org.craftercms.studio.api.v2.dal.UserGroup) Group(org.craftercms.studio.api.v2.dal.Group) User(org.craftercms.studio.api.v2.dal.User) UserServiceInternal(org.craftercms.studio.api.v2.service.security.internal.UserServiceInternal) AuthenticationSystemException(org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) UserAlreadyExistsException(org.craftercms.studio.api.v1.exception.security.UserAlreadyExistsException) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) UserAlreadyExistsException(org.craftercms.studio.api.v1.exception.security.UserAlreadyExistsException) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) AuthenticationSystemException(org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) UserGroup(org.craftercms.studio.api.v2.dal.UserGroup) StudioConfiguration(org.craftercms.studio.api.v2.utils.StudioConfiguration) AuditServiceInternal(org.craftercms.studio.api.v2.service.audit.internal.AuditServiceInternal) SiteService(org.craftercms.studio.api.v1.service.site.SiteService) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) RequestContext(org.craftercms.commons.http.RequestContext)

Example 67 with StudioConfiguration

use of org.craftercms.studio.api.v2.utils.StudioConfiguration in project studio by craftercms.

the class HeadersAuthenticationProvider method upsertUserGroup.

protected boolean upsertUserGroup(String groupName, String username, AuthenticationChain authenticationChain) throws SiteNotFoundException {
    GroupDAO groupDao = authenticationChain.getGroupDao();
    UserDAO userDao = authenticationChain.getUserDao();
    AuditServiceInternal auditServiceInternal = authenticationChain.getAuditServiceInternal();
    SiteService siteService = authenticationChain.getSiteService();
    StudioConfiguration studioConfiguration = authenticationChain.getStudioConfiguration();
    SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
    try {
        Map<String, Object> params = new HashMap<>();
        params.put(ORG_ID, DEFAULT_ORGANIZATION_ID);
        params.put(GROUP_NAME, groupName);
        params.put(GROUP_DESCRIPTION, "Externally managed group - " + groupName);
        groupDao.createGroup(params);
    } catch (Exception e) {
        logger.debug("Error creating group", e);
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put(GROUP_NAME, groupName);
    Group group = groupDao.getGroupByName(params);
    if (group != null) {
        List<String> usernames = new ArrayList<String>();
        params = new HashMap<>();
        params.put(USER_ID, -1);
        params.put(USERNAME, username);
        User user = userDao.getUserByIdOrUsername(params);
        List<Long> users = new ArrayList<Long>();
        users.add(user.getId());
        params = new HashMap<>();
        params.put(USER_IDS, users);
        params.put(GROUP_ID, group.getId());
        try {
            groupDao.addGroupMembers(params);
            AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
            auditLog.setOperation(OPERATION_ADD_MEMBERS);
            auditLog.setSiteId(siteFeed.getId());
            auditLog.setActorId(username);
            auditLog.setPrimaryTargetId(group.getGroupName() + ":" + user.getUsername());
            auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
            auditLog.setPrimaryTargetValue(user.getUsername());
            auditServiceInternal.insertAuditLog(auditLog);
        } catch (Exception e) {
            logger.debug("Unknown database error", e);
        }
    }
    return true;
}
Also used : UserGroup(org.craftercms.studio.api.v2.dal.UserGroup) Group(org.craftercms.studio.api.v2.dal.Group) User(org.craftercms.studio.api.v2.dal.User) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) UserAlreadyExistsException(org.craftercms.studio.api.v1.exception.security.UserAlreadyExistsException) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) AuthenticationSystemException(org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) StudioConfiguration(org.craftercms.studio.api.v2.utils.StudioConfiguration) AuditServiceInternal(org.craftercms.studio.api.v2.service.audit.internal.AuditServiceInternal) UserDAO(org.craftercms.studio.api.v2.dal.UserDAO) SiteService(org.craftercms.studio.api.v1.service.site.SiteService) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) GroupDAO(org.craftercms.studio.api.v2.dal.GroupDAO)

Example 68 with StudioConfiguration

use of org.craftercms.studio.api.v2.utils.StudioConfiguration in project studio by craftercms.

the class LdapAuthenticationProvider method doAuthenticate.

@Override
public boolean doAuthenticate(HttpServletRequest request, HttpServletResponse response, AuthenticationChain authenticationChain, String username, String password) throws AuthenticationSystemException, BadCredentialsException {
    LdapContextSource lcs = new LdapContextSource();
    lcs.setUrl(ldapUrl);
    lcs.setUserDn(ldapUsername);
    lcs.setPassword(ldapPassword);
    lcs.setBase(ldapBaseContext);
    lcs.setDirObjectFactory(DefaultDirObjectFactory.class);
    lcs.afterPropertiesSet();
    LdapTemplate ldapTemplate = new LdapTemplate(lcs);
    // Mapper for user data if user is successfully authenticated
    AuthenticatedLdapEntryContextMapper<User> mapper = (dirContext, ldapEntryIdentification) -> {
        try {
            // User entry - extract attributes
            DirContextOperations dirContextOperations = (DirContextOperations) dirContext.lookup(ldapEntryIdentification.getRelativeName());
            Attributes attributes = dirContextOperations.getAttributes();
            Attribute emailAttrib = attributes.get(emailLdapAttribute);
            Attribute firstNameAttrib = attributes.get(firstNameLdapAttribute);
            Attribute lastNameAttrib = attributes.get(lastNameLdapAttribute);
            Attribute groupNameAttrib = attributes.get(groupNameLdapAttribute);
            User user = new User();
            user.setEnabled(true);
            user.setExternallyManaged(true);
            user.setUsername(username);
            user.setPassword(UUID.randomUUID().toString());
            if (emailAttrib != null && emailAttrib.get() != null) {
                user.setEmail(emailAttrib.get().toString());
            } else {
                logger.warn("No LDAP attribute " + emailLdapAttribute + " found for username " + username + ". User will not be imported into DB.");
                return null;
            }
            if (firstNameAttrib != null && firstNameAttrib.get() != null) {
                user.setFirstName(firstNameAttrib.get().toString());
            } else {
                logger.warn("No LDAP attribute " + firstNameLdapAttribute + " found for username " + username);
            }
            if (lastNameAttrib != null && lastNameAttrib.get() != null) {
                user.setLastName(lastNameAttrib.get().toString());
            } else {
                logger.warn("No LDAP attribute " + lastNameLdapAttribute + " found for username " + username);
            }
            extractGroupsFromAttribute(user, groupNameLdapAttribute, groupNameAttrib);
            return user;
        } catch (NamingException e) {
            logger.debug("Error getting details from LDAP for username " + username, e);
            return null;
        }
    };
    // Create ldap query to authenticate user
    LdapQuery ldapQuery = query().where(usernameLdapAttribute).is(username);
    User user;
    try {
        user = ldapTemplate.authenticate(ldapQuery, password, mapper);
    } catch (EmptyResultDataAccessException e) {
        logger.debug("User " + username + " not found with external security provider.");
        return false;
    } catch (CommunicationException e) {
        logger.debug("Failed to connect with external security provider", e);
        return false;
    } catch (AuthenticationException e) {
        logger.debug("Authentication failed with the LDAP system (bad credentials)", e);
        throw new BadCredentialsException();
    } catch (Exception e) {
        logger.debug("Unexpected exception when authenticating with the LDAP system", e);
        return false;
    }
    if (user != null) {
        // When user authenticated against LDAP, upsert user data into studio database
        UserServiceInternal userServiceInternal = authenticationChain.getUserServiceInternal();
        AuditServiceInternal auditServiceInternal = authenticationChain.getAuditServiceInternal();
        StudioConfiguration studioConfiguration = authenticationChain.getStudioConfiguration();
        SiteService siteService = authenticationChain.getSiteService();
        try {
            SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
            if (userServiceInternal.userExists(-1, username)) {
                try {
                    userServiceInternal.updateUser(user);
                } catch (UserNotFoundException e) {
                    // Shouldn't happen
                    throw new IllegalStateException(e);
                }
                AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
                auditLog.setOperation(OPERATION_UPDATE);
                auditLog.setSiteId(siteFeed.getId());
                auditLog.setActorId(user.getUsername());
                auditLog.setPrimaryTargetId(user.getUsername());
                auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
                auditLog.setPrimaryTargetValue(user.getUsername());
                auditServiceInternal.insertAuditLog(auditLog);
            } else {
                try {
                    userServiceInternal.createUser(user);
                    AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
                    auditLog.setOperation(OPERATION_CREATE);
                    auditLog.setSiteId(siteFeed.getId());
                    auditLog.setActorId(user.getUsername());
                    auditLog.setPrimaryTargetId(user.getUsername());
                    auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
                    auditLog.setPrimaryTargetValue(user.getUsername());
                    auditServiceInternal.insertAuditLog(auditLog);
                } catch (UserAlreadyExistsException e) {
                    logger.debug("Error adding user " + username + " from external authentication provider", e);
                    throw new AuthenticationSystemException("Error adding user " + username + " from external authentication provider", e);
                }
            }
        } catch (ServiceLayerException e) {
            logger.debug("Unknown service error", e);
            throw new AuthenticationSystemException("Unknown service error", e);
        }
        for (UserGroup userGroup : user.getGroups()) {
            upsertUserGroup(userGroup.getGroup().getGroupName(), user.getUsername(), authenticationChain);
        }
        String token = createToken(user, authenticationChain);
        storeAuthentication(new Authentication(username, token, AuthenticationType.LDAP));
        return true;
    } else {
        logger.debug("Failed to retrieve LDAP user details");
        throw new AuthenticationSystemException("Failed to retrieve LDAP user details");
    }
}
Also used : DEFAULT_ORGANIZATION_ID(org.craftercms.studio.api.v1.constant.StudioConstants.DEFAULT_ORGANIZATION_ID) UserServiceInternal(org.craftercms.studio.api.v2.service.security.internal.UserServiceInternal) GROUP_NAME(org.craftercms.studio.api.v2.dal.QueryParameterNames.GROUP_NAME) LdapTemplate(org.springframework.ldap.core.LdapTemplate) NamingException(javax.naming.NamingException) StringUtils(org.apache.commons.lang3.StringUtils) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) User(org.craftercms.studio.api.v2.dal.User) Attribute(javax.naming.directory.Attribute) Matcher(java.util.regex.Matcher) GROUP_DESCRIPTION(org.craftercms.studio.api.v2.dal.QueryParameterNames.GROUP_DESCRIPTION) AuditServiceInternal(org.craftercms.studio.api.v2.service.audit.internal.AuditServiceInternal) Map(java.util.Map) BaseAuthenticationProvider(org.craftercms.studio.api.v2.service.security.BaseAuthenticationProvider) UserGroup(org.craftercms.studio.api.v2.dal.UserGroup) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) USERNAME(org.craftercms.studio.api.v2.dal.QueryParameterNames.USERNAME) LdapContextSource(org.springframework.ldap.core.support.LdapContextSource) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) SiteService(org.craftercms.studio.api.v1.service.site.SiteService) CONFIGURATION_GLOBAL_SYSTEM_SITE(org.craftercms.studio.api.v2.utils.StudioConfiguration.CONFIGURATION_GLOBAL_SYSTEM_SITE) UUID(java.util.UUID) List(java.util.List) StudioConfiguration(org.craftercms.studio.api.v2.utils.StudioConfiguration) GROUP_ID(org.craftercms.studio.api.v2.dal.QueryParameterNames.GROUP_ID) LdapQueryBuilder.query(org.springframework.ldap.query.LdapQueryBuilder.query) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) OPERATION_CREATE(org.craftercms.studio.api.v2.dal.AuditLogConstants.OPERATION_CREATE) Pattern(java.util.regex.Pattern) DirContextOperations(org.springframework.ldap.core.DirContextOperations) UserAlreadyExistsException(org.craftercms.studio.api.v1.exception.security.UserAlreadyExistsException) TARGET_TYPE_USER(org.craftercms.studio.api.v2.dal.AuditLogConstants.TARGET_TYPE_USER) USER_ID(org.craftercms.studio.api.v2.dal.QueryParameterNames.USER_ID) AuthenticationException(org.springframework.ldap.AuthenticationException) USER_IDS(org.craftercms.studio.api.v2.dal.QueryParameterNames.USER_IDS) Logger(org.craftercms.studio.api.v1.log.Logger) GroupDAO(org.craftercms.studio.api.v2.dal.GroupDAO) AuthenticationType(org.craftercms.studio.model.AuthenticationType) HashMap(java.util.HashMap) AuthenticationChain(org.craftercms.studio.api.v2.service.security.AuthenticationChain) ArrayList(java.util.ArrayList) HttpServletRequest(javax.servlet.http.HttpServletRequest) LoggerFactory(org.craftercms.studio.api.v1.log.LoggerFactory) CommunicationException(org.springframework.ldap.CommunicationException) OPERATION_ADD_MEMBERS(org.craftercms.studio.api.v2.dal.AuditLogConstants.OPERATION_ADD_MEMBERS) OPERATION_UPDATE(org.craftercms.studio.api.v2.dal.AuditLogConstants.OPERATION_UPDATE) LdapQuery(org.springframework.ldap.query.LdapQuery) DefaultDirObjectFactory(org.springframework.ldap.core.support.DefaultDirObjectFactory) UserDAO(org.craftercms.studio.api.v2.dal.UserDAO) AuthenticationSystemException(org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException) HttpServletResponse(javax.servlet.http.HttpServletResponse) ORG_ID(org.craftercms.studio.api.v2.dal.QueryParameterNames.ORG_ID) Group(org.craftercms.studio.api.v2.dal.Group) BadCredentialsException(org.craftercms.studio.api.v1.exception.security.BadCredentialsException) AuthenticatedLdapEntryContextMapper(org.springframework.ldap.core.AuthenticatedLdapEntryContextMapper) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) User(org.craftercms.studio.api.v2.dal.User) Attribute(javax.naming.directory.Attribute) AuthenticationException(org.springframework.ldap.AuthenticationException) Attributes(javax.naming.directory.Attributes) UserAlreadyExistsException(org.craftercms.studio.api.v1.exception.security.UserAlreadyExistsException) LdapQuery(org.springframework.ldap.query.LdapQuery) BadCredentialsException(org.craftercms.studio.api.v1.exception.security.BadCredentialsException) LdapTemplate(org.springframework.ldap.core.LdapTemplate) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) UserGroup(org.craftercms.studio.api.v2.dal.UserGroup) StudioConfiguration(org.craftercms.studio.api.v2.utils.StudioConfiguration) SiteService(org.craftercms.studio.api.v1.service.site.SiteService) NamingException(javax.naming.NamingException) CommunicationException(org.springframework.ldap.CommunicationException) LdapContextSource(org.springframework.ldap.core.support.LdapContextSource) UserServiceInternal(org.craftercms.studio.api.v2.service.security.internal.UserServiceInternal) AuthenticationSystemException(org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) NamingException(javax.naming.NamingException) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) UserAlreadyExistsException(org.craftercms.studio.api.v1.exception.security.UserAlreadyExistsException) AuthenticationException(org.springframework.ldap.AuthenticationException) CommunicationException(org.springframework.ldap.CommunicationException) AuthenticationSystemException(org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException) BadCredentialsException(org.craftercms.studio.api.v1.exception.security.BadCredentialsException) AuditServiceInternal(org.craftercms.studio.api.v2.service.audit.internal.AuditServiceInternal) DirContextOperations(org.springframework.ldap.core.DirContextOperations) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException)

Example 69 with StudioConfiguration

use of org.craftercms.studio.api.v2.utils.StudioConfiguration in project studio by craftercms.

the class LdapAuthenticationProvider method upsertUserGroup.

protected boolean upsertUserGroup(String groupName, String username, AuthenticationChain authenticationChain) {
    UserDAO userDao = authenticationChain.getUserDao();
    GroupDAO groupDao = authenticationChain.getGroupDao();
    AuditServiceInternal auditServiceInternal = authenticationChain.getAuditServiceInternal();
    SiteService siteService = authenticationChain.getSiteService();
    StudioConfiguration studioConfiguration = authenticationChain.getStudioConfiguration();
    try {
        Map<String, Object> params = new HashMap<>();
        params.put(ORG_ID, DEFAULT_ORGANIZATION_ID);
        params.put(GROUP_NAME, groupName);
        params.put(GROUP_DESCRIPTION, "Externally managed group - " + groupName);
        groupDao.createGroup(params);
    } catch (Exception e) {
        logger.warn("Error creating group", e);
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put(GROUP_NAME, groupName);
    Group group = groupDao.getGroupByName(params);
    if (group != null) {
        params = new HashMap<>();
        params.put(USER_ID, -1);
        params.put(USERNAME, username);
        User user = userDao.getUserByIdOrUsername(params);
        List<Long> users = new ArrayList<Long>();
        users.add(user.getId());
        params = new HashMap<>();
        params.put(USER_IDS, users);
        params.put(GROUP_ID, group.getId());
        try {
            groupDao.addGroupMembers(params);
            SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
            AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
            auditLog.setOperation(OPERATION_ADD_MEMBERS);
            auditLog.setActorId(user.getUsername());
            auditLog.setSiteId(siteFeed.getId());
            auditLog.setPrimaryTargetId(group.getGroupName() + ":" + user.getUsername());
            auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
            auditLog.setPrimaryTargetValue(user.getUsername());
            auditServiceInternal.insertAuditLog(auditLog);
        } catch (Exception e) {
            logger.debug("Unknown database error", e);
        }
    }
    return true;
}
Also used : UserGroup(org.craftercms.studio.api.v2.dal.UserGroup) Group(org.craftercms.studio.api.v2.dal.Group) User(org.craftercms.studio.api.v2.dal.User) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) NamingException(javax.naming.NamingException) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) UserAlreadyExistsException(org.craftercms.studio.api.v1.exception.security.UserAlreadyExistsException) AuthenticationException(org.springframework.ldap.AuthenticationException) CommunicationException(org.springframework.ldap.CommunicationException) AuthenticationSystemException(org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException) BadCredentialsException(org.craftercms.studio.api.v1.exception.security.BadCredentialsException) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) StudioConfiguration(org.craftercms.studio.api.v2.utils.StudioConfiguration) AuditServiceInternal(org.craftercms.studio.api.v2.service.audit.internal.AuditServiceInternal) UserDAO(org.craftercms.studio.api.v2.dal.UserDAO) SiteService(org.craftercms.studio.api.v1.service.site.SiteService) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) GroupDAO(org.craftercms.studio.api.v2.dal.GroupDAO)

Example 70 with StudioConfiguration

use of org.craftercms.studio.api.v2.utils.StudioConfiguration in project studio by craftercms.

the class SiteRepositoryUpgradePipelineImpl method execute.

/**
 * {@inheritDoc}
 */
@Override
public void execute(final String site) throws UpgradeException {
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, site);
    generalLockService.lock(gitLockKey);
    try {
        clusterSandboxRepoSyncTask.execute(site);
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
        Repository repository = helper.getRepository(site, GitRepositories.SANDBOX);
        String sandboxBranch = siteSandboxBranch;
        if (repository != null) {
            Git git = new Git(repository);
            try {
                if (!isEmpty()) {
                    SiteFeed siteFeed = siteService.getSite(site);
                    if (!StringUtils.isEmpty(siteFeed.getSandboxBranch())) {
                        sandboxBranch = siteFeed.getSandboxBranch();
                    }
                    createTemporaryBranch(site, git);
                    checkoutBranch(siteUpgradeBranch, git);
                    super.execute(site);
                    checkoutBranch(sandboxBranch, git);
                    mergeTemporaryBranch(repository, git);
                    deleteTemporaryBranch(git);
                }
            } catch (GitAPIException | IOException | SiteNotFoundException e) {
                throw new UpgradeException("Error branching or merging upgrade branch for site " + site, e);
            } finally {
                if (!isEmpty()) {
                    try {
                        checkoutBranch(sandboxBranch, git);
                    } catch (GitAPIException e) {
                        logger.error("Error cleaning up repo for site " + site, e);
                    }
                }
                git.close();
            }
        }
    } catch (CryptoException e) {
        throw new UpgradeException("Unexpected error upgrading site " + site, e);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) UpgradeException(org.craftercms.studio.api.v2.exception.UpgradeException) Repository(org.eclipse.jgit.lib.Repository) Git(org.eclipse.jgit.api.Git) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) IOException(java.io.IOException) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) CryptoException(org.craftercms.commons.crypto.CryptoException) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException)

Aggregations

GitRepositoryHelper (org.craftercms.studio.api.v2.utils.GitRepositoryHelper)65 Repository (org.eclipse.jgit.lib.Repository)59 RemoteRepository (org.craftercms.studio.api.v2.dal.RemoteRepository)58 CryptoException (org.craftercms.commons.crypto.CryptoException)53 IOException (java.io.IOException)47 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)43 ContentRepository (org.craftercms.studio.api.v1.repository.ContentRepository)42 Git (org.eclipse.jgit.api.Git)41 ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)34 ArrayList (java.util.ArrayList)22 UserNotFoundException (org.craftercms.studio.api.v1.exception.security.UserNotFoundException)21 Path (java.nio.file.Path)20 ObjectId (org.eclipse.jgit.lib.ObjectId)19 RevCommit (org.eclipse.jgit.revwalk.RevCommit)17 RevTree (org.eclipse.jgit.revwalk.RevTree)17 ContentRepository (org.craftercms.studio.api.v2.repository.ContentRepository)15 File (java.io.File)12 HashMap (java.util.HashMap)12 InvalidRemoteUrlException (org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException)11 InvalidRemoteException (org.eclipse.jgit.api.errors.InvalidRemoteException)10