use of org.craftercms.studio.api.v1.exception.security.UserNotFoundException 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");
}
}
use of org.craftercms.studio.api.v1.exception.security.UserNotFoundException in project studio by craftercms.
the class UserServiceImpl method enableUsers.
@Override
@HasPermission(type = DefaultPermission.class, action = "update_users")
public List<User> enableUsers(List<Long> userIds, List<String> usernames, boolean enabled) throws ServiceLayerException, UserNotFoundException, AuthenticationException {
List<User> users = userServiceInternal.enableUsers(userIds, usernames, enabled);
SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
auditLog.setSiteId(siteFeed.getId());
if (enabled) {
auditLog.setOperation(OPERATION_ENABLE);
} else {
auditLog.setOperation(OPERATION_DISABLE);
}
auditLog.setActorId(getCurrentUser().getUsername());
auditLog.setPrimaryTargetId(siteFeed.getSiteId());
auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
auditLog.setPrimaryTargetValue(siteFeed.getName());
List<AuditLogParameter> paramters = new ArrayList<AuditLogParameter>();
for (User u : users) {
AuditLogParameter paramter = new AuditLogParameter();
paramter.setTargetId(Long.toString(u.getId()));
paramter.setTargetType(TARGET_TYPE_USER);
paramter.setTargetValue(u.getUsername());
paramters.add(paramter);
}
auditLog.setParameters(paramters);
auditServiceInternal.insertAuditLog(auditLog);
return users;
}
use of org.craftercms.studio.api.v1.exception.security.UserNotFoundException in project studio by craftercms.
the class UserServiceImpl method getCurrentUser.
@Override
public AuthenticatedUser getCurrentUser() throws AuthenticationException, ServiceLayerException {
Authentication authentication = securityService.getAuthentication();
if (authentication != null) {
String username = authentication.getUsername();
User user;
try {
user = userServiceInternal.getUserByIdOrUsername(0, username);
} catch (UserNotFoundException e) {
throw new ServiceLayerException("Current authenticated user '" + username + "' wasn't found in repository", e);
}
if (user != null) {
AuthenticatedUser authUser = new AuthenticatedUser(user);
authUser.setAuthenticationType(authentication.getAuthenticationType());
return authUser;
} else {
throw new ServiceLayerException("Current authenticated user '" + username + "' wasn't found in repository");
}
} else {
throw new AuthenticationException("User should be authenticated");
}
}
use of org.craftercms.studio.api.v1.exception.security.UserNotFoundException in project studio by craftercms.
the class UserServiceImpl method getUserSites.
@Override
@HasPermission(type = DefaultPermission.class, action = "read_users")
public List<Site> getUserSites(long userId, String username) throws ServiceLayerException, UserNotFoundException {
List<Site> sites = new ArrayList<>();
Set<String> allSites = siteService.getAllAvailableSites();
List<Group> userGroups = userServiceInternal.getUserGroups(userId, username);
boolean isSysAdmin = userGroups.stream().anyMatch(group -> group.getGroupName().equals(SYSTEM_ADMIN_GROUP));
// Iterate all sites. If the user has any of the site groups, it has access to the site
for (String siteId : allSites) {
List<String> siteGroups = groupServiceInternal.getSiteGroups(siteId);
if (isSysAdmin || userGroups.stream().anyMatch(userGroup -> siteGroups.contains(userGroup.getGroupName()))) {
try {
SiteFeed siteFeed = siteService.getSite(siteId);
Site site = new Site();
site.setSiteId(siteFeed.getSiteId());
site.setDesc(siteFeed.getDescription());
sites.add(site);
} catch (SiteNotFoundException e) {
logger.error("Site not found: {0}", e, siteId);
}
}
}
return sites;
}
use of org.craftercms.studio.api.v1.exception.security.UserNotFoundException in project studio by craftercms.
the class UserServiceImpl method updateUser.
@Override
@HasPermission(type = DefaultPermission.class, action = "update_users")
public void updateUser(User user) throws ServiceLayerException, UserNotFoundException, AuthenticationException {
userServiceInternal.updateUser(user);
SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
auditLog.setOperation(OPERATION_UPDATE);
auditLog.setSiteId(siteFeed.getId());
auditLog.setActorId(getCurrentUser().getUsername());
auditLog.setPrimaryTargetId(user.getUsername());
auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
auditLog.setPrimaryTargetValue(user.getUsername());
auditServiceInternal.insertAuditLog(auditLog);
}
Aggregations