package com.gitplex.server.security.authenticator.ldap;

import org.hibernate.validator.constraints.NotEmpty;

import com.gitplex.server.util.editable.annotation.Editable;

@Editable(name="Active Directory", order=100)
public class ActiveDirectoryAuthenticator extends LdapAuthenticator {

	private static final long serialVersionUID = 1L;

	private String groupSearchBase;
	
    @Editable(order=100, name="LDAP URL", description=
    	"Specifies LDAP URL of the Active Directory server, for example: <i>ldap://ad-server</i>, or <i>ldaps://ad-server</i>")
    @NotEmpty
	@Override
	public String getLdapUrl() {
		return super.getLdapUrl();
	}

	@Editable(order=300, description=""
			+ "To authenticate user against Active Directory and retrieve associated attributes and groups, GitPlex "
			+ "would have to first authenticate itself against the Active Directory server and GitPlex does that by "
			+ "sending 'manager' DN and password. The manager DN should be specified in form of "
			+ "<i>&lt;account name&gt;@&lt;domain&gt;</i>, for instance: <i>gitplex@example.com</i>")
	@NotEmpty
	@Override
	public String getManagerDN() {
		return super.getManagerDN();
	}

	@Editable(order=500, description=
		"Specifies the base node for user search. For example: <i>cn=Users, dc=example, dc=com</i>")
	@NotEmpty
	@Override
	public String getUserSearchBase() {
		return super.getUserSearchBase();
	}

	@Override
	public String getUserSearchFilter() {
		return "(&(sAMAccountName={0})(objectclass=user))";
	}
    
	@Override
	public String getUserFullNameAttribute() {
		return super.getUserFullNameAttribute();
	}

	@Override
	public String getUserEmailAttribute() {
		return super.getUserEmailAttribute();
	}

	@Editable(order=1000, description=""
			+ "Specify group search base if you want to search groups associated with the user. For example: "
			+ "<i>cn=Users, dc=example, dc=com</i>")
	public String getGroupSearchBase() {
		return groupSearchBase;
	}

	public void setGroupSearchBase(String groupSearchBase) {
		this.groupSearchBase = groupSearchBase;
	}

	@Override
	public GroupRetrieval getGroupRetrieval() {
		if (getGroupSearchBase() != null) {
			SearchGroupsUsingFilter groupRetrieval = new SearchGroupsUsingFilter();
			groupRetrieval.setGroupSearchBase(getGroupSearchBase());
			groupRetrieval.setGroupSearchFilter("(&(member:1.2.840.113556.1.4.1941:={0})(objectclass=group))");
			return groupRetrieval;
		} else {
			return new DoNotRetrieveGroups();
		}
	}
	
}
