Monday 16 December 2013

Get List of groups and users From LDAP



using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;

public partial class Admin : System.Web.UI.Page
{

    Common common = new Common();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
                //Getting the Current user name
                string username = common.ExtractUserName(User.Identity.Name);
                UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), IdentityType.SamAccountName, username);
                ArrayList adminGroups = common.GetAdminGroups();//Get the Admin Groups
                ArrayList groups = common.getGroupsByPrincipal(user);//Get the User Groups
                groups.Add(user.DisplayName.ToLower().Trim());
                groups.Add(user.SamAccountName.ToLower().Trim());
                getUsersAndGroup();
                bool redirect = true;
//Check wheather user is admin or not

                if (adminGroups.Count > 0)
                {
                    foreach (string adminGroup in adminGroups)
                    {
                        if (groups.Contains(adminGroup))
                        {
                            redirect = false;
                            break;
                        }
                    }
                    if (redirect)
                    {
                        Response.Redirect("Default.aspx", true);
                    }
                }
        }
    }

    private void getUsersAndGroup()
    {
        try
        {
            ArrayList allUsers = this.getAllUsers();
            ArrayList allGroups = this.getAllGroups();

            DataTable dtGroups = new DataTable();
            dtGroups.Columns.Add("Groups");
            for (int i = 0; i < allGroups.Count; i++)
            {
                DataRow row = dtGroups.NewRow();
                row[0] = allGroups[i];

                dtGroups.Rows.Add(row);
            }

            ddlGroup.DataSource = dtGroups;
            ddlGroup.DataTextField = "Groups";
            ddlGroup.DataValueField = "Groups";
            ddlGroup.DataBind();
        }
        catch (Exception ex)
        {
            ErrorLog.Log(ex);
        }
    }


    public DataTable getUsers(string username)
    {
        DataTable dtUsers = new DataTable();
        dtUsers.Columns.Add("users");
        try
        {
            // create domain context
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            // fetch your group
            GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, username);
            // enumerate over the group's members
            foreach (Principal p in group.Members)
            {
                DataRow row = dtUsers.NewRow();
                row[0] = p.Name;
                dtUsers.Rows.Add(row);
                //Console.WriteLine("Principal '{0}', type '{1}'", p.Name, p.StructuralObjectClass);
            }

        }
        catch (Exception ex)
        {
            ErrorLog.Log(ex);
        }
        return dtUsers;
    }


    private ArrayList getAllUsers()
    {
        return getADObjectsForClass("User");
    }

    private ArrayList getAllGroups()
    {
        return getADObjectsForClass("Group");
    }


    private ArrayList getADObjectsForClass(string objectClass)
    {
        ArrayList list = new ArrayList();
        try
        {
            DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + System.Configuration.ConfigurationManager.AppSettings["DomainName"]); //Enter the domain name here
            DirectorySearcher dirSearcher = new DirectorySearcher();
            dirSearcher.SearchRoot = dirEntry;
            dirSearcher.Filter = "(objectClass=" + objectClass + ")";
            dirSearcher.PropertiesToLoad.Add("cn");
            SearchResultCollection res = dirSearcher.FindAll();
            foreach (SearchResult objectUnit in res)
            {
                list.Add(objectUnit.Properties["cn"][0].ToString());
            }
        }
        catch (Exception ex)
        {
            ErrorLog.Log(ex);
        }
        return list;
    }


}

No comments:

Post a Comment