Example #1
0
        public bool CreateUserPrincipal()
        {
            // Create connection to domain and do a search for the user
            try
            {
                context = new PrincipalContext(ContextType.Domain, givenDomain);

                    UserPrincipal tempUserPrincipal = new UserPrincipal(context);
                    tempUserPrincipal.SamAccountName = givenUserName;

                    // Search for user
                    PrincipalSearcher searchUser = new PrincipalSearcher();
                    searchUser.QueryFilter = tempUserPrincipal;

                    UserPrincipal foundUser = (UserPrincipal)searchUser.FindOne();

                    userPrincipal = foundUser;
                    userGroups = userPrincipal.GetGroups();
                    return true;

            }
            catch (PrincipalServerDownException)
            {
                System.Windows.Forms.MessageBox.Show("Cannot contact the server.");
                return false;
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message, "Unknown Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return false;
            }
        }
Example #2
0
        public static bool adIsUserInAdGroupsBool(string sUserId, string sGroupOrUserListSemiColon)
        {
            //check if user has SAM acct
            System.DirectoryServices.AccountManagement.UserPrincipal ctx = adGetUserPrincipalBySAMAccountName(sUserId);
            if (ctx == null)
            {
                return(false);
            }

            //check if sUserId is in sGroupOrUserListSemiColon
            string[] lstGroupsAndUsers = sGroupOrUserListSemiColon.Split(new char[] { ';' });
            for (int i = 0; i < lstGroupsAndUsers.Length; i++)
            {
                if (sUserId.IndexOf(lstGroupsAndUsers[i]) > -1)
                {
                    return(true);
                }
            }

            //check if any groups is in sGroup
            foreach (GroupPrincipal group in ctx.GetGroups().OrderBy(x => x.Name))
            {
                for (int i = 0; i < lstGroupsAndUsers.Length; i++)
                {
                    if (group.Name == lstGroupsAndUsers[i])
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Example #3
0
 protected void UpdateUser(UserPrincipal up, UserInfo user)
 {
     user.Name = up.DisplayName;
     user.Email = up.EmailAddress;
     user.Active = true;
     foreach (var g in up.GetGroups())
     {
         user.MemberOf.Add(g.SamAccountName);
     }
     user.ExtId = up.DistinguishedName;
 }
Example #4
0
        public static string returnJsonListOfAdGroupsForUserId(string sUserId)
        {
            //get list groups in List
            List <KeyValue> lstGroups = new List <KeyValue>();

            System.DirectoryServices.AccountManagement.UserPrincipal ctx = adGetUserPrincipalBySAMAccountName(sUserId);
            if (ctx == null)
            {
                return("");
            }
            foreach (GroupPrincipal group in ctx.GetGroups().OrderBy(x => x.Name))
            {
                lstGroups.Add(new KeyValue {
                    key = "group", value = group.Name
                });
            }
            return(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(lstGroups).ToString());
        }
Example #5
0
        /// <summary>
        /// Constructor that instantiates an AdUser object with the values of the specified
        /// UserPrincipal's attributes.
        /// </summary>
        /// <param name="user"></param>
        public AdUser(UserPrincipal user)
        {
            this.AccountExpirationData = user.AccountExpirationDate.ToString();
            this.AccountLockoutTime = user.AccountLockoutTime.ToString();
            this.AllowReversiblePasswordEncryption = user.AllowReversiblePasswordEncryption;
            this.BadLogonCount = user.BadLogonCount;
            this.Company = GetCompany(user);
            this.DelegationPermitted = user.DelegationPermitted;
            this.Department = GetDepartment(user);
            this.Description = user.Description;
            this.DisplayName = user.DisplayName;
            this.DistinguishedName = user.DistinguishedName;
            this.EmailAddress = user.EmailAddress;
            this.EmployeeId = user.EmployeeId;
            this.Enabled = user.Enabled;
            this.GivenName = user.GivenName;
            this.Guid = user.Guid.ToString();
            this.HomeDirectory = user.HomeDirectory;
            this.HomeDrive = user.HomeDrive;
            this.LastBadPasswordAttempt = user.LastBadPasswordAttempt.ToString();
            this.LastLogon = user.LastLogon.ToString();
            this.LastPasswordSet = user.LastPasswordSet.ToString();
            this.Manager = GetManager(user);
            this.MemberOf = AdGroup.GetAdGroupSamAccountNames(user.GetGroups());
            this.MiddleName = user.MiddleName;
            this.Mobile = GetMobile(user);
            this.Name = user.Name;
            this.PasswordNeverExpires = user.PasswordNeverExpires;
            this.PasswordNotRequired = user.PasswordNotRequired;
            this.ProfilePath = AdToolkit.GetProperty(user, "profilePath");
            this.SamAccountName = user.SamAccountName;
            this.ScriptPath = user.ScriptPath;
            this.Sid = user.Sid.Value;
            this.SmartCardLogonRequired = user.SmartcardLogonRequired;
            this.Surname = user.Surname;
            this.UserCannotChangePassword = user.UserCannotChangePassword;
            this.UserPrincipalName = user.UserPrincipalName;
            this.VoiceTelephoneNumber = user.VoiceTelephoneNumber;

            //user.GetGroups
        }
        /// <summary>
        /// Create an AD User from the given connection and UserPrincipal
        /// </summary>
        /// <param name="connection">The AD connection</param>
        /// <param name="user">An existing UserPrincipal object</param>
        public ADUser(ActiveDirectory connection, UserPrincipal user)
        {
            if (connection == null || user == null)
            {
                throw new NullReferenceException();
            }

            _sourceUser = user;
            _connection = connection;
            mapper = new DEMapper();
            DEFields.Add("manager");
            this.UserState = UserStates.Existing;

            foreach (System.Reflection.PropertyInfo property in this.GetType().GetProperties())
            {
                DEFieldAttribute tag= property.GetCustomAttributes(typeof(DEFieldAttribute),true).FirstOrDefault() as DEFieldAttribute;

                if (tag != null)
                {
                    DEFields.Add(tag.Name!=null?tag.Name:property.Name);
                }
            }

            if (user.Name != null)
            {
                _groups = new List<string>(_sourceUser.GetGroups(connection.GlobalContext).Select(item => item.Name));
            }

            this.Initialize(_sourceUser);

            if (_sourceUser.DisplayName != null)
            {
                directoryEntry = _sourceUser.GetUnderlyingObject() as DirectoryEntry;
                directoryEntry.RefreshCache(DEFields.ToArray<string>());
                mapper.Copy(directoryEntry, this);
            }

            string ldap=String.Format("LDAP://{0}/{1}", connection.Name, connection.Container);
            parent = new DirectoryEntry(ldap, connection.User, connection.Password);
        }
Example #7
0
        bool _tryAgainAD = true; //Try again to get rid of Load Assemblies exceptions...
        List<string> GetWindowsGroupsUsingAD(string contextType)
        {
            var result = new List<string>();
            try
            {
                // set up domain context
                PrincipalContext context = new PrincipalContext((ContextType)Enum.Parse(typeof(ContextType), contextType));
                string name = WebUserName;
                if (WebPrincipal != null) name = WebPrincipal.Identity.Name;
                if (Identity != null) name = Identity.Name;

                var user = new UserPrincipal(context);
                user.SamAccountName = name;
                var searcher = new PrincipalSearcher(user);
                user = searcher.FindOne() as UserPrincipal;
                if (user == null) user = UserPrincipal.FindByIdentity(context, name);

                if (user != null)
                {
                    // find the roles....
                    var roles = user.GetGroups();
                    // enumerate over them
                    foreach (Principal p in roles)
                    {
                        result.Add(p.Name);
                    }
                }
                else throw new Exception("Unable to find user:"******"Error getting groups using AD...\r\n" + ex.Message + "\r\n";
                }
            }
            return result;
        }
        public void CreateLdapAccount(LdapConfig cfg, bool allowPasswordChange)
        {
            string pwd = ldapContext.LdapConfigs.Decryptpassword(cfg);
            DirectoryEntry ou = new DirectoryEntry("LDAP://" + OuAssignment.OuDistinguishedName, cfg.UserName, pwd);

            string fn = Regex.Replace(Member.GivenName, @"[^A-Za-z0-9]+", "");
            string mn = null;
            if(Member.MiddleName != null)
                mn = Regex.Replace(Member.MiddleName, @"[^A-Za-z0-9]+", "");
            string ln = Regex.Replace(Member.Surname, @"[^A-Za-z0-9]+", "");




            string name = Lcps.DivisionDirectory.Members.DirectoryMemberRepository.GetName(DirectoryMemberNameFormats.Full | DirectoryMemberNameFormats.Sort, ln, fn, mn);
            string dn = string.Format("CN={0} ({1})", name.Replace(",", "\\,"), Member.UserName);

            var principalContext = new PrincipalContext(ContextType.Domain, cfg.DomainPrincipalName, cfg.UserName, pwd);


            string memberPw = Member.DecryptPassword();

            bool enabled = false;
            if ((Member.MembershipScope & Convert.ToInt64(MembershipScopeReserved.Active)) == Convert.ToInt64(MembershipScopeReserved.Active))
                enabled = true;

            if ((Member.MembershipScope & Convert.ToInt64(MembershipScopeReserved.Inactive)) == Convert.ToInt64(MembershipScopeReserved.Inactive))
                enabled = false;


            LdapUser = new UserPrincipal(principalContext, Member.UserName, memberPw, enabled);

            string scope = this.dirContext.MembershipScopes.GetCaptionLabel(Member.MembershipScope);
            LdapUser.Description = scope;
            LdapUser.DisplayName = Lcps.DivisionDirectory.Members.DirectoryMemberRepository.GetName(Member, DirectoryMemberNameFormats.Short | DirectoryMemberNameFormats.Sort);
            LdapUser.UserCannotChangePassword = (!allowPasswordChange);
            LdapUser.Surname = Member.Surname;
            LdapUser.GivenName = Member.GivenName;
            LdapUser.UserPrincipalName = Member.UserName + "@" + cfg.DomainPrincipalName;
            LdapUser.PasswordNeverExpires = true;
            LdapUser.EmployeeId = Member.InternalId;
            LdapUser.EmailAddress = Member.Email;

            try
            {
                LdapUser.Save();
            }
            catch (Exception ex)
            {
                throw new Exception("Could not create user", ex);
            }

            ou.RefreshCache();

            DirectoryEntry de = null;

            try
            {
                de = (DirectoryEntry)LdapUser.GetUnderlyingObject();
                de.InvokeSet("division", pwd);
                de.InvokeSet("comment", DateTime.Now.ToString());
                de.MoveTo(ou, dn);
                de.CommitChanges();
                de.RefreshCache();
                ou.RefreshCache();

                LdapUser = UserPrincipal.FindByIdentity(PrincipalContext, IdentityType.SamAccountName, Member.UserName);

            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Could not move user {0} to OU", dn), ex);
            }



            SyncGroupMemberships(false);

            bool gErr = true;
            int x = 1;

            while(gErr == true)
            {
                try
                {
                    x++;

                    DirectoryEntry thisU = (DirectoryEntry)LdapUser.GetUnderlyingObject();
                    thisU.CommitChanges();
                    ou.RefreshCache();
                    thisU.RefreshCache();
                    

                    foreach(GroupPrincipal g in LdapUser.GetGroups())
                    {
                        string n = g.Name;
                    }
                    gErr = false;
                }
                catch
                {
                    LdapUser = UserPrincipal.FindByIdentity(PrincipalContext, IdentityType.SamAccountName, Member.UserName);
                    gErr = true;
                }
            }

            try
            {
                foreach (PersonalFolder f in PersonalFolders)
                {
                    string n = Member.UserName;
                    if (f.NameFormat == PersonalFolderIdFormats.Fullname)
                    {
                        FormatFolderName(Member, f);
                    }

                    string pth = Path.Combine(f.FolderPath, n);
                    if (!Directory.Exists(pth))
                        Directory.CreateDirectory(pth);

                    GrantFullAccessToFolder(pth, de, Member.UserName, cfg.DomainPrincipalName);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not create personal folders", ex);
            }

        }
Example #9
0
        private IEnumerable<DomainGroup> GetGroupsWithSupergroupsForUser(UserPrincipal userPrincipal)
        {
            var directGroups = userPrincipal.GetGroups();

            var supergroups = GetSupergroups(userPrincipal.GetGroups());
            var groups = directGroups.Select(ToDomainGroup).ToList();

            groups.AddRange(supergroups);

            return groups.Distinct().ToList();
        }
Example #10
0
 private IEnumerable<DomainGroup> GetGroupsForUser(UserPrincipal userPrincipal)
 {
     var groups = new List<DomainGroup>();
     var principalGroups = userPrincipal.GetGroups();
     foreach (var principalGroup in principalGroups)
     {
         groups.Add(ToDomainGroup(principalGroup));
     }
     return groups.Distinct().ToList();
 }