public class CommonFun
{
/// <summary>
/// [获取/设置]认证类型,比如NTLM等
/// </summary>
public string AuthType
{
get
{
return fAuthType;
}
set
{
fAuthType = value;
}
}
/// <summary>
/// 验证用户帐号是否OK,如果成功,返回true,否则返回false
/// </summary>
/// <returns></returns>
public bool Authentication(string userCode, string password)
{
if (string.IsNullOrEmpty(userCode))
{
return false;
}
try
{
userCode = this.GetDomainPrefixName() + @"\" + userCode;
DirectoryEntry entry = new DirectoryEntry(fLDAPPath, userCode, password);
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = string.Format("(AccountName={0})", GetNoDomainPrefixName(userCode));
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (result == null)
{
return false;
}
// 更新目录中的用户的新路径
fLDAPPath = result.Path;
fFilterAttribute = (string)result.Properties["cn"][0];
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 检查域中是否包含该帐号(不需要密码也可以验证)
/// </summary>
/// <returns></returns>
public bool CheckExist(string userCode)
{
//检查是否有重复的帐号
DirectoryEntry entry = new DirectoryEntry(fLDAPPath);
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = string.Format("(AccountName={0})", GetNoDomainPrefixName(userCode));
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
return (result != null);
}
/// <summary>
/// 修改密码,修改成功后返回true,否则false
/// </summary>
/// <param name="newPassword"></param>
/// <returns></returns>
public bool ChangePassword(string userCode,string oldPassword,string newPassword)
{
if (string.IsNullOrEmpty(userCode))
{
return false;
}
try
{
userCode = this.GetDomainPrefixName() + @"\" + userCode;
DirectoryEntry entry = new DirectoryEntry(fLDAPPath, userCode, oldPassword);
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = string.Format("(AccountName={0})", GetNoDomainPrefixName(userCode));
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (result == null)
{
throw new Exception(string.Format("找不到相应的用户:{0}", userCode));
}
fLDAPPath = result.Path;
fFilterAttribute = (string)result.Properties["cn"][0];
entry.Path = fLDAPPath;
entry.Invoke("ChangePassword", oldPassword, newPassword);
entry.CommitChanges();
return true;
}
catch(Exception ex)
{
return false;
}
}
/// <summary>
/// 返回没有域前缀的名称
/// </summary>
/// <returns></returns>
private string GetNoDomainPrefixName(string userCode)
{
string userName = userCode;
if (userName.IndexOf("\\") != -1)
{
userName = userName.Remove(0, userName.IndexOf("\\") + 1);
}
return userName;
}
private string GetDomainPrefixName()
{
string domainPrefixName = "";
int preDI = fLDAPPath.IndexOf(".");
if (preDI> 7)
{
domainPrefixName = fLDAPPath.Substring(7, preDI);
}
return domainPrefixName;
}
}