Fix codestyle/formatting within plugins/userauthenticators/ldap

This commit is contained in:
Ian Duffy 2013-11-20 14:00:08 +01:00
parent 917ea33ba9
commit 31758ed8d0
22 changed files with 1112 additions and 1111 deletions

View File

@ -33,67 +33,67 @@ import com.cloud.user.Account;
@APICommand(name = "addLdapConfiguration", description = "Add a new Ldap Configuration", responseObject = LdapConfigurationResponse.class, since = "4.2.0") @APICommand(name = "addLdapConfiguration", description = "Add a new Ldap Configuration", responseObject = LdapConfigurationResponse.class, since = "4.2.0")
public class LdapAddConfigurationCmd extends BaseCmd { public class LdapAddConfigurationCmd extends BaseCmd {
public static final Logger s_logger = Logger public static final Logger s_logger = Logger
.getLogger(LdapAddConfigurationCmd.class.getName()); .getLogger(LdapAddConfigurationCmd.class.getName());
private static final String s_name = "ldapconfigurationresponse"; private static final String s_name = "ldapconfigurationresponse";
@Inject @Inject
private LdapManager _ldapManager; private LdapManager _ldapManager;
@Parameter(name = "hostname", type = CommandType.STRING, required = true, description = "Hostname") @Parameter(name = "hostname", type = CommandType.STRING, required = true, description = "Hostname")
private String hostname; private String hostname;
@Parameter(name = "port", type = CommandType.INTEGER, required = true, description = "Port") @Parameter(name = "port", type = CommandType.INTEGER, required = true, description = "Port")
private int port; private int port;
public LdapAddConfigurationCmd() { public LdapAddConfigurationCmd() {
super(); super();
} }
public LdapAddConfigurationCmd(final LdapManager ldapManager) { public LdapAddConfigurationCmd(final LdapManager ldapManager) {
super(); super();
_ldapManager = ldapManager; _ldapManager = ldapManager;
} }
@Override @Override
public void execute() throws ServerApiException { public void execute() throws ServerApiException {
try { try {
final LdapConfigurationResponse response = _ldapManager final LdapConfigurationResponse response = _ldapManager
.addConfiguration(hostname, port); .addConfiguration(hostname, port);
response.setObjectName("LdapAddConfiguration"); response.setObjectName("LdapAddConfiguration");
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());
setResponseObject(response); setResponseObject(response);
} catch (final InvalidParameterValueException e) { } catch (final InvalidParameterValueException e) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR,
e.toString()); e.toString());
} }
} }
@Override @Override
public String getCommandName() { public String getCommandName() {
return s_name; return s_name;
} }
@Override @Override
public long getEntityOwnerId() { public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM; return Account.ACCOUNT_ID_SYSTEM;
} }
public String getHostname() { public String getHostname() {
return hostname; return hostname;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
public void setHostname(final String hostname) { public void setHostname(final String hostname) {
this.hostname = hostname; this.hostname = hostname;
} }
public void setPort(final int port) { public void setPort(final int port) {
this.port = port; this.port = port;
} }
} }

View File

@ -43,125 +43,125 @@ import com.cloud.user.UserAccount;
@APICommand(name = "ldapCreateAccount", description = "Creates an account from an LDAP user", responseObject = AccountResponse.class, since = "4.2.0") @APICommand(name = "ldapCreateAccount", description = "Creates an account from an LDAP user", responseObject = AccountResponse.class, since = "4.2.0")
public class LdapCreateAccountCmd extends BaseCmd { public class LdapCreateAccountCmd extends BaseCmd {
public static final Logger s_logger = Logger public static final Logger s_logger = Logger
.getLogger(LdapCreateAccountCmd.class.getName()); .getLogger(LdapCreateAccountCmd.class.getName());
private static final String s_name = "createaccountresponse"; private static final String s_name = "createaccountresponse";
@Inject @Inject
private LdapManager _ldapManager; private LdapManager _ldapManager;
@Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "Creates the user under the specified account. If no account is specified, the username will be used as the account name.") @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "Creates the user under the specified account. If no account is specified, the username will be used as the account name.")
private String accountName; private String accountName;
@Parameter(name = ApiConstants.ACCOUNT_TYPE, type = CommandType.SHORT, required = true, description = "Type of the account. Specify 0 for user, 1 for root admin, and 2 for domain admin") @Parameter(name = ApiConstants.ACCOUNT_TYPE, type = CommandType.SHORT, required = true, description = "Type of the account. Specify 0 for user, 1 for root admin, and 2 for domain admin")
private Short accountType; private Short accountType;
@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "Creates the user under the specified domain.") @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "Creates the user under the specified domain.")
private Long domainId; private Long domainId;
@Parameter(name = ApiConstants.TIMEZONE, type = CommandType.STRING, description = "Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") @Parameter(name = ApiConstants.TIMEZONE, type = CommandType.STRING, description = "Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.")
private String timezone; private String timezone;
@Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Unique username.") @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Unique username.")
private String username; private String username;
@Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "Network domain for the account's networks") @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "Network domain for the account's networks")
private String networkDomain; private String networkDomain;
@Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters")
private Map<String, String> details; private Map<String, String> details;
@Parameter(name = ApiConstants.ACCOUNT_ID, type = CommandType.STRING, description = "Account UUID, required for adding account from external provisioning system") @Parameter(name = ApiConstants.ACCOUNT_ID, type = CommandType.STRING, description = "Account UUID, required for adding account from external provisioning system")
private String accountUUID; private String accountUUID;
@Parameter(name = ApiConstants.USER_ID, type = CommandType.STRING, description = "User UUID, required for adding account from external provisioning system") @Parameter(name = ApiConstants.USER_ID, type = CommandType.STRING, description = "User UUID, required for adding account from external provisioning system")
private String userUUID; private String userUUID;
public LdapCreateAccountCmd() { public LdapCreateAccountCmd() {
super(); super();
} }
public LdapCreateAccountCmd(final LdapManager ldapManager, public LdapCreateAccountCmd(final LdapManager ldapManager,
final AccountService accountService) { final AccountService accountService) {
super(); super();
_ldapManager = ldapManager; _ldapManager = ldapManager;
_accountService = accountService; _accountService = accountService;
} }
UserAccount createCloudstackUserAccount(final LdapUser user) { UserAccount createCloudstackUserAccount(final LdapUser user) {
return _accountService.createUserAccount(username, generatePassword(), return _accountService.createUserAccount(username, generatePassword(),
user.getFirstname(), user.getLastname(), user.getEmail(), user.getFirstname(), user.getLastname(), user.getEmail(),
timezone, accountName, accountType, domainId, networkDomain, timezone, accountName, accountType, domainId, networkDomain,
details, accountUUID, userUUID); details, accountUUID, userUUID);
} }
@Override @Override
public void execute() throws ServerApiException { public void execute() throws ServerApiException {
final CallContext callContext = getCurrentContext(); final CallContext callContext = getCurrentContext();
callContext.setEventDetails("Account Name: " + accountName callContext.setEventDetails("Account Name: " + accountName
+ ", Domain Id:" + domainId); + ", Domain Id:" + domainId);
try { try {
final LdapUser user = _ldapManager.getUser(username); final LdapUser user = _ldapManager.getUser(username);
validateUser(user); validateUser(user);
final UserAccount userAccount = createCloudstackUserAccount(user); final UserAccount userAccount = createCloudstackUserAccount(user);
if (userAccount != null) { if (userAccount != null) {
final AccountResponse response = _responseGenerator final AccountResponse response = _responseGenerator
.createUserAccountResponse(userAccount); .createUserAccountResponse(userAccount);
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());
setResponseObject(response); setResponseObject(response);
} else { } else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR,
"Failed to create a user account"); "Failed to create a user account");
} }
} catch (final NamingException e) { } catch (final NamingException e) {
throw new ServerApiException( throw new ServerApiException(
ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR,
"No LDAP user exists with the username of " + username); "No LDAP user exists with the username of " + username);
} }
} }
private String generatePassword() throws ServerApiException { private String generatePassword() throws ServerApiException {
try { try {
final SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG"); final SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG");
final byte bytes[] = new byte[20]; final byte bytes[] = new byte[20];
randomGen.nextBytes(bytes); randomGen.nextBytes(bytes);
return Base64.encode(bytes).toString(); return Base64.encode(bytes).toString();
} catch (final NoSuchAlgorithmException e) { } catch (final NoSuchAlgorithmException e) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR,
"Failed to generate random password"); "Failed to generate random password");
} }
} }
@Override @Override
public String getCommandName() { public String getCommandName() {
return s_name; return s_name;
} }
CallContext getCurrentContext() { CallContext getCurrentContext() {
return CallContext.current(); return CallContext.current();
} }
@Override @Override
public long getEntityOwnerId() { public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM; return Account.ACCOUNT_ID_SYSTEM;
} }
private boolean validateUser(final LdapUser user) throws ServerApiException { private boolean validateUser(final LdapUser user) throws ServerApiException {
if (user.getEmail() == null) { if (user.getEmail() == null) {
throw new ServerApiException( throw new ServerApiException(
ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, username ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, username
+ " has no email address set within LDAP"); + " has no email address set within LDAP");
} }
if (user.getFirstname() == null) { if (user.getFirstname() == null) {
throw new ServerApiException( throw new ServerApiException(
ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, username ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, username
+ " has no firstname set within LDAP"); + " has no firstname set within LDAP");
} }
if (user.getLastname() == null) { if (user.getLastname() == null) {
throw new ServerApiException( throw new ServerApiException(
ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, username ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, username
+ " has no lastname set within LDAP"); + " has no lastname set within LDAP");
} }
return true; return true;
} }
} }

View File

