Skip to content

The Unified and Autonomous Development Platform

Refactor ldap authenticator

Robin Shend9c6ca92a461
diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultGroupManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultGroupManager.java
index cd98e457fb..eeeee15838 100644
--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultGroupManager.java
+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultGroupManager.java
@@ -19,6 +19,7 @@ import io.onedev.server.model.Project;
import io.onedev.server.model.support.BranchProtection;
import io.onedev.server.model.support.TagProtection;
import io.onedev.server.model.support.administration.SecuritySetting;
+import io.onedev.server.model.support.administration.authenticator.Authenticator;
import io.onedev.server.persistence.annotation.Sessional;
import io.onedev.server.persistence.annotation.Transactional;
import io.onedev.server.persistence.dao.AbstractEntityManager;
@@ -57,6 +58,12 @@ public class DefaultGroupManager extends AbstractEntityManager<Group> implements
protection.onRenameGroup(oldName, group.getName());
}
+ Authenticator authenticator = settingManager.getAuthenticator();
+ if (authenticator != null) {
+ authenticator.onRenameGroup(oldName, group.getName());
+ settingManager.saveAuthenticator(authenticator);
+ }
+
issueFieldManager.onRenameGroup(oldName, group.getName());
settingManager.getIssueSetting().onRenameGroup(oldName, group.getName());
settingManager.getSecuritySetting().onRenameGroup(oldName, group.getName());
@@ -80,6 +87,10 @@ public class DefaultGroupManager extends AbstractEntityManager<Group> implements
usage.add(settingManager.getIssueSetting().onDeleteGroup(group.getName()).prefix("administration"));
+ Authenticator authenticator = settingManager.getAuthenticator();
+ if (authenticator != null)
+ usage.add(authenticator.onDeleteGroup(group.getName()).prefix("administration"));
+
usage.add(settingManager.getSecuritySetting().onDeleteGroup(group.getName()).prefix("administration"));
usage.checkInUse("Group '" + group.getName() + "'");
diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultSshKeyManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultSshKeyManager.java
index 2ea1bd90f7..9f342d416f 100644
--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultSshKeyManager.java
+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultSshKeyManager.java
@@ -49,30 +49,29 @@ public class DefaultSshKeyManager extends AbstractEntityManager<SshKey> implemen
public void syncUserKeys(User user, Collection<SshKey> keys) {
Collection<SshKey> currentKeys = user.getSshKeys();
- Map<String, SshKey> currentKeysMap = sshPublicKeysToMap(currentKeys);
- Map<String, SshKey> authKeysMap = sshPublicKeysToMap(keys);
- MapDifference<String, SshKey> diff = Maps.difference(currentKeysMap, authKeysMap);
+ Map<String, SshKey> currentKeysMap = keysToMap(currentKeys);
+ Map<String, SshKey> keysMap = keysToMap(keys);
+ MapDifference<String, SshKey> diff = Maps.difference(currentKeysMap, keysMap);
- // remove keys not delivered by authentication
diff.entriesOnlyOnLeft().values().forEach((key) -> delete(key));
- // add keys from authorization
diff.entriesOnlyOnRight().values().forEach((key) -> {
-
- if (findByDigest(key.getDigest()) != null) {
+ if (findByDigest(key.getDigest()) == null) {
key.setDate(new Date());
key.setOwner(user);
save(key);
} else {
- logger.warn("SSH public key provided by auth is already in use", key.getDigest());
+ logger.warn("SSH key is already in use (digest: {})", key.getDigest());
}
-
});
+
}
- private Map<String, SshKey> sshPublicKeysToMap(Collection<SshKey> keys) {
+ private Map<String, SshKey> keysToMap(Collection<SshKey> sshKeys) {
Map<String, SshKey> keysMap = new HashMap<String, SshKey>();
- keys.forEach((key) -> keysMap.put(key.getDigest(), key));
+ // use content as map key as we want to update key if key comment is changed
+ sshKeys.forEach((key) -> keysMap.put(key.getContent(), key));
return keysMap;
}
+
}
diff --git a/server-core/src/main/java/io/onedev/server/model/SshKey.java b/server-core/src/main/java/io/onedev/server/model/SshKey.java
index a395b36444..3eb3beea77 100644
--- a/server-core/src/main/java/io/onedev/server/model/SshKey.java
+++ b/server-core/src/main/java/io/onedev/server/model/SshKey.java
@@ -2,6 +2,7 @@ package io.onedev.server.model;
import java.util.Date;
+import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
@@ -15,28 +16,25 @@ import javax.validation.ConstraintValidatorContext;
import org.apache.sshd.common.config.keys.KeyUtils;
import org.hibernate.validator.constraints.NotEmpty;
+import io.onedev.commons.utils.StringUtils;
import io.onedev.server.ssh.SshKeyUtils;
import io.onedev.server.util.validation.Validatable;
import io.onedev.server.util.validation.annotation.ClassValidating;
import io.onedev.server.web.editable.annotation.Editable;
import io.onedev.server.web.editable.annotation.Multiline;
+import io.onedev.server.web.editable.annotation.OmitName;
@Editable
@Entity
@Table(
- indexes={@Index(columnList="o_owner_id"), @Index(columnList="name"), @Index(columnList="digest")},
- uniqueConstraints={
- @UniqueConstraint(columnNames={"o_owner_id", "name"}),
- @UniqueConstraint(columnNames={"digest"})}
+ indexes={@Index(columnList="o_owner_id"), @Index(columnList="digest")},
+ uniqueConstraints={@UniqueConstraint(columnNames={"digest"})}
)
@ClassValidating
public class SshKey extends AbstractEntity implements Validatable {
private static final long serialVersionUID = 1L;
- @Column(nullable=false)
- private String name;
-
@Column(nullable=false, length = 5000)
private String content;
@@ -50,20 +48,10 @@ public class SshKey extends AbstractEntity implements Validatable {
@JoinColumn(nullable=false)
private User owner;
- @Editable(description="Specify a name to identify the key")
- @NotEmpty
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Editable(name = "Key", description="Provide a SSH public key. Begins with 'ssh-rsa', 'ssh-ed25519', "
- + "'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', or 'ecdsa-sha2-nistp521'")
+ @Editable(name = "Key", description="Provide a OpenSSH public key. Normally begins with 'ssh-rsa'")
@NotEmpty
@Multiline
+ @OmitName
public String getContent() {
return content;
}
@@ -96,6 +84,15 @@ public class SshKey extends AbstractEntity implements Validatable {
this.createdAt = createdAt;
}
+ @Nullable
+ public String getComment() {
+ String tempStr = StringUtils.substringAfter(content, " ");
+ if (tempStr.indexOf(' ') != -1)
+ return StringUtils.substringAfter(tempStr, " ");
+ else
+ return null;
+ }
+
@Override
public boolean isValid(ConstraintValidatorContext context) {
if (content == null) {
@@ -106,7 +103,7 @@ public class SshKey extends AbstractEntity implements Validatable {
return true;
} catch (Exception exception) {
context.disableDefaultConstraintViolation();
- context.buildConstraintViolationWithTemplate("Invalid SSH public key")
+ context.buildConstraintViolationWithTemplate("A valid OpenSSH public key is expected")
.addPropertyNode("content").addConstraintViolation();
return false;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/User.java b/server-core/src/main/java/io/onedev/server/model/User.java
index 30e953547f..42fdf51c4a 100644
--- a/server-core/src/main/java/io/onedev/server/model/User.java
+++ b/server-core/src/main/java/io/onedev/server/model/User.java
@@ -523,4 +523,14 @@ public class User extends AbstractEntity implements AuthenticationInfo {
return false;
}
}
+
+ public boolean isMembershipExternalManaged() {
+ if (isExternalManaged()) {
+ Authenticator authenticator = OneDev.getInstance(SettingManager.class).getAuthenticator();
+ return authenticator != null && authenticator.isManagingMemberships();
+ } else {
+ return false;
+ }
+ }
+
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/Authenticated.java b/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/Authenticated.java
index c56d3198b1..ad58ee9af6 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/Authenticated.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/Authenticated.java
@@ -14,20 +14,14 @@ public class Authenticated {
private final Collection<String> groupNames;
- private final Collection<SshKey> sshPublicKeys;
+ private final Collection<SshKey> sshKeys;
- public Authenticated(String email, @Nullable String fullName, Collection<String> groupNames) {
- this(email, fullName, groupNames, null);
- }
-
- public Authenticated(
- String email, @Nullable String fullName,
- Collection<String> groupNames, @Nullable Collection<SshKey> sshPublicKeys
- ) {
+ public Authenticated(String email, @Nullable String fullName,
+ @Nullable Collection<String> groupNames, @Nullable Collection<SshKey> sshKeys) {
this.email = email;
this.fullName = fullName;
this.groupNames = groupNames;
- this.sshPublicKeys = sshPublicKeys;
+ this.sshKeys = sshKeys;
}
@Nullable
@@ -39,13 +33,14 @@ public class Authenticated {
return email;
}
+ @Nullable
public Collection<String> getGroupNames() {
return groupNames;
}
@Nullable
- public Collection<SshKey> getSSHPublicKeys() {
- return sshPublicKeys;
+ public Collection<SshKey> getSshKeys() {
+ return sshKeys;
}
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/Authenticator.java b/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/Authenticator.java
index bd5f7fde87..fe7decbf0c 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/Authenticator.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/Authenticator.java
@@ -5,13 +5,18 @@ import java.io.Serializable;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
+import io.onedev.server.util.usage.Usage;
import io.onedev.server.web.editable.annotation.Editable;
+import io.onedev.server.web.editable.annotation.GroupChoice;
+import io.onedev.server.web.editable.annotation.NameOfEmptyValue;
@Editable
public abstract class Authenticator implements Serializable {
private static final long serialVersionUID = 1L;
+ private String defaultGroup;
+
private int timeout = 300;
@Editable(order=10000, description="Specify network timeout in seconds when authenticate through this system")
@@ -23,10 +28,34 @@ public abstract class Authenticator implements Serializable {
this.timeout = timeout;
}
+ @Editable(order=20000, description="Optionally add newly authenticated user to specified group if membership "
+ + "information is not retrieved")
+ @GroupChoice
+ @NameOfEmptyValue("No default group")
+ public String getDefaultGroup() {
+ return defaultGroup;
+ }
+
+ public void setDefaultGroup(String defaultGroup) {
+ this.defaultGroup = defaultGroup;
+ }
+
+ public void onRenameGroup(String oldName, String newName) {
+ if (oldName.equals(defaultGroup))
+ defaultGroup = newName;
+ }
+
+ public Usage onDeleteGroup(String groupName) {
+ Usage usage = new Usage();
+ if (groupName.equals(defaultGroup))
+ usage.add("default group");
+ return usage.prefix("external authenticator");
+ }
+
public abstract Authenticated authenticate(UsernamePasswordToken token) throws AuthenticationException;
public abstract boolean isManagingMemberships();
-
+
public abstract boolean isManagingSshKeys();
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/ActiveDirectoryAuthenticator.java b/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/ActiveDirectoryAuthenticator.java
index c599c8d9d7..d1af8a2eba 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/ActiveDirectoryAuthenticator.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/ActiveDirectoryAuthenticator.java
@@ -89,5 +89,5 @@ public class ActiveDirectoryAuthenticator extends LdapAuthenticator {
return new DoNotRetrieveGroups();
}
}
-
+
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/LdapAuthenticator.java b/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/LdapAuthenticator.java
index 4555412fd5..80473f6d05 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/LdapAuthenticator.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/LdapAuthenticator.java
@@ -9,6 +9,7 @@ import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
+import javax.annotation.Nullable;
import javax.naming.AuthenticationException;
import javax.naming.CompositeName;
import javax.naming.Context;
@@ -38,6 +39,7 @@ import io.onedev.server.model.SshKey;
import io.onedev.server.model.support.administration.authenticator.Authenticated;
import io.onedev.server.model.support.administration.authenticator.Authenticator;
import io.onedev.server.ssh.SshKeyUtils;
+import io.onedev.server.util.CollectionUtils;
import io.onedev.server.web.editable.annotation.Editable;
import io.onedev.server.web.editable.annotation.Password;
@@ -149,9 +151,9 @@ public class LdapAuthenticator extends Authenticator {
this.userEmailAttribute = userEmailAttribute;
}
- @Editable(order=850, description=""
- + "Specifies name of the attributes inside the user LDAP entry whose values will be taken as user "
- + "SSH public keys. If this field is set SSH public keys are managed by LDAP only")
+ @Editable(name="User SSH Key Attribute", order=850, description=""
+ + "Optionally specify name of the attribute inside the user LDAP entry whose values will be taken as user "
+ + "SSH keys. SSH keys will be managed by LDAP only if this field is set")
public String getUserSshKeyAttribute() {
return userSshKeyAttribute;
}
@@ -161,9 +163,9 @@ public class LdapAuthenticator extends Authenticator {
}
@Editable(order=900, description="Specify the strategy to retrieve group membership information. "
- + "To give appropriate permissions to a LDAP group, a OneDev group with same name "
- + "should be defined. Use strategy <tt>Do Not Retrieve Groups</tt> if you want to manage "
- + "group memberships at OneDev side")
+ + "To give appropriate permissions to a LDAP group, a OneDev group with same name should "
+ + "be defined. Use strategy <tt>Do Not Retrieve Groups</tt> if you want to manage group "
+ + "memberships at OneDev side")
@NotNull(message="may not be empty")
public GroupRetrieval getGroupRetrieval() {
return groupRetrieval;
@@ -177,7 +179,8 @@ public class LdapAuthenticator extends Authenticator {
public Authenticated authenticate(UsernamePasswordToken token) {
String fullName = null;
String email = null;
- Collection<String> groupNames = new HashSet<>();
+ Collection<String> groupNames = null;
+ Collection<SshKey> sshKeys = null;
Name userSearchBase;
try {
@@ -195,10 +198,8 @@ public class LdapAuthenticator extends Authenticator {
if (getUserFullNameAttribute() != null)
attributeNames.add(getUserFullNameAttribute());
- String userSSHPublicKey = getUserSshKeyAttribute();
-
- if (userSSHPublicKey != null)
- attributeNames.add(userSSHPublicKey);
+ if (getUserSshKeyAttribute() != null)
+ attributeNames.add(getUserSshKeyAttribute());
attributeNames.add(getUserEmailAttribute());
@@ -269,111 +270,28 @@ public class LdapAuthenticator extends Authenticator {
}
Attributes searchResultAttributes = searchResult.getAttributes();
+
if (searchResultAttributes != null) {
if (getUserFullNameAttribute() != null) {
Attribute attribute = searchResultAttributes.get(getUserFullNameAttribute());
if (attribute != null && attribute.get() != null)
fullName = (String) attribute.get();
}
+
Attribute attribute = searchResultAttributes.get(getUserEmailAttribute());
if (attribute != null && attribute.get() != null)
email = (String) attribute.get();
- if (getGroupRetrieval() instanceof GetGroupsUsingAttribute) {
- GetGroupsUsingAttribute groupRetrieval = (GetGroupsUsingAttribute) getGroupRetrieval();
- attribute = searchResultAttributes.get(
- groupRetrieval.getUserGroupsAttribute());
- if (attribute != null) {
- for (NamingEnumeration<?> e = attribute.getAll(); e.hasMore();) {
-
- // use composite name instead of DN according to
- // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4307193
- Name groupDN = new CompositeName().add((String) e.next());
- logger.debug("Looking up group entry '" + groupDN + "'...");
-
- DirContext groupCtx = null;
- try {
- if (referralCtx != null)
- groupCtx = (DirContext) referralCtx.lookup(groupDN);
- else
- groupCtx = (DirContext) ctx.lookup(groupDN);
-
- if (groupCtx == null) {
- throw new RuntimeException("Can not find group entry " +
- "identified by '" + groupDN + "'.");
- }
- String groupNameAttribute = groupRetrieval.getGroupNameAttribute();
- Attributes groupAttributes = groupCtx.getAttributes("",
- new String[]{groupNameAttribute});
- if (groupAttributes == null
- || groupAttributes.get(groupNameAttribute) == null
- || groupAttributes.get(groupNameAttribute).get() == null) {
- throw new RuntimeException("Can not find attribute '"
- + groupNameAttribute + "' in returned group entry.");
- }
- groupNames.add((String) groupAttributes.get(groupNameAttribute).get());
- } finally {
- if (groupCtx != null)
- try {
- groupCtx.close();
- } catch (NamingException ne) {
- }
- }
- }
- } else {
- logger.warn("No attribute identified by '" + groupRetrieval.getUserGroupsAttribute()
- + "' inside fetched user LDAP entry.");
- }
- }
+
+ if (getGroupRetrieval() instanceof GetGroupsUsingAttribute)
+ groupNames = retrieveGroupsByAttribute(ctx, referralCtx, searchResultAttributes);
+
+ if (getUserSshKeyAttribute() != null)
+ sshKeys = retrieveSshKeys(searchResultAttributes);
}
- Collection<SshKey> sshKeys;
-
- if (userSSHPublicKey != null) {
- try {
- sshKeys = retrieveSSHPublicKeys(searchResultAttributes);
- } catch (Exception err) {
- logger.warn("Error retrieving SSH public keys", err);
- sshKeys = null;
- }
-
- } else {
- sshKeys = null;
- }
-
- if (getGroupRetrieval() instanceof SearchGroupsUsingFilter) {
- SearchGroupsUsingFilter groupRetrieval = (SearchGroupsUsingFilter) getGroupRetrieval();
- String groupNameAttribute = groupRetrieval.getGroupNameAttribute();
- Name groupSearchBase = new CompositeName().add(groupRetrieval.getGroupSearchBase());
- String groupSearchFilter = StringUtils.replace(groupRetrieval.getGroupSearchFilter(), "{0}", userDN);
- groupSearchFilter = StringUtils.replace(groupSearchFilter, "\\", "\\\\");
-
- logger.debug("Evaluated group search filter: " + groupSearchFilter);
- searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
- searchControls.setReturningAttributes(new String[]{groupNameAttribute});
-
- try {
- if (referralCtx != null)
- results = referralCtx.search(groupSearchBase, groupSearchFilter, searchControls);
- else
- results = ctx.search(groupSearchBase, groupSearchFilter, searchControls);
- if (results != null) {
- while (results.hasMore()) {
- searchResult = (SearchResult) results.next();
- searchResultAttributes = searchResult.getAttributes();
- if (searchResultAttributes == null
- || searchResultAttributes.get(groupNameAttribute) == null
- || searchResultAttributes.get(groupNameAttribute).get() == null) {
- throw new RuntimeException("Can not find attribute '"
- + groupNameAttribute + "' in the returned group object.");
- }
- groupNames.add((String) searchResultAttributes.get(groupNameAttribute).get());
- }
- }
- } catch (PartialResultException pre) {
- logger.warn("Partial exception detected. You may try to set property " +
- "'follow referrals' to true to avoid this exception.", pre);
- }
- }
+ if (getGroupRetrieval() instanceof SearchGroupsUsingFilter)
+ groupNames = retrieveGroupsByFilter(ctx, referralCtx, userDN);
+
if (StringUtils.isBlank(email))
throw new AccountException("Email is required but not available in ldap directory");
else
@@ -395,69 +313,157 @@ public class LdapAuthenticator extends Authenticator {
}
}
}
-
- private Collection<SshKey> retrieveSSHPublicKeys(Attributes searchResultAttributes) throws NamingException, IOException, GeneralSecurityException {
- Collection<SshKey> sshKeys = new ArrayList<SshKey>();
-
- Attribute attributeValue = searchResultAttributes.get(getUserSshKeyAttribute());
-
- if (attributeValue == null) {
- // no values for the user stored in LDAP
- return sshKeys;
+
+ private Collection<String> retrieveGroupsByAttribute(DirContext ctx, DirContext referralCtx,
+ Attributes searchResultAttributes) {
+ Collection<String> groupNames = new HashSet<>();
+ try {
+ GetGroupsUsingAttribute groupRetrieval = (GetGroupsUsingAttribute) getGroupRetrieval();
+ Attribute attribute = searchResultAttributes.get(groupRetrieval.getUserGroupsAttribute());
+ if (attribute != null) {
+ for (NamingEnumeration<?> e = attribute.getAll(); e.hasMore();) {
+
+ // use composite name instead of DN according to
+ // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4307193
+ Name groupDN = new CompositeName().add((String) e.next());
+ logger.debug("Looking up group entry '" + groupDN + "'...");
+
+ DirContext groupCtx = null;
+ try {
+ if (referralCtx != null)
+ groupCtx = (DirContext) referralCtx.lookup(groupDN);
+ else
+ groupCtx = (DirContext) ctx.lookup(groupDN);
+
+ if (groupCtx == null) {
+ throw new RuntimeException("Can not find group entry " +
+ "identified by '" + groupDN + "'.");
+ }
+ String groupNameAttribute = groupRetrieval.getGroupNameAttribute();
+ Attributes groupAttributes = groupCtx.getAttributes("",
+ new String[]{groupNameAttribute});
+ if (groupAttributes == null
+ || groupAttributes.get(groupNameAttribute) == null
+ || groupAttributes.get(groupNameAttribute).get() == null) {
+ throw new RuntimeException("Can not find attribute '"
+ + groupNameAttribute + "' in returned group entry.");
+ }
+ groupNames.add((String) groupAttributes.get(groupNameAttribute).get());
+ } finally {
+ if (groupCtx != null) {
+ try {
+ groupCtx.close();
+ } catch (NamingException ne) {
+ }
+ }
+ }
+ }
+ } else {
+ logger.warn("No attribute identified by '" + groupRetrieval.getUserGroupsAttribute()
+ + "' inside fetched user LDAP entry.");
+ }
+ } catch (NamingException e) {
+ logger.error("Error retrieving groups by attribute");
+ }
+ return groupNames;
+ }
+
+ private Collection<String> retrieveGroupsByFilter(DirContext ctx, DirContext referralCtx, String userDN) {
+ Collection<String> groupNames = new HashSet<>();
+ try {
+ SearchGroupsUsingFilter groupRetrieval = (SearchGroupsUsingFilter) getGroupRetrieval();
+ String groupNameAttribute = groupRetrieval.getGroupNameAttribute();
+ Name groupSearchBase = new CompositeName().add(groupRetrieval.getGroupSearchBase());
+ String groupSearchFilter = StringUtils.replace(groupRetrieval.getGroupSearchFilter(), "{0}", userDN);
+ groupSearchFilter = StringUtils.replace(groupSearchFilter, "\\", "\\\\");
+
+ logger.debug("Evaluated group search filter: " + groupSearchFilter);
+ SearchControls searchControls = new SearchControls();
+ searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
+ searchControls.setReturningAttributes(new String[]{groupNameAttribute});
+ searchControls.setReturningObjFlag(true);
+
+ NamingEnumeration<SearchResult> results;
+ if (referralCtx != null)
+ results = referralCtx.search(groupSearchBase, groupSearchFilter, searchControls);
+ else
+ results = ctx.search(groupSearchBase, groupSearchFilter, searchControls);
+ if (results != null) {
+ while (results.hasMore()) {
+ SearchResult searchResult = (SearchResult) results.next();
+ Attributes searchResultAttributes = searchResult.getAttributes();
+ if (searchResultAttributes == null
+ || searchResultAttributes.get(groupNameAttribute) == null
+ || searchResultAttributes.get(groupNameAttribute).get() == null) {
+ throw new RuntimeException("Can not find attribute '"
+ + groupNameAttribute + "' in the returned group object.");
+ }
+ groupNames.add((String) searchResultAttributes.get(groupNameAttribute).get());
+ }
+ }
+ } catch (PartialResultException pre) {
+ logger.warn("Partial exception detected. You may try to set property " +
+ "'follow referrals' to true to avoid this exception.", pre);
+ } catch (NamingException e) {
+ logger.error("Error retrieving groups by filter", e);
}
+ return groupNames;
+ }
- NamingEnumeration<?> ldapValues = attributeValue.getAll();
- int keyIndex = 1;
-
- while (ldapValues.hasMore()) {
- Object value = ldapValues.next();
-
- if (value instanceof String) {
- String content = (String) value;
+ @Nullable
+ private Collection<SshKey> retrieveSshKeys(Attributes searchResultAttributes) {
+ Attribute attribute = searchResultAttributes.get(getUserSshKeyAttribute());
+ if (attribute != null) {
+ Collection<SshKey> sshKeys = new ArrayList<SshKey>();
+ try {
+ NamingEnumeration<?> ldapValues = attribute.getAll();
+ int keyIndex = 1;
- try {
- SshKey sshKey = parseSshPublicKey(keyIndex, content);
- sshKeys.add(sshKey);
- } catch (Exception err) {
- logger.warn("Error parsing SSH public key", err);
+ while (ldapValues.hasMore()) {
+ Object value = ldapValues.next();
+
+ if (value instanceof String)
+ CollectionUtils.addIgnoreNull(sshKeys, parseSshKey(keyIndex, (String) value));
+ else
+ logger.error("SSH key from ldap is not a String");
+
+ keyIndex++;
}
-
- } else {
- logger.warn("SSH public key from ldap not a String");
+
+ } catch (NamingException e) {
+ logger.error("Error retrieving SSH keys", e);
}
-
- keyIndex++;
+ return sshKeys;
+ } else {
+ return null;
}
-
- return sshKeys;
}
- private SshKey parseSshPublicKey(int keyIndex, String content) throws IOException, GeneralSecurityException {
- PublicKey pubEntry = SshKeyUtils.decodeSshPublicKey(content);
- String fingerPrint = KeyUtils.getFingerPrint(SshKeyUtils.MD5_DIGESTER, pubEntry);
-
- SshKey sshKey = new SshKey();
- sshKey.setDigest(fingerPrint);
- sshKey.setContent(content);
-
- String[] parts = content.split(" ");
- if (parts.length > 2) {
- sshKey.setName(parts[2]);
- } else {
- sshKey.setName("ldap." + keyIndex);
- }
-
- return sshKey;
+ @Nullable
+ private SshKey parseSshKey(int keyIndex, String content) {
+ try {
+ PublicKey pubEntry = SshKeyUtils.decodeSshPublicKey(content);
+ String fingerPrint = KeyUtils.getFingerPrint(SshKeyUtils.MD5_DIGESTER, pubEntry);
+
+ SshKey sshKey = new SshKey();
+ sshKey.setDigest(fingerPrint);
+ sshKey.setContent(content);
+
+ return sshKey;
+ } catch (IOException | GeneralSecurityException e) {
+ logger.error("Error parsing SSH key", e);
+ return null;
+ }
}
@Override
public boolean isManagingMemberships() {
- return !(groupRetrieval instanceof DoNotRetrieveGroups);
+ return !(getGroupRetrieval() instanceof DoNotRetrieveGroups);
}
@Override
public boolean isManagingSshKeys() {
- return userSshKeyAttribute != null;
+ return getUserSshKeyAttribute() != null;
}
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/SearchGroupsUsingFilter.java b/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/SearchGroupsUsingFilter.java
index 2b82422d8b..a10623b0ac 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/SearchGroupsUsingFilter.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/administration/authenticator/ldap/SearchGroupsUsingFilter.java
@@ -16,7 +16,7 @@ public class SearchGroupsUsingFilter implements GroupRetrieval {
private String groupNameAttribute = "cn";
@Editable(order=100, description=
- "In case user group relationship maintained at group side, this property specifies " +
+ "In case user group membership maintained at group side, this property specifies " +
"base node for group search. For example: <i>ou=groups, dc=example, dc=com</i>")
@NotEmpty
public String getGroupSearchBase() {
diff --git a/server-core/src/main/java/io/onedev/server/security/OneAuthorizingRealm.java b/server-core/src/main/java/io/onedev/server/security/OneAuthorizingRealm.java
index 533788c5fc..0d4909686d 100644
--- a/server-core/src/main/java/io/onedev/server/security/OneAuthorizingRealm.java
+++ b/server-core/src/main/java/io/onedev/server/security/OneAuthorizingRealm.java
@@ -253,15 +253,24 @@ public class OneAuthorizingRealm extends AuthorizingRealm {
if (authenticated.getFullName() != null)
user.setFullName(authenticated.getFullName());
userManager.save(user);
+
+ if (authenticated.getGroupNames() == null && authenticator.getDefaultGroup() != null) {
+ Group group = groupManager.find(authenticator.getDefaultGroup());
+ if (group != null) {
+ Membership membership = new Membership();
+ membership.setGroup(group);
+ membership.setUser(user);
+ user.getMemberships().add(membership);
+ membershipManager.save(membership);
+ } else {
+ logger.error("Group not found: " + authenticator.getDefaultGroup());
+ }
+ }
}
- if (authenticated.getSSHPublicKeys() != null) {
+ if (authenticated.getSshKeys() != null) {
SshKeyManager sshKeyManager = OneDev.getInstance(SshKeyManager.class);
- try {
- sshKeyManager.syncUserKeys(user, authenticated.getSSHPublicKeys());
- } catch (Exception err) {
- logger.warn("Error setting user SSH public keys provided by authentication", err);
- }
+ sshKeyManager.syncUserKeys(user, authenticated.getSshKeys());
}
}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/InsertSshKeyPanel.html b/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/InsertSshKeyPanel.html
index d0b84a8166..99a4d4022f 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/InsertSshKeyPanel.html
+++ b/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/InsertSshKeyPanel.html
@@ -2,7 +2,7 @@
<div class="insert-ssh-key">
<div class="modal-header">
<button wicket:id="close" type="button" class="close">&times;</button>
- <h4 class="modal-title">Add a SSH key</h4>
+ <h4 class="modal-title">Add a SSH Key</h4>
</div>
<form wicket:id="form">
<div class="modal-body">
diff --git a/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/InsertSshKeyPanel.java b/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/InsertSshKeyPanel.java
index 2dd99ff0d9..7a7afd1730 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/InsertSshKeyPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/InsertSshKeyPanel.java
@@ -21,7 +21,6 @@ import io.onedev.server.model.User;
import io.onedev.server.ssh.SshKeyUtils;
import io.onedev.server.util.Path;
import io.onedev.server.util.PathNode;
-import io.onedev.server.util.SecurityUtils;
import io.onedev.server.web.editable.BeanContext;
import io.onedev.server.web.editable.BeanEditor;
@@ -67,15 +66,7 @@ public abstract class InsertSshKeyPanel extends Panel {
throw new RuntimeException(e);
}
- if (getUser().getSshKeys().stream().anyMatch(it->it.getName().equals(sshKey.getName()))) {
- String message;
- if (SecurityUtils.getUser().equals(getUser()))
- message = "You have another key with the same name";
- else
- message = "This name is already used by another key of user '" + getUser().getDisplayName() + "'";
- editor.error(new Path(new PathNode.Named("name")), message);
- target.add(form);
- } else if (sshKeyManager.findByDigest(sshKey.getDigest()) != null) {
+ if (sshKeyManager.findByDigest(sshKey.getDigest()) != null) {
editor.error(new Path(new PathNode.Named("content")), "This key is already in use");
target.add(form);
} else {
diff --git a/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/SshKeyListPanel.java b/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/SshKeyListPanel.java
index 3f1f2a0446..ccb7902d59 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/SshKeyListPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/user/sshkey/SshKeyListPanel.java
@@ -50,22 +50,26 @@ public class SshKeyListPanel extends GenericPanel<List<SshKey>> {
List<IColumn<SshKey, Void>> columns = new ArrayList<>();
- columns.add(new AbstractColumn<SshKey, Void>(Model.of("Name")) {
+ columns.add(new AbstractColumn<SshKey, Void>(Model.of("Digest")) {
@Override
public void populateItem(Item<ICellPopulator<SshKey>> cellItem, String componentId,
IModel<SshKey> rowModel) {
- cellItem.add(new Label(componentId, rowModel.getObject().getName()));
+ cellItem.add(new Label(componentId, rowModel.getObject().getDigest()));
}
});
- columns.add(new AbstractColumn<SshKey, Void>(Model.of("Digest")) {
+ columns.add(new AbstractColumn<SshKey, Void>(Model.of("Comment")) {
@Override
public void populateItem(Item<ICellPopulator<SshKey>> cellItem, String componentId,
IModel<SshKey> rowModel) {
- cellItem.add(new Label(componentId, rowModel.getObject().getDigest()));
+ String comment = rowModel.getObject().getComment();
+ if (comment != null)
+ cellItem.add(new Label(componentId, comment));
+ else
+ cellItem.add(new Label(componentId, "<i>No comment</i>").setEscapeModelStrings(false));
}
});
@@ -98,15 +102,14 @@ public class SshKeyListPanel extends GenericPanel<List<SshKey>> {
public void onClick(AjaxRequestTarget target) {
SshKey sshKey = rowModel.getObject();
OneDev.getInstance(SshKeyManager.class).delete(sshKey);
- Session.get().success("SSH key '" + sshKey.getName() + "' deleted");
+ Session.get().success("SSH key deleted");
target.add(sshKeysTable);
}
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
-
- String message = "Do you really want to delete SSH key '" + rowModel.getObject().getName() + "'?";
+ String message = "Do you really want to delete this SSH key?";
attributes.getAjaxCallListeners().add(new ConfirmClickListener(message));
}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/authenticator/AuthenticatorPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/authenticator/AuthenticatorPage.java
index 575a554951..c6ae7b8e30 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/authenticator/AuthenticatorPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/authenticator/AuthenticatorPage.java
@@ -140,7 +140,7 @@ public class AuthenticatorPage extends AdministrationPage {
new UsernamePasswordToken(token.getUserName(), token.getPassword()));
StringBuilder retrievedInfoBuilder = new StringBuilder();
if (authenticated.getFullName() != null) {
- retrievedInfoBuilder.append("Full name: ")
+ retrievedInfoBuilder.append("Full Name: ")
.append(authenticated.getFullName())
.append("\n");
}
@@ -154,6 +154,10 @@ public class AuthenticatorPage extends AdministrationPage {
.append(Joiner.on(", ").join(authenticated.getGroupNames()))
.append("\n");
}
+ if (authenticated.getSshKeys() != null) {
+ retrievedInfoBuilder.append("Number of SSH Keys: ").append(authenticated.getSshKeys().size())
+ .append("\n");
+ }
StringBuilder messageBuilder =
new StringBuilder("Test successful: authentication passed");
if (retrievedInfoBuilder.length() != 0) {
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/user/UserPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/user/UserPage.java
index 9a2781459c..be4b808c20 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/user/UserPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/user/UserPage.java
@@ -98,7 +98,7 @@ public abstract class UserPage extends AdministrationPage {
tabs.add(new UserTab("Authorized Projects", "fa fa-fw fa-ext fa-repo", UserAuthorizationsPage.class));
if (isSshEnabled()) {
- tabs.add(new UserTab("Ssh Keys", "fa fa-fw fa-shield", UserSshKeysPage.class));
+ tabs.add(new UserTab("SSH Keys", "fa fa-fw fa-shield", UserSshKeysPage.class));
}
return tabs;
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/user/membership/UserMembershipsPage.html b/server-core/src/main/java/io/onedev/server/web/page/admin/user/membership/UserMembershipsPage.html
index d84eb8d4bc..d00b7e6f07 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/user/membership/UserMembershipsPage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/user/membership/UserMembershipsPage.html
@@ -2,6 +2,9 @@
<div class="page-title">Belonging Groups</div>
<div class="membership-list list">
<div class="head clearfix">
+ <div wicket:id="externalManagedNote" class="alert alert-info">
+ Group memberships of this user are managed by external authentication provider
+ </div>
<div class="pull-left clearable-wrapper">
<input wicket:id="filterGroups" class="form-control search" placeholder="Filter by group name">
</div>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/user/membership/UserMembershipsPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/user/membership/UserMembershipsPage.java
index 8217eeb7c1..ae4e7ef8e9 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/user/membership/UserMembershipsPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/user/membership/UserMembershipsPage.java
@@ -18,6 +18,7 @@ import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
+import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
@@ -85,6 +86,8 @@ public class UserMembershipsPage extends UserPage {
protected void onInitialize() {
super.onInitialize();
+ add(new WebMarkupContainer("externalManagedNote").setVisible(getUser().isMembershipExternalManaged()));
+
TextField<String> searchField;
add(searchField = new TextField<String>("filterGroups", Model.of(query)));
@@ -150,7 +153,7 @@ public class UserMembershipsPage extends UserPage {
response.render(JavaScriptHeaderItem.forReference(new GroupChoiceResourceReference()));
}
- });
+ }.setVisible(!getUser().isMembershipExternalManaged()));
AjaxLink<Void> deleteSelected = new AjaxLink<Void>("deleteSelected") {
@@ -169,7 +172,7 @@ public class UserMembershipsPage extends UserPage {
@Override
protected void onConfigure() {
super.onConfigure();
- setVisible(!selectionColumn.getSelections().isEmpty());
+ setVisible(selectionColumn != null && !selectionColumn.getSelections().isEmpty());
}
};
@@ -178,15 +181,17 @@ public class UserMembershipsPage extends UserPage {
List<IColumn<Membership, Void>> columns = new ArrayList<>();
- selectionColumn = new SelectionColumn<Membership, Void>() {
-
- @Override
- protected void onSelectionChange(AjaxRequestTarget target) {
- target.add(deleteSelected);
- }
-
- };
- columns.add(selectionColumn);
+ if (!getUser().isMembershipExternalManaged()) {
+ selectionColumn = new SelectionColumn<Membership, Void>() {
+
+ @Override
+ protected void onSelectionChange(AjaxRequestTarget target) {
+ target.add(deleteSelected);
+ }
+
+ };
+ columns.add(selectionColumn);
+ }
columns.add(new AbstractColumn<Membership, Void>(Model.of("Name")) {
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/user/ssh/UserSshKeysPage.html b/server-core/src/main/java/io/onedev/server/web/page/admin/user/ssh/UserSshKeysPage.html
index 6907d03c31..d736f01b94 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/user/ssh/UserSshKeysPage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/user/ssh/UserSshKeysPage.html
@@ -1,11 +1,11 @@
<wicket:extend>
- <div class="page-title">Ssh Keys</div>
+ <div class="page-title">SSH Keys</div>
<div class="user-ssh-key-list list">
<div class="head">
<a class="add-new btn btn-success" wicket:id="newKey"><i
- class="fa fa-plus"></i> New Ssh Key</a>
+ class="fa fa-plus"></i> New SSH Key</a>
<div wicket:id="sshKeyNote" class="alert alert-info">
- SSH keys are managed by an external authentication provider
+ SSH keys of this user are managed by an external authentication provider
</div>
</div>
<div class="body">
diff --git a/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.html b/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.html
index f25c77a153..474f55f30d 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.html
@@ -26,7 +26,7 @@
<li wicket:id="groupManagement"><a wicket:id="link"><i class="fa fa-fw fa-group"></i> Group Management</a></li>
<li wicket:id="securitySetting"><a wicket:id="link"><i class="fa fa-fw fa-lock"></i> Security Setting</a></li>
<li wicket:id="externelAuthentication"><a wicket:id="link"><i class="fa fa-fw fa-key"></i> Externel Authentication</a></li>
- <li wicket:id="sshSetting"><a wicket:id="link"><i class="fa fa-fw fa-shield"></i> Ssh Setting</a></li>
+ <li wicket:id="sshSetting"><a wicket:id="link"><i class="fa fa-fw fa-shield"></i> SSH Setting</a></li>
<li role="separator" class="divider"></li>
<li wicket:id="systemSetting"><a wicket:id="link"><i class="fa fa-fw fa-sliders"></i> System Setting</a></li>
<li wicket:id="issueSetting"><a wicket:id="link"><i class="fa fa-fw fa-bug"></i> Issue Setting</a></li>
@@ -65,7 +65,7 @@
<li wicket:id="myProfile"><a wicket:id="link"><i class="fa fa-fw fa-list-alt"></i> My Profile</a></li>
<li wicket:id="myAvatar"><a wicket:id="link"><i class="fa fa-fw fa-picture-o"></i> Edit Avatar</a></li>
<li wicket:id="myPassword"><a wicket:id="link"><i class="fa fa-fw fa-key"></i> Change Password</a></li>
- <li wicket:id="mySshKeys"><a wicket:id="link"><i class="fa fa-fw fa-shield"></i> Ssh Keys</a></li>
+ <li wicket:id="mySshKeys"><a wicket:id="link"><i class="fa fa-fw fa-shield"></i> SSH Keys</a></li>
<li role="separator" class="divider"></li>
<li><a wicket:id="signOut"><i class="fa fa-fw fa-sign-out"></i> <span wicket:id="label"></span></a></li>
</ul>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/my/sshkeys/MySshKeysPage.html b/server-core/src/main/java/io/onedev/server/web/page/my/sshkeys/MySshKeysPage.html
index de34c45f69..2482e94fb1 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/my/sshkeys/MySshKeysPage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/my/sshkeys/MySshKeysPage.html
@@ -4,7 +4,7 @@
<div class="head">
<a class="add-new btn btn-success" wicket:id="newKey"><i class="fa fa-plus"></i> New SSH Key</a>
<div wicket:id="sshKeyNote" class="alert alert-info">
- SSH keys are managed by external authentication provider
+ Your SSH keys are managed by external authentication provider
</div>
</div>
<div class="body">