您的位置:首页 > 其它

通过LDAP获取Username

2011-01-06 01:17 239 查看
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security.Principal;
using System.DirectoryServices;
using System.Net.Mail;
using System.Text;

/// <summary>
/// Summary description for Tools
/// </summary>
public class Tools
{
    public enum RightType
    {
        Manager = 1,
        Logistics = 2,
        IDM=3,
        Admin=4
    }

    // Fields
    private string Adpathg = ConfigurationManager.AppSettings["getgroup"].ToString();
    private string Adpathu = ConfigurationManager.AppSettings["getuser"].ToString();

    // Methods
    public string ExtractUserName(string path)
    {
        string[] strArray = path.Split(new char[] { '//' });
        return strArray[strArray.Length - 1];
    }

    static public string GetUserName(IPrincipal user)
    {
        return GetUserName(user.Identity.Name);
    }

    static public string GetUserFullName(IPrincipal user)
    {
        return GetUserFullName(user.Identity.Name);
    }

    static public string GetUserName(string strLogin)
    {
        string fullUserName = strLogin.ToUpper();

        char[] split = { '//' };
        string[] arrUsers = fullUserName.Split(split);
        return arrUsers[arrUsers.Length - 1];
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="ntAccount">like Asia/Jiyzhou</param>
    /// <returns></returns>
    static public string GetUserFullName(string ntAccount)
    {
        string str = "";
        // Parse the string to check if domain name is present.
        int idx = ntAccount.IndexOf('//');
        if (idx == -1)
        {
            idx = ntAccount.IndexOf('@');
        }

        string strDomain;
        string strName;

        if (idx != -1)
        {
            strDomain = ntAccount.Substring(0, idx);
            strName = ntAccount.Substring(idx + 1);
        }
        else
        {
            strDomain = Environment.MachineName;
            strName = ntAccount;
        }

        DirectoryEntry obDirEntry = null;
        try
        {
            obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
            System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
            object obVal = coll["FullName"].Value;
            str = obVal.ToString();
        }
        catch (Exception ex)
        {
            str = "";
            //Trace.Write(ex.Message);
        }
        return str;
    }

    public bool GetAccountname(string loginName)
    {
        DirectoryEntry searchRoot = new DirectoryEntry(this.Adpathu, ConfigurationManager.AppSettings["logonname"].ToString(), ConfigurationManager.AppSettings["logonpwd"].ToString());
        SearchResult result = new DirectorySearcher(searchRoot).FindOne();
        string str2 = (string)result.Properties["samaccountname"][0];
        string str = (string)result.Properties["givenname"][0];
        string str3 = (string)result.Properties["sn"][0];
        if (result == null)
        {
            return false;
        }
        return true;
    }
    /// <summary>
    /// Retrieve the members within the group name
    /// </summary>
    /// <param name="groupName"></param>
    /// <returns>Dictionary contains NT Account stored in key and display name stored in value</returns>
    public Dictionary<string, string> GetADGroupMembers(string groupName)
    {
        //Initial Directory Searchser
        DirectoryEntry searchRoot = new DirectoryEntry(this.Adpathg, ConfigurationManager.AppSettings["logonname"].ToString(), ConfigurationManager.AppSettings["logonpwd"].ToString());
        DirectorySearcher searcher = new DirectorySearcher(searchRoot);

        //find the NT group
        searcher.Filter = string.Format("(cn={0})", groupName);
        searcher.PropertiesToLoad.Add("member");
        searcher.CacheResults = true;
        SearchResult result = searcher.FindOne();

        //retrieve the members within group
        Dictionary<string, string> rtUsers = new Dictionary<string, string>();
        foreach (string memberDN in result.Properties["member"])     //memberDN,short for member Distinguish Name in LDAP
        {
            DirectoryEntry dnMember = new DirectoryEntry("LDAP://" + memberDN, ConfigurationManager.AppSettings["logonname"].ToString(), ConfigurationManager.AppSettings["logonpwd"].ToString());
            DirectorySearcher dsMemberDetails = new DirectorySearcher(dnMember);
            SearchResult srMemberDetails = dsMemberDetails.FindOne();

            string ntAccount = srMemberDetails.Properties["samaccountname"][0].ToString();
            //display maybe empty,prevent the exception
            string displayName = string.Empty;
            try
            {
                displayName = srMemberDetails.Properties["displayName"][0].ToString();
            }
            catch (Exception) { }
            rtUsers.Add(ntAccount, displayName);
        }

        //if (result != null)  
        //{
        //    for (int i = 0; i < result.Properties["member"].Count; i++)
        //    {
        //        DirectoryEntry drEntryUser = new DirectoryEntry("LDAP://" + ((string)result.Properties["member"][i]), ConfigurationManager.AppSettings["logonname"].ToString(), ConfigurationManager.AppSettings["logonpwd"].ToString());
        //        DirectorySearcher searcherUserDetails = new DirectorySearcher(drEntryUser);
        //        SearchResult resultUserDetail = searcherUserDetails.FindOne();

        //        string ntAccount = resultUserDetail.Properties["samaccountname"][0].ToString();
        //    
4000
    string displayName = resultUserDetail.Properties["displayName"][0].ToString();

        //    }
        //}
        return rtUsers;
    }

    static public void FillDropListFromNTGroup(DropDownList dropDownList, string ntGroupName)
    {
        Tools tool = new Tools();
        Dictionary<string, string> dictMembers = tool.GetADGroupMembers(ntGroupName);

        foreach (KeyValuePair<string, string> kvPair in dictMembers)
        {
            dropDownList.Items.Add(new ListItem(string.Format("{0}, {1}", kvPair.Key.ToUpper(), kvPair.Value), kvPair.Key.ToUpper()));
        }
    }

    static public bool CheckNTGroup(string ntname, string ntGroupName)
    {
        bool existname=false;
        Tools tool = new Tools();
        Dictionary<string, string> dictMembers = tool.GetADGroupMembers(ntGroupName);

        foreach (KeyValuePair<string, string> kvPair in dictMembers)
        {
            if (kvPair.Key.ToUpper() == ntname.ToUpper())
            {
                existname=true;
                break;
            }
        }
        if (existname == true)
            return true;
        else
            return false;

    }

    static public string GetNTGroupEmail( string ntGroupName)
    {
        string strEmail = "";
        Tools tool = new Tools();
        Dictionary<string, string> dictMembers = tool.GetADGroupMembers(ntGroupName);

        foreach (KeyValuePair<string, string> kvPair in dictMembers)
        {
            strEmail += GetMaillAddress(kvPair.Key) + ";";
        }
        strEmail = strEmail.Substring(0, strEmail.Length - 1);
        return strEmail;
    }

    public string GetADUserGroups(string username, string password)
    {
        DirectoryEntry searchRoot = new DirectoryEntry(this.Adpathu, username, password);
        DirectorySearcher searcher = new DirectorySearcher(searchRoot);
        searcher.Filter = string.Format("(cn={0})", username);
        searcher.PropertiesToLoad.Add("memberOf");
        StringBuilder builder = new StringBuilder();
        SearchResult result = searcher.FindOne();
        if (result != null)
        {
            int count = result.Properties["memberOf"].Count;
            int num3 = count - 1;
            for (int i = 0; i <= num3; i++)
            {
                builder.Append((string)result.Properties["memberOf"][i]);
                builder.Append("|");
            }
        }
        StringBuilder builder2 = builder;
        builder2.Length--;
        return builder.ToString();
    }

    public bool IsExistInAD(string loginName)
    {
        string str = this.ExtractUserName(loginName);
        DirectoryEntry searchRoot = new DirectoryEntry(this.Adpathu, ConfigurationManager.AppSettings["logonname"].ToString(), ConfigurationManager.AppSettings["logonpwd"].ToString());
        DirectorySearcher searcher = new DirectorySearcher(searchRoot);
        searcher.Filter = string.Format("(SAMAccountName={0})", str);
        searcher.PropertiesToLoad.Add("cn");
        //LogInfo.Loger.Info(str + "|" +searcher.Filter + "|" + Adpathu);
        if (searcher.FindOne() == null)
        {
            return false;
        }
        return true;
    }

    public bool IsExistInGroup(string username, string groupName)
    {
        username = this.ExtractUserName(username);
        DirectoryEntry searchRoot = new DirectoryEntry(this.Adpathg, ConfigurationManager.AppSettings["logonname"].ToString(), ConfigurationManager.AppSettings["logonpwd"].ToString());
        DirectorySearcher searcher = new DirectorySearcher(searchRoot);
        searcher.Filter = string.Format("(cn={0})", groupName);
        searcher.PropertiesToLoad.Add("member");
        SearchResult result = searcher.FindOne();
        if (result != null)
        {
            int num2 = result.Properties["member"].Count - 1;
            for (int i = 0; i <= num2; i++)
            {
                DirectoryEntry entry2 = new DirectoryEntry("LDAP://" + ((string)result.Properties["member"][i]), ConfigurationManager.AppSettings["logonname"].ToString(), ConfigurationManager.AppSettings["logonpwd"].ToString());
                DirectorySearcher searcher2 = new DirectorySearcher(entry2);
                string str = (string)searcher2.FindOne().Properties["samaccountname"][0];
                if (str.ToUpper() == username.ToUpper())
                {
                    return true;
                }
                str = "";
            }
        }
        return false;
    }

    public bool CheckUserRight(IPrincipal user, RightType rightType)
    {
        return this.CheckUserRight(user.Identity.Name, rightType);
    }

    public bool CheckUserRight(string fullUserName, RightType rightType)
    {
        string upperUserName = GetUserName(fullUserName);

        if (rightType == RightType.Admin)
        {
            if (IsExistInAD(fullUserName))
            {
                if (IsExistInGroup(fullUserName, ConfigurationManager.AppSettings["Admingroup"]))
                    return true;
                else
                    return false;
            }
            else
            {
                return false;
            }
        }
        if (rightType == RightType.Manager)
        {
            if (IsExistInAD(fullUserName))
            {
                if (IsExistInGroup(fullUserName, ConfigurationManager.AppSettings["Managergroup"]))
                    return true;
                else
                    return false;
            }
            else
            {
                return false;
            }
        }
        if (rightType == RightType.Logistics)
        {
            if (IsExistInAD(fullUserName))
            {
                if (IsExistInGroup(fullUserName, ConfigurationManager.AppSettings["Logisticsgroup"]))
                    return true;
                else
                    return false;
            }
            else
            {
                return false;
            }
        }
        if (rightType == RightType.IDM)
        {
            if (IsExistInAD(fullUserName))
            {
                if (IsExistInGroup(fullUserName, ConfigurationManager.AppSettings["IDMgroup"]))
                    return true;
                else
                    return false;
            }
            else
            {
                return false;
            }
        }

        return false;
    }

    static public string GetMaillAddress(string ntAccount)
    {
        return ntAccount += "@Sohu.com";
    }

    public void SentMail(string strto, string strsubject, string strcontent)
    {
        try
        {
            MailMessage message = new MailMessage();
            SmtpClient client = new SmtpClient("smtp.celestica.com", 25);
            message.From = new MailAddress(ConfigurationManager.AppSettings["mailfrom"].ToString(), "RSN for materials SysAdmin", Encoding.UTF8);
            message.To.Add(new MailAddress(strto, "", Encoding.UTF8));
            message.Subject = strsubject;
            message.SubjectEncoding = Encoding.UTF8;
            message.IsBodyHtml = true;
            message.Body = strcontent;
            message.BodyEncoding = Encoding.UTF8;
            //client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis;
            client.Send(message);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public bool SentMail2Admin(ArrayList listto, string strsubject, string strcontent)
    {
        bool flag = false;
        try
        {
            MailMessage message = new MailMessage();
            SmtpClient client = new SmtpClient("smtp.celestica.com", 25);
            message.From = new MailAddress(ConfigurationManager.AppSettings["mailfrom"].ToString(), "RSN for materials SysAdmin", Encoding.UTF8);
            int num2 = listto.Count - 1;
            for (int i = 0; i <= num2; i++)
            {
                message.To.Add(new MailAddress(listto[i].ToString().Trim(), "", Encoding.UTF8));
            }
            message.Subject = strsubject;
            message.SubjectEncoding = Encoding.UTF8;
            message.IsBodyHtml = true;
            message.Body = strcontent;
            message.BodyEncoding = Encoding.UTF8;
            client.Send(message);
            flag = true;
        }
        catch (Exception exception1)
        {
            Exception exception = exception1;
            flag = false;
        }
        return flag;
    }

    public bool SentMail3Admin(ArrayList listto, string strsubject, string strcontent,string strCC)
    {
        bool flag = false;
        try
        {
            MailMessage message = new MailMessage();
            SmtpClient client = new SmtpClient("smtp.celestica.com", 25);
            message.From = new MailAddress(ConfigurationManager.AppSettings["mailfrom"].ToString(), "RSN for materials SysAdmin", Encoding.UTF8);
            int num2 = listto.Count - 1;
            for (int i = 0; i <= num2; i++)
            {
                message.To.Add(new MailAddress(listto[i].ToString().Trim(), "", Encoding.UTF8));
            }
            message.CC.Add(new MailAddress(strCC, "", Encoding.UTF8));
            message.Subject = strsubject;
            message.SubjectEncoding = Encoding.UTF8;
            message.IsBodyHtml = true;
            message.Body = strcontent;
            message.BodyEncoding = Encoding.UTF8;
            client.Send(message);
            flag = true;
        }
        catch (Exception exception1)
        {
            Exception exception = exception1;
            flag = false;
        }
        return flag;
    }
}

 

 

webconfig:

 <add key="getuser" value="LDAP://DC=域名,DC=ad,DC=公司名,DC=com" />
  <add key="getgroup" value="LDAP://DC=域名,DC=ad,DC=公司名,DC=com" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