@ -32,47 +32,47 @@ import com.cloud.user.Account;
@APICommand(name = "deleteLdapConfiguration", description = "Remove an Ldap Configuration", responseObject = LdapConfigurationResponse.class, since = "4.2.0") @APICommand(name = "deleteLdapConfiguration", description = "Remove an Ldap Configuration", responseObject = LdapConfigurationResponse.class, since = "4.2.0")
public class LdapDeleteConfigurationCmd extends BaseCmd { public class LdapDeleteConfigurationCmd extends BaseCmd {
public static final Logger s_logger = Logger public static final Logger s_logger = Logger
.getLogger(LdapDeleteConfigurationCmd.class.getName()); .getLogger(LdapDeleteConfigurationCmd.class.getName());
private static final String s_name = "ldapconfigurationresponse"; private static final String s_name = "ldapconfigurationresponse";
@Inject @Inject
private LdapManager _ldapManager; private LdapManager _ldapManager;
@Parameter(name = "hostname", type = CommandType.STRING, required = true, description = "Hostname") @Parameter(name = "hostname", type = CommandType.STRING, required = true, description = "Hostname")
private String hostname; private String hostname;
public LdapDeleteConfigurationCmd() { public LdapDeleteConfigurationCmd() {
super(); super();
} }
public LdapDeleteConfigurationCmd(final LdapManager ldapManager) { public LdapDeleteConfigurationCmd(final LdapManager ldapManager) {
super(); super();
_ldapManager = ldapManager; _ldapManager = ldapManager;
} }
@Override @Override
public void execute() throws ServerApiException { public void execute() throws ServerApiException {
try { try {
final LdapConfigurationResponse response = _ldapManager final LdapConfigurationResponse response = _ldapManager
.deleteConfiguration(hostname); .deleteConfiguration(hostname);
response.setObjectName("LdapDeleteConfiguration"); response.setObjectName("LdapDeleteConfiguration");
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());
setResponseObject(response); setResponseObject(response);
} catch (final InvalidParameterValueException e) { } catch (final InvalidParameterValueException e) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR,
e.toString()); e.toString());
} }
} }
@Override @Override
public String getCommandName() { public String getCommandName() {
return s_name; return s_name;
} }
@Override @Override
public long getEntityOwnerId() { public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM; return Account.ACCOUNT_ID_SYSTEM;
} }
} }

View File

@ -58,12 +58,12 @@ public class LdapImportUsersCmd extends BaseListCmd {
private Map<String, String> details; private Map<String, String> details;
@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "Specifies the domain to which the ldap users are to be " @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "Specifies the domain to which the ldap users are to be "
+ "imported. If no domain is specified, a domain will created using group parameter. If the group is also not specified, a domain name based on the OU information will be " + "imported. If no domain is specified, a domain will created using group parameter. If the group is also not specified, a domain name based on the OU information will be "
+ "created. If no OU hierarchy exists, will be defaulted to ROOT domain") + "created. If no OU hierarchy exists, will be defaulted to ROOT domain")
private Long domainId; private Long domainId;
@Parameter(name = ApiConstants.GROUP, type = CommandType.STRING, description = "Specifies the group name from which the ldap users are to be imported. " @Parameter(name = ApiConstants.GROUP, type = CommandType.STRING, description = "Specifies the group name from which the ldap users are to be imported. "
+ "If no group is specified, all the users will be imported.") + "If no group is specified, all the users will be imported.")
private String groupName; private String groupName;
private Domain _domain; private Domain _domain;
@ -84,7 +84,7 @@ public class LdapImportUsersCmd extends BaseListCmd {
@Override @Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException,
NetworkRuleConflictException { NetworkRuleConflictException {
List<LdapUser> users; List<LdapUser> users;
try { try {
@ -103,7 +103,7 @@ public class LdapImportUsersCmd extends BaseListCmd {
Domain domain = getDomain(user); Domain domain = getDomain(user);
try { try {
_accountService.createUserAccount(user.getUsername(), generatePassword(), user.getFirstname(), user.getLastname(), user.getEmail(), timezone, user.getUsername(), _accountService.createUserAccount(user.getUsername(), generatePassword(), user.getFirstname(), user.getLastname(), user.getEmail(), timezone, user.getUsername(),
accountType, domain.getId(), domain.getNetworkDomain(), details, UUID.randomUUID().toString(), UUID.randomUUID().toString()); accountType, domain.getId(), domain.getNetworkDomain(), details, UUID.randomUUID().toString(), UUID.randomUUID().toString());
addedUsers.add(user); addedUsers.add(user);
} catch (InvalidParameterValueException ex) { } catch (InvalidParameterValueException ex) {
s_logger.error("Failed to create user with username: " + user.getUsername() +" ::: "+ex.getMessage()); s_logger.error("Failed to create user with username: " + user.getUsername() +" ::: "+ex.getMessage());

View File

@ -35,76 +35,76 @@ import com.cloud.utils.Pair;
@APICommand(name = "listLdapConfigurations", responseObject = LdapConfigurationResponse.class, description = "Lists all LDAP configurations", since = "4.2.0") @APICommand(name = "listLdapConfigurations", responseObject = LdapConfigurationResponse.class, description = "Lists all LDAP configurations", since = "4.2.0")
public class LdapListConfigurationCmd extends BaseListCmd { public class LdapListConfigurationCmd extends BaseListCmd {
public static final Logger s_logger = Logger public static final Logger s_logger = Logger
.getLogger(LdapListConfigurationCmd.class.getName()); .getLogger(LdapListConfigurationCmd.class.getName());
private static final String s_name = "ldapconfigurationresponse"; private static final String s_name = "ldapconfigurationresponse";
@Inject @Inject
private LdapManager _ldapManager; private LdapManager _ldapManager;
@Parameter(name = "hostname", type = CommandType.STRING, required = false, description = "Hostname") @Parameter(name = "hostname", type = CommandType.STRING, required = false, description = "Hostname")
private String hostname; private String hostname;
@Parameter(name = "port", type = CommandType.INTEGER, required = false, description = "Port") @Parameter(name = "port", type = CommandType.INTEGER, required = false, description = "Port")
private int port; private int port;
public LdapListConfigurationCmd() { public LdapListConfigurationCmd() {
super(); super();
} }
public LdapListConfigurationCmd(final LdapManager ldapManager) { public LdapListConfigurationCmd(final LdapManager ldapManager) {
super(); super();
_ldapManager = ldapManager; _ldapManager = ldapManager;
} }
private List<LdapConfigurationResponse> createLdapConfigurationResponses( private List<LdapConfigurationResponse> createLdapConfigurationResponses(
final List<? extends LdapConfigurationVO> configurations) { final List<? extends LdapConfigurationVO> configurations) {
final List<LdapConfigurationResponse> responses = new ArrayList<LdapConfigurationResponse>(); final List<LdapConfigurationResponse> responses = new ArrayList<LdapConfigurationResponse>();
for (final LdapConfigurationVO resource : configurations) { for (final LdapConfigurationVO resource : configurations) {
final LdapConfigurationResponse configurationResponse = _ldapManager final LdapConfigurationResponse configurationResponse = _ldapManager
.createLdapConfigurationResponse(resource); .createLdapConfigurationResponse(resource);
configurationResponse.setObjectName("LdapConfiguration"); configurationResponse.setObjectName("LdapConfiguration");
responses.add(configurationResponse); responses.add(configurationResponse);
} }
return responses; return responses;
} }
@Override @Override
public void execute() { public void execute() {
final Pair<List<? extends LdapConfigurationVO>, Integer> result = _ldapManager final Pair<List<? extends LdapConfigurationVO>, Integer> result = _ldapManager
.listConfigurations(this); .listConfigurations(this);
final List<LdapConfigurationResponse> responses = createLdapConfigurationResponses(result final List<LdapConfigurationResponse> responses = createLdapConfigurationResponses(result
.first()); .first());
final ListResponse<LdapConfigurationResponse> response = new ListResponse<LdapConfigurationResponse>(); final ListResponse<LdapConfigurationResponse> response = new ListResponse<LdapConfigurationResponse>();
response.setResponses(responses, result.second()); response.setResponses(responses, result.second());
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());
setResponseObject(response); setResponseObject(response);
} }
@Override @Override
public String getCommandName() { public String getCommandName() {
return s_name; return s_name;
} }
@Override @Override
public long getEntityOwnerId() { public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM; return Account.ACCOUNT_ID_SYSTEM;
} }
public String getHostname() { public String getHostname() {
return hostname; return hostname;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
public void setHostname(final String hostname) { public void setHostname(final String hostname) {
this.hostname = hostname; this.hostname = hostname;
} }
public void setPort(final int port) { public void setPort(final int port) {
this.port = port; this.port = port;
} }
} }

View File

@ -40,84 +40,84 @@ import com.cloud.user.Account;
@APICommand(name = "listLdapUsers", responseObject = LdapUserResponse.class, description = "Lists all LDAP Users", since = "4.2.0") @APICommand(name = "listLdapUsers", responseObject = LdapUserResponse.class, description = "Lists all LDAP Users", since = "4.2.0")
public class LdapListUsersCmd extends BaseListCmd { public class LdapListUsersCmd extends BaseListCmd {
public static final Logger s_logger = Logger public static final Logger s_logger = Logger
.getLogger(LdapListUsersCmd.class.getName()); .getLogger(LdapListUsersCmd.class.getName());
private static final String s_name = "ldapuserresponse"; private static final String s_name = "ldapuserresponse";
@Inject @Inject
private LdapManager _ldapManager; private LdapManager _ldapManager;
@Inject @Inject
private QueryService _queryService; private QueryService _queryService;
@Parameter(name = "listtype", type = CommandType.STRING, required = false, description = "Determines whether all ldap users are returned or just non-cloudstack users") @Parameter(name = "listtype", type = CommandType.STRING, required = false, description = "Determines whether all ldap users are returned or just non-cloudstack users")
private String listType; private String listType;
public LdapListUsersCmd() { public LdapListUsersCmd() {
super(); super();
} }
public LdapListUsersCmd(final LdapManager ldapManager, public LdapListUsersCmd(final LdapManager ldapManager,
final QueryService queryService) { final QueryService queryService) {
super(); super();
_ldapManager = ldapManager; _ldapManager = ldapManager;
_queryService = queryService; _queryService = queryService;
} }
private List<LdapUserResponse> createLdapUserResponse( private List<LdapUserResponse> createLdapUserResponse(
final List<LdapUser> users) { final List<LdapUser> users) {
final List<LdapUserResponse> ldapResponses = new ArrayList<LdapUserResponse>(); final List<LdapUserResponse> ldapResponses = new ArrayList<LdapUserResponse>();
for (final LdapUser user : users) { for (final LdapUser user : users) {
if (getListType().equals("all") || !isACloudstackUser(user)) { if (getListType().equals("all") || !isACloudstackUser(user)) {
final LdapUserResponse ldapResponse = _ldapManager final LdapUserResponse ldapResponse = _ldapManager
.createLdapUserResponse(user); .createLdapUserResponse(user);
ldapResponse.setObjectName("LdapUser"); ldapResponse.setObjectName("LdapUser");
ldapResponses.add(ldapResponse); ldapResponses.add(ldapResponse);
} }
} }
return ldapResponses; return ldapResponses;
} }
@Override @Override
public void execute() throws ServerApiException { public void execute() throws ServerApiException {
List<LdapUserResponse> ldapResponses = null; List<LdapUserResponse> ldapResponses = null;
final ListResponse<LdapUserResponse> response = new ListResponse<LdapUserResponse>(); final ListResponse<LdapUserResponse> response = new ListResponse<LdapUserResponse>();
try { try {
final List<LdapUser> users = _ldapManager.getUsers(); final List<LdapUser> users = _ldapManager.getUsers();
ldapResponses = createLdapUserResponse(users); ldapResponses = createLdapUserResponse(users);
} catch (final NoLdapUserMatchingQueryException ex) { } catch (final NoLdapUserMatchingQueryException ex) {
ldapResponses = new ArrayList<LdapUserResponse>(); ldapResponses = new ArrayList<LdapUserResponse>();
} finally { } finally {
response.setResponses(ldapResponses); response.setResponses(ldapResponses);
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());
setResponseObject(response); setResponseObject(response);
} }
} }
@Override @Override
public String getCommandName() { public String getCommandName() {
return s_name; return s_name;
} }
@Override @Override
public long getEntityOwnerId() { public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM; return Account.ACCOUNT_ID_SYSTEM;
} }
private String getListType() { private String getListType() {
return listType == null ? "all" : listType; return listType == null ? "all" : listType;
} }
private boolean isACloudstackUser(final LdapUser ldapUser) { private boolean isACloudstackUser(final LdapUser ldapUser) {
final ListResponse<UserResponse> response = _queryService final ListResponse<UserResponse> response = _queryService
.searchForUsers(new ListUsersCmd()); .searchForUsers(new ListUsersCmd());
final List<UserResponse> cloudstackUsers = response.getResponses(); final List<UserResponse> cloudstackUsers = response.getResponses();
if (cloudstackUsers != null && cloudstackUsers.size() != 0) { if (cloudstackUsers != null && cloudstackUsers.size() != 0) {
for (final UserResponse cloudstackUser : response.getResponses()) { for (final UserResponse cloudstackUser : response.getResponses()) {
if (ldapUser.getUsername().equals(cloudstackUser.getUsername())) { if (ldapUser.getUsername().equals(cloudstackUser.getUsername())) {
return true; return true;
} }
} }
} }
return false; return false;
} }
} }

View File

@ -36,63 +36,63 @@ import com.cloud.user.Account;
@APICommand(name = "searchLdap", responseObject = LdapUserResponse.class, description = "Searches LDAP based on the username attribute", since = "4.2.0") @APICommand(name = "searchLdap", responseObject = LdapUserResponse.class, description = "Searches LDAP based on the username attribute", since = "4.2.0")
public class LdapUserSearchCmd extends BaseListCmd { public class LdapUserSearchCmd extends BaseListCmd {
public static final Logger s_logger = Logger public static final Logger s_logger = Logger
.getLogger(LdapUserSearchCmd.class.getName()); .getLogger(LdapUserSearchCmd.class.getName());
private static final String s_name = "ldapuserresponse"; private static final String s_name = "ldapuserresponse";
@Inject @Inject
private LdapManager _ldapManager; private LdapManager _ldapManager;
@Parameter(name = "query", type = CommandType.STRING, entityType = LdapUserResponse.class, required = true, description = "query to search using") @Parameter(name = "query", type = CommandType.STRING, entityType = LdapUserResponse.class, required = true, description = "query to search using")
private String query; private String query;
public LdapUserSearchCmd() { public LdapUserSearchCmd() {
super(); super();
} }
public LdapUserSearchCmd(final LdapManager ldapManager) { public LdapUserSearchCmd(final LdapManager ldapManager) {
super(); super();
_ldapManager = ldapManager; _ldapManager = ldapManager;
} }
private List<LdapUserResponse> createLdapUserResponse( private List<LdapUserResponse> createLdapUserResponse(
final List<LdapUser> users) { final List<LdapUser> users) {
final List<LdapUserResponse> ldapUserResponses = new ArrayList<LdapUserResponse>(); final List<LdapUserResponse> ldapUserResponses = new ArrayList<LdapUserResponse>();
if (users != null) { if (users != null) {
for (final LdapUser user : users) { for (final LdapUser user : users) {
final LdapUserResponse ldapUserResponse = _ldapManager final LdapUserResponse ldapUserResponse = _ldapManager
.createLdapUserResponse(user); .createLdapUserResponse(user);
ldapUserResponse.setObjectName("LdapUser"); ldapUserResponse.setObjectName("LdapUser");
ldapUserResponses.add(ldapUserResponse); ldapUserResponses.add(ldapUserResponse);
} }
} }
return ldapUserResponses; return ldapUserResponses;
} }
@Override @Override
public void execute() { public void execute() {
final ListResponse<LdapUserResponse> response = new ListResponse<LdapUserResponse>(); final ListResponse<LdapUserResponse> response = new ListResponse<LdapUserResponse>();
List<LdapUser> users = null; List<LdapUser> users = null;
try { try {
users = _ldapManager.searchUsers(query); users = _ldapManager.searchUsers(query);
} catch (final NoLdapUserMatchingQueryException e) { } catch (final NoLdapUserMatchingQueryException e) {
s_logger.debug(e.getMessage()); s_logger.debug(e.getMessage());
} }
final List<LdapUserResponse> ldapUserResponses = createLdapUserResponse(users); final List<LdapUserResponse> ldapUserResponses = createLdapUserResponse(users);
response.setResponses(ldapUserResponses); response.setResponses(ldapUserResponses);
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());
setResponseObject(response); setResponseObject(response);
} }
@Override @Override
public String getCommandName() { public String getCommandName() {
return s_name; return s_name;
} }
@Override @Override
public long getEntityOwnerId() { public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM; return Account.ACCOUNT_ID_SYSTEM;
} }
} }

View File

@ -22,41 +22,41 @@ import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
public class LdapConfigurationResponse extends BaseResponse { public class LdapConfigurationResponse extends BaseResponse {
@SerializedName("hostname") @SerializedName("hostname")
@Param(description = "hostname") @Param(description = "hostname")
private String hostname; private String hostname;
@SerializedName("port") @SerializedName("port")
@Param(description = "port") @Param(description = "port")
private int port; private int port;
public LdapConfigurationResponse() { public LdapConfigurationResponse() {
super(); super();
} }
public LdapConfigurationResponse(final String hostname) { public LdapConfigurationResponse(final String hostname) {
super(); super();
this.hostname = hostname; this.hostname = hostname;
} }
public LdapConfigurationResponse(final String hostname, final int port) { public LdapConfigurationResponse(final String hostname, final int port) {
this.hostname = hostname; this.hostname = hostname;
this.port = port; this.port = port;
} }
public String getHostname() { public String getHostname() {
return hostname; return hostname;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
public void setHostname(final String hostname) { public void setHostname(final String hostname) {
this.hostname = hostname; this.hostname = hostname;
} }
public void setPort(final int port) { public void setPort(final int port) {
this.port = port; this.port = port;
} }
} }

View File

@ -46,64 +46,64 @@ public class LdapUserResponse extends BaseResponse {
private String domain; private String domain;
public LdapUserResponse() { public LdapUserResponse() {
super(); super();
} }
public LdapUserResponse(final String username, final String email, final String firstname, final String lastname, final String principal, String domain) { public LdapUserResponse(final String username, final String email, final String firstname, final String lastname, final String principal, String domain) {
super(); super();
this.username = username; this.username = username;
this.email = email; this.email = email;
this.firstname = firstname; this.firstname = firstname;
this.lastname = lastname; this.lastname = lastname;
this.principal = principal; this.principal = principal;
this.domain = domain; this.domain = domain;
} }
public String getEmail() { public String getEmail() {
return email; return email;
} }
public String getFirstname() { public String getFirstname() {
return firstname; return firstname;
} }
public String getLastname() { public String getLastname() {
return lastname; return lastname;
} }
public String getPrincipal() { public String getPrincipal() {
return principal; return principal;
} }
public String getUsername() { public String getUsername() {
return username; return username;
} }
public String getDomain() { public String getDomain() {
return domain; return domain;
} }
public void setEmail(final String email) { public void setEmail(final String email) {
this.email = email; this.email = email;
} }
public void setFirstname(final String firstname) { public void setFirstname(final String firstname) {
this.firstname = firstname; this.firstname = firstname;
} }
public void setLastname(final String lastname) { public void setLastname(final String lastname) {
this.lastname = lastname; this.lastname = lastname;
} }
public void setPrincipal(final String principal) { public void setPrincipal(final String principal) {
this.principal = principal; this.principal = principal;
} }
public void setUsername(final String username) { public void setUsername(final String username) {
this.username = username; this.username = username;
} }
public void setDomain(String domain) { public void setDomain(String domain) {
this.domain = domain; this.domain = domain;
} }
} }

View File

@ -27,45 +27,45 @@ import com.cloud.user.UserAccount;
import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserAccountDao;
public class LdapAuthenticator extends DefaultUserAuthenticator { public class LdapAuthenticator extends DefaultUserAuthenticator {
private static final Logger s_logger = Logger private static final Logger s_logger = Logger
.getLogger(LdapAuthenticator.class.getName()); .getLogger(LdapAuthenticator.class.getName());
@Inject @Inject
private LdapManager _ldapManager; private LdapManager _ldapManager;
@Inject @Inject
private UserAccountDao _userAccountDao; private UserAccountDao _userAccountDao;
public LdapAuthenticator() { public LdapAuthenticator() {
super(); super();
} }
public LdapAuthenticator(final LdapManager ldapManager, public LdapAuthenticator(final LdapManager ldapManager,
final UserAccountDao userAccountDao) { final UserAccountDao userAccountDao) {
super(); super();
_ldapManager = ldapManager; _ldapManager = ldapManager;
_userAccountDao = userAccountDao; _userAccountDao = userAccountDao;
} }
@Override @Override
public boolean authenticate(final String username, final String password, public boolean authenticate(final String username, final String password,
final Long domainId, final Map<String, Object[]> requestParameters) { final Long domainId, final Map<String, Object[]> requestParameters) {
final UserAccount user = _userAccountDao.getUserAccount(username, final UserAccount user = _userAccountDao.getUserAccount(username,
domainId); domainId);
if (user == null) { if (user == null) {
s_logger.debug("Unable to find user with " + username s_logger.debug("Unable to find user with " + username
+ " in domain " + domainId); + " in domain " + domainId);
return false; return false;
} else if (_ldapManager.isLdapEnabled()) { } else if (_ldapManager.isLdapEnabled()) {
return _ldapManager.canAuthenticate(username, password); return _ldapManager.canAuthenticate(username, password);
} else { } else {
return false; return false;
} }
} }
@Override @Override
public String encode(final String password) { public String encode(final String password) {
return password; return password;
} }
} }

View File

@ -27,133 +27,134 @@ import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
public class LdapConfiguration { public class LdapConfiguration {
private final static String factory = "com.sun.jndi.ldap.LdapCtxFactory"; private final static String factory = "com.sun.jndi.ldap.LdapCtxFactory";
private final static int scope = SearchControls.SUBTREE_SCOPE; private final static int scope = SearchControls.SUBTREE_SCOPE;
@Inject @Inject
private ConfigurationDao _configDao; private ConfigurationDao _configDao;
@Inject @Inject
private LdapManager _ldapManager; private LdapManager _ldapManager;
public LdapConfiguration() { public LdapConfiguration() {
} }
public LdapConfiguration(final ConfigurationDao configDao, public LdapConfiguration(final ConfigurationDao configDao,
final LdapManager ldapManager) { final LdapManager ldapManager) {
_configDao = configDao; _configDao = configDao;
_ldapManager = ldapManager; _ldapManager = ldapManager;
} }
public String getAuthentication() { public String getAuthentication() {
if ((getBindPrincipal() == null) && (getBindPassword() == null)) { if ((getBindPrincipal() == null) && (getBindPassword() == null)) {
return "none"; return "none";
} else { } else {
return "simple"; return "simple";
} }
} }
public String getBaseDn() { public String getBaseDn() {
return _configDao.getValue("ldap.basedn"); return _configDao.getValue("ldap.basedn");
} }
public String getBindPassword() { public String getBindPassword() {
return _configDao.getValue("ldap.bind.password"); return _configDao.getValue("ldap.bind.password");
} }
public String getBindPrincipal() { public String getBindPrincipal() {
return _configDao.getValue("ldap.bind.principal"); return _configDao.getValue("ldap.bind.principal");
} }
public String getEmailAttribute() { public String getEmailAttribute() {
final String emailAttribute = _configDao final String emailAttribute = _configDao
.getValue("ldap.email.attribute"); .getValue("ldap.email.attribute");
return emailAttribute == null ? "mail" : emailAttribute; return emailAttribute == null ? "mail" : emailAttribute;
} }
public String getFactory() { public String getFactory() {
return factory; return factory;
} }
public String getFirstnameAttribute() { public String getFirstnameAttribute() {
final String firstnameAttribute = _configDao final String firstnameAttribute = _configDao
.getValue("ldap.firstname.attribute"); .getValue("ldap.firstname.attribute");
return firstnameAttribute == null ? "givenname" : firstnameAttribute; return firstnameAttribute == null ? "givenname" : firstnameAttribute;
} }
public String getLastnameAttribute() { public String getLastnameAttribute() {
final String lastnameAttribute = _configDao final String lastnameAttribute = _configDao
.getValue("ldap.lastname.attribute"); .getValue("ldap.lastname.attribute");
return lastnameAttribute == null ? "sn" : lastnameAttribute; return lastnameAttribute == null ? "sn" : lastnameAttribute;
} }
public String getProviderUrl() { public String getProviderUrl() {
final String protocol = getSSLStatus() == true ? "ldaps://" : "ldap://"; final String protocol = getSSLStatus() == true ? "ldaps://" : "ldap://";
final Pair<List<? extends LdapConfigurationVO>, Integer> result = _ldapManager final Pair<List<? extends LdapConfigurationVO>, Integer> result = _ldapManager
.listConfigurations(new LdapListConfigurationCmd(_ldapManager)); .listConfigurations(new LdapListConfigurationCmd(_ldapManager));
final StringBuilder providerUrls = new StringBuilder(); final StringBuilder providerUrls = new StringBuilder();
String delim = ""; String delim = "";
for (final LdapConfigurationVO resource : result.first()) { for (final LdapConfigurationVO resource : result.first()) {
final String providerUrl = protocol + resource.getHostname() + ":" final String providerUrl = protocol + resource.getHostname() + ":"
+ resource.getPort(); + resource.getPort();
providerUrls.append(delim).append(providerUrl); providerUrls.append(delim).append(providerUrl);
delim = " "; delim = " ";
} }
return providerUrls.toString(); return providerUrls.toString();
} }
public String[] getReturnAttributes() { public String[] getReturnAttributes() {
return new String[] { getUsernameAttribute(), getEmailAttribute(), return new String[] { getUsernameAttribute(), getEmailAttribute(),
getFirstnameAttribute(), getLastnameAttribute(), getCommonNameAttribute() }; getFirstnameAttribute(), getLastnameAttribute(), getCommonNameAttribute()
} };
}
public int getScope() { public int getScope() {
return scope; return scope;
} }
public String getSearchGroupPrinciple() { public String getSearchGroupPrinciple() {
return _configDao.getValue("ldap.search.group.principle"); return _configDao.getValue("ldap.search.group.principle");
} }
public boolean getSSLStatus() { public boolean getSSLStatus() {
boolean sslStatus = false; boolean sslStatus = false;
if (getTrustStore() != null && getTrustStorePassword() != null) { if (getTrustStore() != null && getTrustStorePassword() != null) {
sslStatus = true; sslStatus = true;
} }
return sslStatus; return sslStatus;
} }
public String getTrustStore() { public String getTrustStore() {
return _configDao.getValue("ldap.truststore"); return _configDao.getValue("ldap.truststore");
} }
public String getTrustStorePassword() { public String getTrustStorePassword() {
return _configDao.getValue("ldap.truststore.password"); return _configDao.getValue("ldap.truststore.password");
} }
public String getUsernameAttribute() { public String getUsernameAttribute() {
final String usernameAttribute = _configDao final String usernameAttribute = _configDao
.getValue("ldap.username.attribute"); .getValue("ldap.username.attribute");
return usernameAttribute == null ? "uid" : usernameAttribute; return usernameAttribute == null ? "uid" : usernameAttribute;
} }
public String getUserObject() { public String getUserObject() {
final String userObject = _configDao.getValue("ldap.user.object"); final String userObject = _configDao.getValue("ldap.user.object");
return userObject == null ? "inetOrgPerson" : userObject; return userObject == null ? "inetOrgPerson" : userObject;
} }
public String getGroupObject() { public String getGroupObject() {
final String groupObject = _configDao.getValue("ldap.group.object"); final String groupObject = _configDao.getValue("ldap.group.object");
return groupObject == null ? "groupOfUniqueNames" : groupObject; return groupObject == null ? "groupOfUniqueNames" : groupObject;
} }
public String getGroupUniqueMemeberAttribute() { public String getGroupUniqueMemeberAttribute() {
final String uniqueMemberAttribute = _configDao.getValue("ldap.group.user.uniquemember"); final String uniqueMemberAttribute = _configDao.getValue("ldap.group.user.uniquemember");
return uniqueMemberAttribute == null ? "uniquemember" : uniqueMemberAttribute; return uniqueMemberAttribute == null ? "uniquemember" : uniqueMemberAttribute;
} }
public String getCommonNameAttribute() { public String getCommonNameAttribute() {
return "cn"; return "cn";
} }
} }

View File

@ -28,39 +28,39 @@ import org.apache.cloudstack.api.InternalIdentity;
@Entity @Entity
@Table(name = "ldap_configuration") @Table(name = "ldap_configuration")
public class LdapConfigurationVO implements InternalIdentity { public class LdapConfigurationVO implements InternalIdentity {
@Column(name = "hostname") @Column(name = "hostname")
private String hostname; private String hostname;
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id") @Column(name = "id")
private Long id; private Long id;
@Column(name = "port") @Column(name = "port")
private int port; private int port;
public LdapConfigurationVO() { public LdapConfigurationVO() {
} }
public LdapConfigurationVO(final String hostname, final int port) { public LdapConfigurationVO(final String hostname, final int port) {
this.hostname = hostname; this.hostname = hostname;
this.port = port; this.port = port;
} }
public String getHostname() { public String getHostname() {
return hostname; return hostname;
} }
@Override @Override
public long getId() { public long getId() {
return id; return id;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
public void setId(final long id) { public void setId(final long id) {
this.id = id; this.id = id;
} }
} }

View File

@ -27,110 +27,110 @@ import javax.naming.directory.InitialDirContext;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
public class LdapContextFactory { public class LdapContextFactory {
private static final Logger s_logger = Logger private static final Logger s_logger = Logger
.getLogger(LdapContextFactory.class.getName()); .getLogger(LdapContextFactory.class.getName());
@Inject @Inject
private LdapConfiguration _ldapConfiguration; private LdapConfiguration _ldapConfiguration;
public LdapContextFactory() { public LdapContextFactory() {
} }
public LdapContextFactory(final LdapConfiguration ldapConfiguration) { public LdapContextFactory(final LdapConfiguration ldapConfiguration) {
_ldapConfiguration = ldapConfiguration; _ldapConfiguration = ldapConfiguration;
} }
public DirContext createBindContext() throws NamingException { public DirContext createBindContext() throws NamingException {
return createBindContext(null); return createBindContext(null);
} }
public DirContext createBindContext(final String providerUrl) public DirContext createBindContext(final String providerUrl)
throws NamingException { throws NamingException {
final String bindPrincipal = _ldapConfiguration.getBindPrincipal(); final String bindPrincipal = _ldapConfiguration.getBindPrincipal();
final String bindPassword = _ldapConfiguration.getBindPassword(); final String bindPassword = _ldapConfiguration.getBindPassword();
return createInitialDirContext(bindPrincipal, bindPassword, return createInitialDirContext(bindPrincipal, bindPassword,
providerUrl, true); providerUrl, true);
} }
private DirContext createInitialDirContext(final String principal, private DirContext createInitialDirContext(final String principal,
final String password, final boolean isSystemContext) final String password, final boolean isSystemContext)
throws NamingException { throws NamingException {
return createInitialDirContext(principal, password, null, return createInitialDirContext(principal, password, null,
isSystemContext); isSystemContext);
} }
private DirContext createInitialDirContext(final String principal, private DirContext createInitialDirContext(final String principal,
final String password, final String providerUrl, final String password, final String providerUrl,
final boolean isSystemContext) throws NamingException { final boolean isSystemContext) throws NamingException {
return new InitialDirContext(getEnvironment(principal, password, return new InitialDirContext(getEnvironment(principal, password,
providerUrl, isSystemContext)); providerUrl, isSystemContext));
} }
public DirContext createUserContext(final String principal, public DirContext createUserContext(final String principal,
final String password) throws NamingException { final String password) throws NamingException {
return createInitialDirContext(principal, password, false); return createInitialDirContext(principal, password, false);
} }
private void enableSSL(final Hashtable<String, String> environment) { private void enableSSL(final Hashtable<String, String> environment) {
final boolean sslStatus = _ldapConfiguration.getSSLStatus(); final boolean sslStatus = _ldapConfiguration.getSSLStatus();
if (sslStatus) { if (sslStatus) {
s_logger.info("LDAP SSL enabled."); s_logger.info("LDAP SSL enabled.");
environment.put(Context.SECURITY_PROTOCOL, "ssl"); environment.put(Context.SECURITY_PROTOCOL, "ssl");
System.setProperty("javax.net.ssl.trustStore", System.setProperty("javax.net.ssl.trustStore",
_ldapConfiguration.getTrustStore()); _ldapConfiguration.getTrustStore());
System.setProperty("javax.net.ssl.trustStorePassword", System.setProperty("javax.net.ssl.trustStorePassword",
_ldapConfiguration.getTrustStorePassword()); _ldapConfiguration.getTrustStorePassword());
} }
} }
private Hashtable<String, String> getEnvironment(final String principal, private Hashtable<String, String> getEnvironment(final String principal,
final String password, final String providerUrl, final String password, final String providerUrl,
final boolean isSystemContext) { final boolean isSystemContext) {
final String factory = _ldapConfiguration.getFactory(); final String factory = _ldapConfiguration.getFactory();
final String url = providerUrl == null ? _ldapConfiguration final String url = providerUrl == null ? _ldapConfiguration
.getProviderUrl() : providerUrl; .getProviderUrl() : providerUrl;
final Hashtable<String, String> environment = new Hashtable<String, String>(); final Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, factory); environment.put(Context.INITIAL_CONTEXT_FACTORY, factory);
environment.put(Context.PROVIDER_URL, url); environment.put(Context.PROVIDER_URL, url);
environment.put("com.sun.jndi.ldap.read.timeout", "500"); environment.put("com.sun.jndi.ldap.read.timeout", "500");
environment.put("com.sun.jndi.ldap.connect.pool", "true"); environment.put("com.sun.jndi.ldap.connect.pool", "true");
enableSSL(environment); enableSSL(environment);
setAuthentication(environment, isSystemContext); setAuthentication(environment, isSystemContext);
if (principal != null) { if (principal != null) {
environment.put(Context.SECURITY_PRINCIPAL, principal); environment.put(Context.SECURITY_PRINCIPAL, principal);
} }
if (password != null) { if (password != null) {
environment.put(Context.SECURITY_CREDENTIALS, password); environment.put(Context.SECURITY_CREDENTIALS, password);
} }
return environment; return environment;
} }
private void setAuthentication(final Hashtable<String, String> environment, private void setAuthentication(final Hashtable<String, String> environment,
final boolean isSystemContext) { final boolean isSystemContext) {
final String authentication = _ldapConfiguration.getAuthentication(); final String authentication = _ldapConfiguration.getAuthentication();
if ("none".equals(authentication) && !isSystemContext) { if ("none".equals(authentication) && !isSystemContext) {
environment.put(Context.SECURITY_AUTHENTICATION, "simple"); environment.put(Context.SECURITY_AUTHENTICATION, "simple");
} else { } else {
environment.put(Context.SECURITY_AUTHENTICATION, authentication); environment.put(Context.SECURITY_AUTHENTICATION, authentication);
} }
} }
public void testConnection(final String providerUrl) throws NamingException { public void testConnection(final String providerUrl) throws NamingException {
try { try {
createBindContext(providerUrl); createBindContext(providerUrl);
s_logger.info("LDAP Connection was successful"); s_logger.info("LDAP Connection was successful");
} catch (final NamingException e) { } catch (final NamingException e) {
s_logger.warn("LDAP Connection failed"); s_logger.warn("LDAP Connection failed");
s_logger.error(e.getMessage(), e); s_logger.error(e.getMessage(), e);
throw e; throw e;
} }
} }
} }

View File

@ -30,30 +30,30 @@ import com.cloud.utils.component.PluggableService;
public interface LdapManager extends PluggableService { public interface LdapManager extends PluggableService {
LdapConfigurationResponse addConfiguration(String hostname, int port) LdapConfigurationResponse addConfiguration(String hostname, int port)
throws InvalidParameterValueException; throws InvalidParameterValueException;
boolean canAuthenticate(String username, String password); boolean canAuthenticate(String username, String password);
LdapConfigurationResponse createLdapConfigurationResponse( LdapConfigurationResponse createLdapConfigurationResponse(
LdapConfigurationVO configuration); LdapConfigurationVO configuration);
LdapUserResponse createLdapUserResponse(LdapUser user); LdapUserResponse createLdapUserResponse(LdapUser user);
LdapConfigurationResponse deleteConfiguration(String hostname) LdapConfigurationResponse deleteConfiguration(String hostname)
throws InvalidParameterValueException; throws InvalidParameterValueException;
LdapUser getUser(final String username) throws NamingException; LdapUser getUser(final String username) throws NamingException;
List<LdapUser> getUsers() throws NoLdapUserMatchingQueryException; List<LdapUser> getUsers() throws NoLdapUserMatchingQueryException;
List<LdapUser> getUsersInGroup(String groupName) throws NoLdapUserMatchingQueryException; List<LdapUser> getUsersInGroup(String groupName) throws NoLdapUserMatchingQueryException;
boolean isLdapEnabled(); boolean isLdapEnabled();
Pair<List<? extends LdapConfigurationVO>, Integer> listConfigurations( Pair<List<? extends LdapConfigurationVO>, Integer> listConfigurations(
LdapListConfigurationCmd cmd); LdapListConfigurationCmd cmd);
List<LdapUser> searchUsers(String query) List<LdapUser> searchUsers(String query)
throws NoLdapUserMatchingQueryException; throws NoLdapUserMatchingQueryException;
} }

View File

@ -38,205 +38,205 @@ import com.cloud.utils.Pair;
@Component @Component
@Local(value = LdapManager.class) @Local(value = LdapManager.class)
public class LdapManagerImpl implements LdapManager, LdapValidator { public class LdapManagerImpl implements LdapManager, LdapValidator {
private static final Logger s_logger = Logger private static final Logger s_logger = Logger
.getLogger(LdapManagerImpl.class.getName()); .getLogger(LdapManagerImpl.class.getName());
@Inject @Inject
private LdapConfigurationDao _ldapConfigurationDao; private LdapConfigurationDao _ldapConfigurationDao;
@Inject @Inject
private LdapContextFactory _ldapContextFactory; private LdapContextFactory _ldapContextFactory;
@Inject @Inject
private LdapUserManager _ldapUserManager; private LdapUserManager _ldapUserManager;
public LdapManagerImpl() { public LdapManagerImpl() {
super(); super();
} }
public LdapManagerImpl(final LdapConfigurationDao ldapConfigurationDao, public LdapManagerImpl(final LdapConfigurationDao ldapConfigurationDao,
final LdapContextFactory ldapContextFactory, final LdapContextFactory ldapContextFactory,
final LdapUserManager ldapUserManager) { final LdapUserManager ldapUserManager) {
super(); super();
_ldapConfigurationDao = ldapConfigurationDao; _ldapConfigurationDao = ldapConfigurationDao;
_ldapContextFactory = ldapContextFactory; _ldapContextFactory = ldapContextFactory;
_ldapUserManager = ldapUserManager; _ldapUserManager = ldapUserManager;
}
@Override
public LdapConfigurationResponse addConfiguration(final String hostname,
final int port) throws InvalidParameterValueException {
LdapConfigurationVO configuration = _ldapConfigurationDao
.findByHostname(hostname);
if (configuration == null) {
try {
final String providerUrl = "ldap://" + hostname + ":" + port;
_ldapContextFactory.createBindContext(providerUrl);
configuration = new LdapConfigurationVO(hostname, port);
_ldapConfigurationDao.persist(configuration);
s_logger.info("Added new ldap server with hostname: "
+ hostname);
return new LdapConfigurationResponse(hostname, port);
} catch (final NamingException e) {
throw new InvalidParameterValueException(
"Unable to bind to the given LDAP server");
}
} else {
throw new InvalidParameterValueException("Duplicate configuration");
}
}
@Override
public boolean canAuthenticate(final String username, final String password) {
final String escapedUsername = LdapUtils
.escapeLDAPSearchFilter(username);
try {
final LdapUser user = getUser(escapedUsername);
final String principal = user.getPrincipal();
final DirContext context = _ldapContextFactory.createUserContext(
principal, password);
closeContext(context);
return true;
} catch (final NamingException e) {
s_logger.info("Failed to authenticate user: " + username
+ ". incorrect password.");
return false;
}
}
private void closeContext(final DirContext context) {
try {
if (context != null) {
context.close();
}
} catch (final NamingException e) {
s_logger.warn(e.getMessage());
}
}
@Override
public LdapConfigurationResponse createLdapConfigurationResponse(
final LdapConfigurationVO configuration) {
final LdapConfigurationResponse response = new LdapConfigurationResponse();
response.setHostname(configuration.getHostname());
response.setPort(configuration.getPort());
return response;
}
@Override
public LdapUserResponse createLdapUserResponse(final LdapUser user) {
final LdapUserResponse response = new LdapUserResponse();
response.setUsername(user.getUsername());
response.setFirstname(user.getFirstname());
response.setLastname(user.getLastname());
response.setEmail(user.getEmail());
response.setPrincipal(user.getPrincipal());
response.setDomain(user.getDomain());
return response;
}
@Override
public LdapConfigurationResponse deleteConfiguration(final String hostname)
throws InvalidParameterValueException {
final LdapConfigurationVO configuration = _ldapConfigurationDao
.findByHostname(hostname);
if (configuration == null) {
throw new InvalidParameterValueException(
"Cannot find configuration with hostname " + hostname);
} else {
_ldapConfigurationDao.remove(configuration.getId());
s_logger.info("Removed ldap server with hostname: " + hostname);
return new LdapConfigurationResponse(configuration.getHostname(),
configuration.getPort());
}
}
@Override
public List<Class<?>> getCommands() {
final List<Class<?>> cmdList = new ArrayList<Class<?>>();
cmdList.add(LdapUserSearchCmd.class);
cmdList.add(LdapListUsersCmd.class);
cmdList.add(LdapAddConfigurationCmd.class);
cmdList.add(LdapDeleteConfigurationCmd.class);
cmdList.add(LdapListConfigurationCmd.class);
cmdList.add(LdapCreateAccountCmd.class);
cmdList.add(LdapImportUsersCmd.class);
return cmdList;
}
@Override
public LdapUser getUser(final String username) throws NamingException {
DirContext context = null;
try {
context = _ldapContextFactory.createBindContext();
final String escapedUsername = LdapUtils
.escapeLDAPSearchFilter(username);
return _ldapUserManager.getUser(escapedUsername, context);
} catch (final NamingException e) {
throw e;
} finally {
closeContext(context);
}
}
@Override
public List<LdapUser> getUsers() throws NoLdapUserMatchingQueryException {
DirContext context = null;
try {
context = _ldapContextFactory.createBindContext();
return _ldapUserManager.getUsers(context);
} catch (final NamingException e) {
throw new NoLdapUserMatchingQueryException("*");
} finally {
closeContext(context);
}
}
@Override
public List<LdapUser> getUsersInGroup(String groupName) throws NoLdapUserMatchingQueryException {
DirContext context = null;
try {
context = _ldapContextFactory.createBindContext();
return _ldapUserManager.getUsersInGroup(groupName, context);
} catch (final NamingException e) {
throw new NoLdapUserMatchingQueryException("groupName=" + groupName);
} finally {
closeContext(context);
}
} }
@Override @Override
public boolean isLdapEnabled() { public LdapConfigurationResponse addConfiguration(final String hostname,
return listConfigurations(new LdapListConfigurationCmd(this)).second() > 0; final int port) throws InvalidParameterValueException {
} LdapConfigurationVO configuration = _ldapConfigurationDao
.findByHostname(hostname);
if (configuration == null) {
try {
final String providerUrl = "ldap://" + hostname + ":" + port;
_ldapContextFactory.createBindContext(providerUrl);
configuration = new LdapConfigurationVO(hostname, port);
_ldapConfigurationDao.persist(configuration);
s_logger.info("Added new ldap server with hostname: "
+ hostname);
return new LdapConfigurationResponse(hostname, port);
} catch (final NamingException e) {
throw new InvalidParameterValueException(
"Unable to bind to the given LDAP server");
}
} else {
throw new InvalidParameterValueException("Duplicate configuration");
}
}
@Override @Override
public Pair<List<? extends LdapConfigurationVO>, Integer> listConfigurations( public boolean canAuthenticate(final String username, final String password) {
final LdapListConfigurationCmd cmd) { final String escapedUsername = LdapUtils
final String hostname = cmd.getHostname(); .escapeLDAPSearchFilter(username);
final int port = cmd.getPort(); try {
final Pair<List<LdapConfigurationVO>, Integer> result = _ldapConfigurationDao final LdapUser user = getUser(escapedUsername);
.searchConfigurations(hostname, port); final String principal = user.getPrincipal();
return new Pair<List<? extends LdapConfigurationVO>, Integer>( final DirContext context = _ldapContextFactory.createUserContext(
result.first(), result.second()); principal, password);
} closeContext(context);
return true;
} catch (final NamingException e) {
s_logger.info("Failed to authenticate user: " + username
+ ". incorrect password.");
return false;
}
}
@Override private void closeContext(final DirContext context) {
public List<LdapUser> searchUsers(final String username) try {
throws NoLdapUserMatchingQueryException { if (context != null) {
DirContext context = null; context.close();
try { }
context = _ldapContextFactory.createBindContext(); } catch (final NamingException e) {
final String escapedUsername = LdapUtils s_logger.warn(e.getMessage());
.escapeLDAPSearchFilter(username); }
return _ldapUserManager.getUsers("*" + escapedUsername + "*", }
context);
} catch (final NamingException e) { @Override
throw new NoLdapUserMatchingQueryException(username); public LdapConfigurationResponse createLdapConfigurationResponse(
} finally { final LdapConfigurationVO configuration) {
closeContext(context); final LdapConfigurationResponse response = new LdapConfigurationResponse();
} response.setHostname(configuration.getHostname());
} response.setPort(configuration.getPort());
return response;
}
@Override
public LdapUserResponse createLdapUserResponse(final LdapUser user) {
final LdapUserResponse response = new LdapUserResponse();
response.setUsername(user.getUsername());
response.setFirstname(user.getFirstname());
response.setLastname(user.getLastname());
response.setEmail(user.getEmail());
response.setPrincipal(user.getPrincipal());
response.setDomain(user.getDomain());
return response;
}
@Override
public LdapConfigurationResponse deleteConfiguration(final String hostname)
throws InvalidParameterValueException {
final LdapConfigurationVO configuration = _ldapConfigurationDao
.findByHostname(hostname);
if (configuration == null) {
throw new InvalidParameterValueException(
"Cannot find configuration with hostname " + hostname);
} else {
_ldapConfigurationDao.remove(configuration.getId());
s_logger.info("Removed ldap server with hostname: " + hostname);
return new LdapConfigurationResponse(configuration.getHostname(),
configuration.getPort());
}
}
@Override
public List<Class<?>> getCommands() {
final List<Class<?>> cmdList = new ArrayList<Class<?>>();
cmdList.add(LdapUserSearchCmd.class);
cmdList.add(LdapListUsersCmd.class);
cmdList.add(LdapAddConfigurationCmd.class);
cmdList.add(LdapDeleteConfigurationCmd.class);
cmdList.add(LdapListConfigurationCmd.class);
cmdList.add(LdapCreateAccountCmd.class);
cmdList.add(LdapImportUsersCmd.class);
return cmdList;
}
@Override
public LdapUser getUser(final String username) throws NamingException {
DirContext context = null;
try {
context = _ldapContextFactory.createBindContext();
final String escapedUsername = LdapUtils
.escapeLDAPSearchFilter(username);
return _ldapUserManager.getUser(escapedUsername, context);
} catch (final NamingException e) {
throw e;
} finally {
closeContext(context);
}
}
@Override
public List<LdapUser> getUsers() throws NoLdapUserMatchingQueryException {
DirContext context = null;
try {
context = _ldapContextFactory.createBindContext();
return _ldapUserManager.getUsers(context);
} catch (final NamingException e) {
throw new NoLdapUserMatchingQueryException("*");
} finally {
closeContext(context);
}
}
@Override
public List<LdapUser> getUsersInGroup(String groupName) throws NoLdapUserMatchingQueryException {
DirContext context = null;
try {
context = _ldapContextFactory.createBindContext();
return _ldapUserManager.getUsersInGroup(groupName, context);
} catch (final NamingException e) {
throw new NoLdapUserMatchingQueryException("groupName=" + groupName);
} finally {
closeContext(context);
}
}
@Override
public boolean isLdapEnabled() {
return listConfigurations(new LdapListConfigurationCmd(this)).second() > 0;
}
@Override
public Pair<List<? extends LdapConfigurationVO>, Integer> listConfigurations(
final LdapListConfigurationCmd cmd) {
final String hostname = cmd.getHostname();
final int port = cmd.getPort();
final Pair<List<LdapConfigurationVO>, Integer> result = _ldapConfigurationDao
.searchConfigurations(hostname, port);
return new Pair<List<? extends LdapConfigurationVO>, Integer>(
result.first(), result.second());
}
@Override
public List<LdapUser> searchUsers(final String username)
throws NoLdapUserMatchingQueryException {
DirContext context = null;
try {
context = _ldapContextFactory.createBindContext();
final String escapedUsername = LdapUtils
.escapeLDAPSearchFilter(username);
return _ldapUserManager.getUsers("*" + escapedUsername + "*",
context);
} catch (final NamingException e) {
throw new NoLdapUserMatchingQueryException(username);
} finally {
closeContext(context);
}
}
} }

View File

@ -17,65 +17,65 @@
package org.apache.cloudstack.ldap; package org.apache.cloudstack.ldap;
public class LdapUser implements Comparable<LdapUser> { public class LdapUser implements Comparable<LdapUser> {
private final String email; private final String email;
private final String principal; private final String principal;
private final String firstname; private final String firstname;
private final String lastname; private final String lastname;
private final String username; private final String username;
private final String domain; private final String domain;
public LdapUser(final String username, final String email, final String firstname, final String lastname, final String principal, String domain) { public LdapUser(final String username, final String email, final String firstname, final String lastname, final String principal, String domain) {
this.username = username; this.username = username;
this.email = email; this.email = email;
this.firstname = firstname; this.firstname = firstname;
this.lastname = lastname; this.lastname = lastname;
this.principal = principal; this.principal = principal;
this.domain = domain; this.domain = domain;
}
@Override
public int compareTo(final LdapUser other) {
return getUsername().compareTo(other.getUsername());
}
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other instanceof LdapUser) {
final LdapUser otherLdapUser = (LdapUser) other;
return getUsername().equals(otherLdapUser.getUsername());
}
return false;
}
public String getEmail() {
return email;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public String getPrincipal() {
return principal;
}
public String getUsername() {
return username;
}
public String getDomain() {
return domain;
} }
@Override @Override
public int hashCode() { public int compareTo(final LdapUser other) {
return getUsername().hashCode(); return getUsername().compareTo(other.getUsername());
} }
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other instanceof LdapUser) {
final LdapUser otherLdapUser = (LdapUser) other;
return getUsername().equals(otherLdapUser.getUsername());
}
return false;
}
public String getEmail() {
return email;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public String getPrincipal() {
return principal;
}
public String getUsername() {
return username;
}
public String getDomain() {
return domain;
}
@Override
public int hashCode() {
return getUsername().hashCode();
}
} }

View File

@ -34,153 +34,153 @@ public class LdapUserManager {
} }
public LdapUserManager(final LdapConfiguration ldapConfiguration) { public LdapUserManager(final LdapConfiguration ldapConfiguration) {
_ldapConfiguration = ldapConfiguration; _ldapConfiguration = ldapConfiguration;
} }
private LdapUser createUser(final SearchResult result) throws NamingException { private LdapUser createUser(final SearchResult result) throws NamingException {
final Attributes attributes = result.getAttributes(); final Attributes attributes = result.getAttributes();
final String username = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getUsernameAttribute()); final String username = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getUsernameAttribute());
final String email = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getEmailAttribute()); final String email = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getEmailAttribute());
final String firstname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getFirstnameAttribute()); final String firstname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getFirstnameAttribute());
final String lastname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getLastnameAttribute()); final String lastname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getLastnameAttribute());
final String principal = result.getNameInNamespace(); final String principal = result.getNameInNamespace();
String domain = principal.replace("cn="+LdapUtils.getAttributeValue(attributes,_ldapConfiguration.getCommonNameAttribute())+",", ""); String domain = principal.replace("cn="+LdapUtils.getAttributeValue(attributes,_ldapConfiguration.getCommonNameAttribute())+",", "");
domain = domain.replace(","+_ldapConfiguration.getBaseDn(), ""); domain = domain.replace(","+_ldapConfiguration.getBaseDn(), "");
domain = domain.replace("ou=",""); domain = domain.replace("ou=","");
return new LdapUser(username, email, firstname, lastname, principal, domain); return new LdapUser(username, email, firstname, lastname, principal, domain);
} }
private String generateSearchFilter(final String username) { private String generateSearchFilter(final String username) {
final StringBuilder userObjectFilter = new StringBuilder(); final StringBuilder userObjectFilter = new StringBuilder();
userObjectFilter.append("(objectClass="); userObjectFilter.append("(objectClass=");
userObjectFilter.append(_ldapConfiguration.getUserObject()); userObjectFilter.append(_ldapConfiguration.getUserObject());
userObjectFilter.append(")"); userObjectFilter.append(")");
final StringBuilder usernameFilter = new StringBuilder(); final StringBuilder usernameFilter = new StringBuilder();
usernameFilter.append("("); usernameFilter.append("(");
usernameFilter.append(_ldapConfiguration.getUsernameAttribute()); usernameFilter.append(_ldapConfiguration.getUsernameAttribute());
usernameFilter.append("="); usernameFilter.append("=");
usernameFilter.append((username == null ? "*" : username)); usernameFilter.append((username == null ? "*" : username));
usernameFilter.append(")"); usernameFilter.append(")");
final StringBuilder memberOfFilter = new StringBuilder(); final StringBuilder memberOfFilter = new StringBuilder();
if (_ldapConfiguration.getSearchGroupPrinciple() != null) { if (_ldapConfiguration.getSearchGroupPrinciple() != null) {
memberOfFilter.append("(memberof="); memberOfFilter.append("(memberof=");
memberOfFilter.append(_ldapConfiguration.getSearchGroupPrinciple()); memberOfFilter.append(_ldapConfiguration.getSearchGroupPrinciple());
memberOfFilter.append(")"); memberOfFilter.append(")");
} }
final StringBuilder result = new StringBuilder(); final StringBuilder result = new StringBuilder();
result.append("(&"); result.append("(&");
result.append(userObjectFilter); result.append(userObjectFilter);
result.append(usernameFilter); result.append(usernameFilter);
result.append(memberOfFilter); result.append(memberOfFilter);
result.append(")"); result.append(")");
return result.toString(); return result.toString();
} }
private String generateGroupSearchFilter(final String groupName) { private String generateGroupSearchFilter(final String groupName) {
final StringBuilder groupObjectFilter = new StringBuilder(); final StringBuilder groupObjectFilter = new StringBuilder();
groupObjectFilter.append("(objectClass="); groupObjectFilter.append("(objectClass=");
groupObjectFilter.append(_ldapConfiguration.getGroupObject()); groupObjectFilter.append(_ldapConfiguration.getGroupObject());
groupObjectFilter.append(")"); groupObjectFilter.append(")");
final StringBuilder groupNameFilter = new StringBuilder(); final StringBuilder groupNameFilter = new StringBuilder();
groupNameFilter.append("("); groupNameFilter.append("(");
groupNameFilter.append(_ldapConfiguration.getCommonNameAttribute()); groupNameFilter.append(_ldapConfiguration.getCommonNameAttribute());
groupNameFilter.append("="); groupNameFilter.append("=");
groupNameFilter.append((groupName == null ? "*" : groupName)); groupNameFilter.append((groupName == null ? "*" : groupName));
groupNameFilter.append(")"); groupNameFilter.append(")");
final StringBuilder result = new StringBuilder(); final StringBuilder result = new StringBuilder();
result.append("(&"); result.append("(&");
result.append(groupObjectFilter); result.append(groupObjectFilter);
result.append(groupNameFilter); result.append(groupNameFilter);
result.append(")"); result.append(")");
return result.toString(); return result.toString();
} }
public LdapUser getUser(final String username, final DirContext context) throws NamingException { public LdapUser getUser(final String username, final DirContext context) throws NamingException {
final NamingEnumeration<SearchResult> result = searchUsers(username, context); final NamingEnumeration<SearchResult> result = searchUsers(username, context);
if (result.hasMoreElements()) { if (result.hasMoreElements()) {
return createUser(result.nextElement()); return createUser(result.nextElement());
} else { } else {
throw new NamingException("No user found for username " + username); throw new NamingException("No user found for username " + username);
} }
} }
public List<LdapUser> getUsers(final DirContext context) throws NamingException { public List<LdapUser> getUsers(final DirContext context) throws NamingException {
return getUsers(null, context); return getUsers(null, context);
} }
public List<LdapUser> getUsers(final String username, final DirContext context) throws NamingException { public List<LdapUser> getUsers(final String username, final DirContext context) throws NamingException {
final NamingEnumeration<SearchResult> results = searchUsers(username, context); final NamingEnumeration<SearchResult> results = searchUsers(username, context);
final List<LdapUser> users = new ArrayList<LdapUser>(); final List<LdapUser> users = new ArrayList<LdapUser>();
while (results.hasMoreElements()) { while (results.hasMoreElements()) {
final SearchResult result = results.nextElement(); final SearchResult result = results.nextElement();
users.add(createUser(result)); users.add(createUser(result));
} }
Collections.sort(users); Collections.sort(users);
return users; return users;
} }
public List<LdapUser> getUsersInGroup(String groupName, DirContext context) throws NamingException { public List<LdapUser> getUsersInGroup(String groupName, DirContext context) throws NamingException {
String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute(); String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
final SearchControls controls = new SearchControls(); final SearchControls controls = new SearchControls();
controls.setSearchScope(_ldapConfiguration.getScope()); controls.setSearchScope(_ldapConfiguration.getScope());
controls.setReturningAttributes(new String[]{attributeName}); controls.setReturningAttributes(new String[] {attributeName});
NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(), generateGroupSearchFilter(groupName), controls); NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(), generateGroupSearchFilter(groupName), controls);
final List<LdapUser> users = new ArrayList<LdapUser>(); final List<LdapUser> users = new ArrayList<LdapUser>();
//Expecting only one result which has all the users //Expecting only one result which has all the users
if (result.hasMoreElements()) { if (result.hasMoreElements()) {
Attribute attribute = result.nextElement().getAttributes().get(attributeName); Attribute attribute = result.nextElement().getAttributes().get(attributeName);
NamingEnumeration<?> values = attribute.getAll(); NamingEnumeration<?> values = attribute.getAll();
while (values.hasMoreElements()) { while (values.hasMoreElements()) {
String userdn = String.valueOf(values.nextElement()); String userdn = String.valueOf(values.nextElement());
users.add(getUserForDn(userdn,context)); users.add(getUserForDn(userdn,context));
} }
} }
Collections.sort(users); Collections.sort(users);
return users; return users;
} }
private LdapUser getUserForDn(String userdn, DirContext context) throws NamingException { private LdapUser getUserForDn(String userdn, DirContext context) throws NamingException {
final SearchControls controls = new SearchControls(); final SearchControls controls = new SearchControls();
controls.setSearchScope(_ldapConfiguration.getScope()); controls.setSearchScope(_ldapConfiguration.getScope());
controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());
NamingEnumeration<SearchResult> result = context.search(userdn, "(objectClass="+_ldapConfiguration.getUserObject()+")", controls); NamingEnumeration<SearchResult> result = context.search(userdn, "(objectClass="+_ldapConfiguration.getUserObject()+")", controls);
if (result.hasMoreElements()) { if (result.hasMoreElements()) {
return createUser(result.nextElement()); return createUser(result.nextElement());
} else { } else {
throw new NamingException("No user found for dn " + userdn); throw new NamingException("No user found for dn " + userdn);
} }
} }
public NamingEnumeration<SearchResult> searchUsers(final DirContext context) throws NamingException { public NamingEnumeration<SearchResult> searchUsers(final DirContext context) throws NamingException {
return searchUsers(null, context); return searchUsers(null, context);
} }
public NamingEnumeration<SearchResult> searchUsers(final String username, final DirContext context) throws NamingException { public NamingEnumeration<SearchResult> searchUsers(final String username, final DirContext context) throws NamingException {
final SearchControls controls = new SearchControls(); final SearchControls controls = new SearchControls();
controls.setSearchScope(_ldapConfiguration.getScope()); controls.setSearchScope(_ldapConfiguration.getScope());
controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());
return context.search(_ldapConfiguration.getBaseDn(), generateSearchFilter(username), controls); return context.search(_ldapConfiguration.getBaseDn(), generateSearchFilter(username), controls);
} }
} }

View File

@ -21,42 +21,42 @@ import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes; import javax.naming.directory.Attributes;
public final class LdapUtils { public final class LdapUtils {
public static String escapeLDAPSearchFilter(final String filter) { public static String escapeLDAPSearchFilter(final String filter) {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
for (final char character : filter.toCharArray()) { for (final char character : filter.toCharArray()) {
switch (character) { switch (character) {
case '\\': case '\\':
sb.append("\\5c"); sb.append("\\5c");
break; break;
case '*': case '*':
sb.append("\\2a"); sb.append("\\2a");
break; break;
case '(': case '(':
sb.append("\\28"); sb.append("\\28");
break; break;
case ')': case ')':
sb.append("\\29"); sb.append("\\29");
break; break;
case '\u0000': case '\u0000':
sb.append("\\00"); sb.append("\\00");
break; break;
default: default:
sb.append(character); sb.append(character);
} }
} }
return sb.toString(); return sb.toString();
} }
public static String getAttributeValue(final Attributes attributes, public static String getAttributeValue(final Attributes attributes,
final String attributeName) throws NamingException { final String attributeName) throws NamingException {
final Attribute attribute = attributes.get(attributeName); final Attribute attribute = attributes.get(attributeName);
if (attribute != null) { if (attribute != null) {
final Object value = attribute.get(); final Object value = attribute.get();
return String.valueOf(value); return String.valueOf(value);
} }
return null; return null;
} }
private LdapUtils() { private LdapUtils() {
} }
} }

View File

@ -17,16 +17,16 @@
package org.apache.cloudstack.ldap; package org.apache.cloudstack.ldap;
public class NoLdapUserMatchingQueryException extends Exception { public class NoLdapUserMatchingQueryException extends Exception {
private static final long serialVersionUID = 7124360347208388174L; private static final long serialVersionUID = 7124360347208388174L;
private final String query; private final String query;
public NoLdapUserMatchingQueryException(final String query) { public NoLdapUserMatchingQueryException(final String query) {
super("No users matching: " + query); super("No users matching: " + query);
this.query = query; this.query = query;
} }
public String getQuery() { public String getQuery() {
return query; return query;
} }
} }

View File

@ -17,15 +17,15 @@
package org.apache.cloudstack.ldap; package org.apache.cloudstack.ldap;
public class NoSuchLdapUserException extends Exception { public class NoSuchLdapUserException extends Exception {
private static final long serialVersionUID = 6782938919658010900L; private static final long serialVersionUID = 6782938919658010900L;
private final String username; private final String username;
public NoSuchLdapUserException(final String username) { public NoSuchLdapUserException(final String username) {
super("No such user: " + username); super("No such user: " + username);
this.username = username; this.username = username;
} }
public String getUsername() { public String getUsername() {
return username; return username;
} }
} }

View File

@ -24,9 +24,9 @@ import com.cloud.utils.Pair;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
public interface LdapConfigurationDao extends public interface LdapConfigurationDao extends
GenericDao<LdapConfigurationVO, Long> { GenericDao<LdapConfigurationVO, Long> {
LdapConfigurationVO findByHostname(String hostname); LdapConfigurationVO findByHostname(String hostname);
Pair<List<LdapConfigurationVO>, Integer> searchConfigurations( Pair<List<LdapConfigurationVO>, Integer> searchConfigurations(
String hostname, int port); String hostname, int port);
} }

View File

@ -32,41 +32,41 @@ import com.cloud.utils.db.SearchCriteria.Op;
@Component @Component
@Local(value = { LdapConfigurationDao.class }) @Local(value = { LdapConfigurationDao.class })
public class LdapConfigurationDaoImpl extends public class LdapConfigurationDaoImpl extends
GenericDaoBase<LdapConfigurationVO, Long> implements GenericDaoBase<LdapConfigurationVO, Long> implements
LdapConfigurationDao { LdapConfigurationDao {
private final SearchBuilder<LdapConfigurationVO> hostnameSearch; private final SearchBuilder<LdapConfigurationVO> hostnameSearch;
private final SearchBuilder<LdapConfigurationVO> listAllConfigurationsSearch; private final SearchBuilder<LdapConfigurationVO> listAllConfigurationsSearch;
public LdapConfigurationDaoImpl() { public LdapConfigurationDaoImpl() {
super(); super();
hostnameSearch = createSearchBuilder(); hostnameSearch = createSearchBuilder();
hostnameSearch.and("hostname", hostnameSearch.entity().getHostname(), hostnameSearch.and("hostname", hostnameSearch.entity().getHostname(),
SearchCriteria.Op.EQ); SearchCriteria.Op.EQ);
hostnameSearch.done(); hostnameSearch.done();
listAllConfigurationsSearch = createSearchBuilder(); listAllConfigurationsSearch = createSearchBuilder();
listAllConfigurationsSearch.and("hostname", listAllConfigurationsSearch listAllConfigurationsSearch.and("hostname", listAllConfigurationsSearch
.entity().getHostname(), Op.EQ); .entity().getHostname(), Op.EQ);
listAllConfigurationsSearch.and("port", listAllConfigurationsSearch listAllConfigurationsSearch.and("port", listAllConfigurationsSearch
.entity().getPort(), Op.EQ); .entity().getPort(), Op.EQ);
listAllConfigurationsSearch.done(); listAllConfigurationsSearch.done();
} }
@Override @Override
public LdapConfigurationVO findByHostname(final String hostname) { public LdapConfigurationVO findByHostname(final String hostname) {
final SearchCriteria<LdapConfigurationVO> sc = hostnameSearch.create(); final SearchCriteria<LdapConfigurationVO> sc = hostnameSearch.create();
sc.setParameters("hostname", hostname); sc.setParameters("hostname", hostname);
return findOneBy(sc); return findOneBy(sc);
} }
@Override @Override
public Pair<List<LdapConfigurationVO>, Integer> searchConfigurations( public Pair<List<LdapConfigurationVO>, Integer> searchConfigurations(
final String hostname, final int port) { final String hostname, final int port) {
final SearchCriteria<LdapConfigurationVO> sc = listAllConfigurationsSearch final SearchCriteria<LdapConfigurationVO> sc = listAllConfigurationsSearch
.create(); .create();
if (hostname != null) { if (hostname != null) {
sc.setParameters("hostname", hostname); sc.setParameters("hostname", hostname);
} }
return searchAndCount(sc, null); return searchAndCount(sc, null);
} }
} }