Exemple #1
0
        /// <summary>
        /// Aktif Dizin Veritabanına yeni kayıt ekleme methodu.
        /// Kullanıcı Kayıt UI formunda girilen parametreleri UserFormInputs sınıfı vasıtasıyla alır ve veritabanıına kaydeder.
        /// </summary>
        /// <param name="userFormInputs"></param>
        /// <returns></returns>
        public void CreateUserAccount(UserFormInputs userFormInputs)
        {
            try
            {
                using (PrincipalContext principialCon = user.BaglantiKur(userFormInputs.YapisalBirim))
                    using (UserPrincipal userPrincipial = user.SetUserPrincipial(principialCon, userFormInputs.userName, userFormInputs.userPass))
                    {
                        userPrincipial.SamAccountName = userFormInputs.userName;
                        userPrincipial.Name           = string.Format("{0} {1}", userFormInputs.name, userFormInputs.surname);
                        userPrincipial.Surname        = userFormInputs.surname;
                        userPrincipial.DisplayName    = string.Format("{0} {1}", userFormInputs.name, userFormInputs.surname);
                        userPrincipial.Enabled        = true;

                        userPrincipial.Save();
                        userPrincipial.ExpirePasswordNow(); //Kullanıcı ilk oturum açılısında parolasını değiştirsin .
                        _stateForTest   = true;
                        ResponseMessage = "Kullanıcı kaydı başarılı";
                    }
            }
            catch (DirectoryServicesCOMException ex)
            {
                _stateForTest   = false;
                ResponseMessage = ex.Message;
            }
            catch (Exception ex)
            {
                _stateForTest   = false;
                ResponseMessage = ex.Message;
            }
        }
Exemple #2
0
        /// <summary>
        /// Expires the specified user or computer's password, forcing it to be required to be reset.
        /// </summary>
        /// <param name="name">The unique identifier of the user or computer.</param>
        /// <returns>True if the password was expired successfully, false otherwise.</returns>
        public static Boolean ExpirePassword(string name)
        {
            Boolean result = false;

            try
            {
                Principal p = Principal.FindByIdentity(GetPrincipalContext(), name);

                if ((p != null) && (p is UserPrincipal))
                {
                    UserPrincipal u = p as UserPrincipal;
                    u.ExpirePasswordNow();
                    u.Save();
                    result = true;
                }
                else if ((p != null) && (p is ComputerPrincipal))
                {
                    ComputerPrincipal c = p as ComputerPrincipal;
                    c.ExpirePasswordNow();
                    c.Save();
                    result = true;
                }
            }
            catch
            {
                result = false;
            }
            return(result);
        }
Exemple #3
0
        public static void AddUser(SBSUser user)
        {
            UserPrincipal userPrincipal = new UserPrincipal(Context);

            //if (lastName != null && lastName.Length > 0)
            userPrincipal.Surname = user.UserName;

            //if (firstName != null && firstName.Length > 0)
            userPrincipal.GivenName = user.UserName;

            //if (employeeID != null && employeeID.Length > 0)
            //    userPrincipal.EmployeeId = employeeID;

            //if (emailAddress != null && emailAddress.Length > 0)
            userPrincipal.EmailAddress = user.Email;

            //if (telephone != null && telephone.Length > 0)
            //    userPrincipal.VoiceTelephoneNumber = telephone;

            //if (userLogonName != null && userLogonName.Length > 0)
            userPrincipal.SamAccountName = user.UserName;

            string pwdOfNewlyCreatedUser = user.PassWord;

            userPrincipal.SetPassword(pwdOfNewlyCreatedUser);

            userPrincipal.Enabled = true;
            userPrincipal.ExpirePasswordNow();

            userPrincipal.Save();
        }
Exemple #4
0
        private UserPrincipal CreateOrGetUserPrincipal(UserInformation userInfo)
        {
            UserPrincipal user = null;

            if (!LocalAccount.UserExists(userInfo.Username))
            {
                // See note about MS bug in CreateOrGetGroupPrincipal to understand the mix of DE/Principal here:
                using (user = new UserPrincipal(m_machinePrincipal))
                {
                    user.Name = userInfo.Username;
                    user.SetPassword(userInfo.Password);
                    user.Description     = "pGina created";
                    userInfo.Description = user.Description;
                    if (userInfo.PasswordEXP)
                    {
                        user.ExpirePasswordNow();
                    }
                    user.Save();

                    // Sync via DE
                    SyncUserPrincipalInfo(userInfo);

                    // We have to re-fetch to get changes made via underlying DE
                    return(GetUserPrincipal(user.Name));
                }
            }

            user = GetUserPrincipal(userInfo.Username);
            if (user == null)
            {
                m_logger.ErrorFormat("Unable to get user principal for account that apparently exists: {0}", userInfo.Username);
            }

            return(user);
        }
        public void NewADUser(User user, string senha)
        {
            try {
                DirectoryEntry NewUser;
                DirectoryEntry UserDirectory;

                String strPath = "LDAP://OU=INTRANET,DC=livehost-dom,DC=local";
                UserDirectory = new DirectoryEntry(strPath);
                UserDirectory.RefreshCache();

                NewUser = UserDirectory.Children.Add("CN=" + user.Nome, "user");
                NewUser.Properties["Name"].Add(user.Nome);
                NewUser.Properties["DisplayName"].Add(user.Nome);
                NewUser.Properties["SamAccountName"].Add(user.Login);
                NewUser.Properties["mail"].Add(user.Mail);
                NewUser.Properties["EmployeeNumber"].Add(user.Cpf);
                NewUser.Properties["EmployeeID"].Add(user.DataNasc);
                NewUser.Properties["Title"].Add(user.Cargo);
                NewUser.Properties["UserPrincipalName"].Add(user.Login + "@livehost-dom.local");
                NewUser.CommitChanges();

                UserPrincipal ADUser = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, user.Login);
                ADUser.SetPassword(senha);
                ADUser.Enabled = true;
                ADUser.ExpirePasswordNow();
                ADUser.Save();
            }
            catch (Exception e) {
                MessageBox.Show(e.Message.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }
Exemple #6
0
        public static UserPrincipal CreateNewUser(string sUserName, string sPassword, string sGivenName, string sSurname, string sEmailAddress)
        {
            if (!IsUserExisiting(sUserName))
            {
                PrincipalContext oPrincipalContext = GetPrincipalContext();
                Console.WriteLine(" creating context");
                UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext);
                if (oUserPrincipal != null)
                {
                    Console.WriteLine(" creating user");

                    oUserPrincipal.UserPrincipalName = sUserName;
                    oUserPrincipal.SetPassword(sPassword);
                    oUserPrincipal.GivenName    = sGivenName;
                    oUserPrincipal.Surname      = sSurname;
                    oUserPrincipal.EmailAddress = sEmailAddress;
                    oUserPrincipal.DisplayName  = sGivenName + " " + sSurname;
                    oUserPrincipal.Name         = sGivenName + " " + sSurname;
                    oUserPrincipal.ExpirePasswordNow();
                    //                    oUserPrincipal..PasswordNeverExpires = true;
                    Console.WriteLine(" saving user");
                    oUserPrincipal.Save();
                }
                return(oUserPrincipal);
            }
            else
            {
                return(GetUser(sUserName));
            }
        }
        /// <summary>
        /// Aktif Dizin Veritabanına yeni kayıt ekleme methodu.
        /// Kullanıcı Kayıt UI formunda girilen parametreleri UserFormInputs sınıfı vasıtasıyla alır ve veritabanıına kaydeder.
        /// </summary>
        /// <param name="userFormInputs"></param>
        /// <returns></returns>
        public bool CreateUserAccount(UserFormInputs userFormInputs)
        {
            UserFormInputs _userFormInputs = userFormInputs;
            bool           kayitDurum      = false;


            try
            {
                using (PrincipalContext principialCon = user.BaglantiKur())
                    using (UserPrincipal userPrincipial = user.SetUserPrincipial(principialCon, _userFormInputs.userName, _userFormInputs.userPass))
                    {
                        userPrincipial.SamAccountName = _userFormInputs.userName;
                        userPrincipial.Name           = string.Format("{0} {1}", _userFormInputs.name, _userFormInputs.surname);
                        userPrincipial.Surname        = _userFormInputs.surname;
                        userPrincipial.DisplayName    = string.Format("{0} {1}", _userFormInputs.name, _userFormInputs.surname);
                        userPrincipial.Enabled        = true;
                        userPrincipial.Save();

                        //Kullanıcı ilk oturum açılısında parolasını değiştirsin .
                        userPrincipial.ExpirePasswordNow();
                        kayitDurum = true;
                    }
            }

            catch (PrincipalExistsException ex)
            {
                responseMessage = ex.Message;
            }

            catch (PrincipalException ex)
            {
                responseMessage = ex.Message;
            }
            return(kayitDurum);
        }
Exemple #8
0
        public ActionResult ResetarConta(string usuario)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            // find a user
            UserPrincipal user = UserPrincipal.FindByIdentity(ctx, usuario);

            if (user != null)
            {
                try
                {
                    user.SetPassword("Seconci@1234");
                    user.ExpirePasswordNow();
                    user.Save();
                    TempData["MsgIndex"]       = "A senha de " + usuario + " foi trocada para Seconci@1234";
                    TempData["MsgIndexStatus"] = "success";
                }
                catch (Exception e)
                {
                    TempData["MsgIndex"]       = "A senha de " + usuario + " não foi trocada. Erro " + e;
                    TempData["MsgIndexStatus"] = "danger";
                }
            }

            return(RedirectToAction("Index"));
        }
        /// <summary>
        /// Force expire password of a user
        /// </summary>
        /// <param name="sUserName">The username to expire the password</param>
        public void ExpireUserPassword(string sUserName)
        {
            UserPrincipal oUserPrincipal = GetUser(sUserName);

            oUserPrincipal.ExpirePasswordNow();
            oUserPrincipal.Save();
        }
Exemple #10
0
        public void ExpireUserPassword(string userIdentity)
        {
            UserPrincipal oUserPrincipal = GetUserPrincipal(userIdentity);

            oUserPrincipal.ExpirePasswordNow();
            oUserPrincipal.Save();
        }
Exemple #11
0
        private void CreateUser(string username, string password, bool canChange, bool isExpired, bool isDisabled)
        {
            try
            {
                PrincipalContext principalContext = new PrincipalContext(ContextType.Machine, Environment.MachineName);

                UserPrincipal user = new UserPrincipal(principalContext);

                user.SetPassword(password);
                if (isExpired)
                {
                    user.ExpirePasswordNow();
                }

                user.Name    = username;
                user.Enabled = !isDisabled;
                user.UserCannotChangePassword = !canChange;


                user.Save();

                GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, "Users");
                group.Members.Add(user);
                group.Save();

                MessageBox.Show("User Created");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Exemple #12
0
        public void Create(Account account)
        {
            try
            {
                using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain, container))
                    using (UserPrincipal up = new UserPrincipal(pc, account.AccountName, account.Password, account.Enabled))
                    {
                        up.GivenName             = account.FirstName;
                        up.UserPrincipalName     = $"{account.AccountName}@{domain}";
                        up.Surname               = account.LastName;
                        up.AccountExpirationDate = account.Expires;
                        up.DisplayName           = account.AccountName;
                        up.Save();

                        if (account.PasswordExpired)
                        {
                            up.ExpirePasswordNow();
                        }
                    }
            }
            catch (PrincipalExistsException)
            {
                throw new AppException("Kontoen findes i forvejen.");
            }
            catch (PasswordException)
            {
                throw new AppException("Passwordet opfylder ikke domænets krav til kompleksitet.");
            }
            catch (Exception)
            {
                throw new AppException("Der skete en fejl ved oprettelsen af kontoen.");
            }
        }
Exemple #13
0
    /// <summary>
    /// Saves the user to AD
    /// </summary>
    /// <returns>Returns an Error object with information about eventual errors</returns>
    public CustomError Save(bool mustChangePassword, bool BULK)
    {
        CustomError errors = new CustomError();

        if (DoesUserExist(AccountName))
        {
            errors.Add(CustomError.ErrorType.UserExists);
        }
        else
        {
            try
            {
                up.SamAccountName    = AccountName;
                up.UserPrincipalName = AccountName + "@TRR-INET.local";
                up.Surname           = Lastname;
                up.GivenName         = Firstname;
                up.DisplayName       = AccountName;
                up.SetPassword(Password);
                up.AccountExpirationDate = DateExpires;
                up.Enabled = true;

                //up.HomeDrive = "P:";
                //up.HomeDirectory = (@"\\TRR-I-SRV2\Pdrev$\" + AccountName);

                if (mustChangePassword)
                {
                    up.ExpirePasswordNow();
                }

                up.Save();

                //CreatePDriveFolder();
                //DirectoryEntry entry = (DirectoryEntry)up.GetUnderlyingObject();
                //entry.InvokeSet("HomeDirectory", new object[] { (@"\\TRR-I-SRV2\Pdrev$\" + AccountName) });
                //entry.InvokeSet("HomeDrive", new object[] { "P:" });
                //entry.InvokeSet("ProfilePath", new object[] { (@"\\TRR-SRV1\UserProfiles$\" + AccountName) });
                //entry.CommitChanges();

                if (!BULK)
                {
                    Logging.WriteLog(Logging.Action.Create, Logging.ObjectType.ADUser, AccountName, (!mustChangePassword ? Password : String.Empty), mustChangePassword, String.Format("{0}{1}", FullName, (DateExpires.HasValue ? (" - " + DateExpires.Value.ToShortDateString()) : String.Empty)));
                }
            }
            catch (PrincipalExistsException)
            {
                errors.Add(CustomError.ErrorType.UserExists);
            }
            catch (PrincipalOperationException)
            {
                errors.Add(CustomError.ErrorType.OUDoesNotExist);
            }
            catch (InvalidOperationException)
            {
                errors.Add(CustomError.ErrorType.UnknownError);
            }
        }

        return(errors);
    }
Exemple #14
0
 /// <summary>
 /// Установить признак истечения срока действия пароля
 /// </summary>
 /// <param name="sUserName">Имя пользователя с "истекающим" сроком действия</param>
 public static void ExpireUserPassword(string sUserName)
 {
     using (UserPrincipal oUserPrincipal = GetUser(sUserName))
     {
         oUserPrincipal.ExpirePasswordNow();
         oUserPrincipal.Save();
     }
 }
Exemple #15
0
        public bool CreateUser()
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "testdomene.local", "OU=Users,OU=TEST,DC=testdomene,DC=local");


            UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, username);

            if (usr != null)
            {
                MessageBox.Show("Brukernavn finnes allerede i domenet");
                return(false);
            }

            UserPrincipal userPrincipal = new UserPrincipal(ctx);

            if (lastname != null && lastname.Length > 0)
            {
                userPrincipal.Surname = lastname;
            }

            if (firstname != null && firstname.Length > 0)
            {
                userPrincipal.GivenName = firstname;
            }

            if (username != null && username.Length > 0)
            {
                userPrincipal.SamAccountName = username;
            }

            if (description != null && description.Length > 0)
            {
                userPrincipal.Description = username;
            }

            userPrincipal.DisplayName = firstname + lastname;

            string pwd = "test1234";

            userPrincipal.SetPassword(pwd);

            userPrincipal.Enabled = false;
            userPrincipal.ExpirePasswordNow();

            try
            {
                userPrincipal.Save();
            }
            catch (Exception e)
            {
                MessageBox.Show("Kunne ikke lagre objektet." + e + "");
                return(false);
            }


            return(true);
        }
Exemple #16
0
 private void ChangePassword(UserPrincipal userObject, string password, bool unlockAccount, bool passwordExpired)
 {
     userObject.SetPassword(password);
     if (IsAccountLocked(userObject))
     {
         userObject.UnlockAccount();
     }
     if (passwordExpired)
     {
         userObject.ExpirePasswordNow();
     }
     userObject.Save();
 }
Exemple #17
0
 // changes db
 private void btnChangeLogon_Click(object sender, EventArgs e)
 {
     if (adUser == null)
     {
         MessageBox.Show("No user object, please reload.", "Invalid request", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     adUser.ExpirePasswordNow();
     adUser.Save();
     statusLabel.Text = "Password expires, user now has to change on next logon.";
     MessageBox.Show("Password expires, user now has to change on next logon.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
     refreshUser();
 }
Exemple #18
0
    public static CustomError ChangePassword(string accountname, string password, bool changePasswordAtLogon, bool pwdGenerated, bool noLogging = false)
    {
        CustomError errors = new CustomError();

        if (!DoesUserExist(accountname))
        {
            errors.Add(CustomError.ErrorType.UserDoesNotExist);
        }
        else
        {
            errors = Utilities.CheckPassword(password, accountname);

            if (!errors.HasErrors)
            {
                try
                {
                    PrincipalContext ouContex = new PrincipalContext(ContextType.Domain, "TRR-INET.local", Utilities.GetSearchOU());

                    UserPrincipal up = UserPrincipal.FindByIdentity(ouContex, accountname);

                    if (up == null)
                    {
                        errors.Add(CustomError.ErrorType.NoAccess);
                    }
                    else
                    {
                        up.SetPassword(password);

                        if (changePasswordAtLogon)
                        {
                            up.PasswordNeverExpires = false;
                            up.ExpirePasswordNow();
                            up.Enabled = true;
                            up.Save();
                        }

                        if (!noLogging)
                        {
                            Logging.WriteLog(Logging.Action.ChangePassword, Logging.ObjectType.ADUser, accountname, (pwdGenerated ? password : String.Empty), changePasswordAtLogon);
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        return(errors);
    }
 public Boolean ResetPassword(String user, String senha)
 {
     try {
         UserPrincipal ADUser = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, user);
         ADUser.SetPassword(senha);
         ADUser.ExpirePasswordNow();
         ADUser.Save();
         return(true);
     }
     catch (Exception e) {
         MessageBox.Show(e.Message.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
         return(false);
     }
 }
Exemple #20
0
        public Utilities.ItemRunResult RunItem(int EmpID, RunPayload RunPayload)
        {
            DataLayer.EPSEntities db   = new DataLayer.EPSEntities();
            Utilities             util = new Utilities();

            try
            {
                Employee emp             = db.Employees.Where(e => e.EmpID == EmpID).FirstOrDefault();
                String   domain          = util.GetParam("ADDomain", "Active Directory domain");
                String   adminName       = util.GetParam("ADUsername", "Active Directory admin user");
                String   password        = util.GetParam("ADPassword", "Active Directory admin user password");
                String   defaultPassword = String.Format("AA{0}^", Guid.NewGuid().ToString());

                PrincipalContext context = new PrincipalContext(ContextType.Domain, domain, adminName, password);
                UserPrincipal    user    = UserPrincipal.FindByIdentity(context, emp.Username);

                if (user == null)
                {
                    return(new Utilities.ItemRunResult {
                        ResultID = 4, ResultText = String.Format("{0} could not be found in Active Directory.", emp.Username), TimeDone = DateTime.Now
                    });
                }

                if (user.AccountExpirationDate == null)
                {
                    return(new Utilities.ItemRunResult {
                        ResultID = 5, ResultText = String.Format("{0} was not expired in Active Directory.", emp.Username), TimeDone = DateTime.Now
                    });
                }

                user.AccountExpirationDate = null;
                user.Save();

                user.SetPassword(defaultPassword);
                user.ExpirePasswordNow();
                user.Save();

                return(new Utilities.ItemRunResult {
                    ResultID = 2, ResultText = String.Format("{0} {1} was removed from expiration in Active Directory.", emp.FirstName, emp.LastName), TimeDone = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return(new Utilities.ItemRunResult {
                    ResultID = 4, ResultText = String.Format("Error: {0}", ex.Message), TimeDone = DateTime.Now
                });
            }
        }
Exemple #21
0
        /// <summary>
        /// Sets the user information for a given user
        /// </summary>
        /// <param name="domainName">domain name for the user, empty for local users</param>
        /// <param name="userName">the user name</param>
        /// <param name="passwordExpired">user is required to change the password on first login</param>
        /// <param name="passwordNeverExpires">password never expires</param>
        /// <param name="disabled">account is disabled</param>
        public static void SetUserInformation(string domainName, string userName, bool passwordExpired, bool passwordNeverExpires, bool disabled)
        {
            UserPrincipal user = GetUser(domainName, userName);

            Assert.IsFalse(null == user, string.Format("User '{0}' was not found under domain '{1}'.", userName, domainName));
            user.PasswordNeverExpires = passwordNeverExpires;
            user.Enabled = !disabled;
            if (passwordExpired)
            {
                user.ExpirePasswordNow();
            }
            else
            {
                // extend the expiration date to a month
                user.AccountExpirationDate = DateTime.Now.Add(new TimeSpan(30, 0, 0, 0, 0));
            }
            user.Save();
        }
Exemple #22
0
        public ActionResult ResetPassword(string Samaccountname)
        {
            //i get the user by its SamaccountName to change his password
            PrincipalContext context = new PrincipalContext(ContextType.Domain, "MBS", "OU=DevOU,DC=MBS,DC=com");
            UserPrincipal    user    = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, Samaccountname);

            //Enable Account if it is disabled
            user.Enabled = true;
            //Reset User Password
            string newPassword = "******";

            user.SetPassword(newPassword);
            //Force user to change password at next logon dh optional
            user.ExpirePasswordNow();
            user.Save();
            TempData["msg"] = "<script>alert('Password Changed Successfully');</script>";
            return(RedirectToAction("GetAllUsers"));
        }
        /// <summary>
        /// Creates user.
        /// </summary>
        /// <param name="name">User name.</param>
        /// <returns>Newly created user.</returns>
        public async Task <IPrincipalAsync> CreatePrincipalAsync(string name)
        {
            if (!PrincipalBase.IsValidUserName(name))
            {
                throw new DavException("User name contains invalid characters", DavStatus.FORBIDDEN);
            }

            UserPrincipal userPrincipal = new UserPrincipal(Context.GetPrincipalContext());

            userPrincipal.Name = name;
            userPrincipal.UserPrincipalName = name;

            userPrincipal.Enabled = true;
            userPrincipal.ExpirePasswordNow();

            Context.PrincipalOperation(userPrincipal.Save);

            return(new User(userPrincipal, Context));
        }
Exemple #24
0
        /// <summary>
        /// Создать AD-пользователя.
        /// </summary>
        /// <param name="newUser">Данные нового пользователя.</param>
        /// <returns>Результат операции.</returns>
        public Either <Error, Success> CreateUser(DtoNewAdUser newUser)
        {
            using (var ctx = new PrincipalContext(ContextType.Domain, _domain))
                using (var query = new UserPrincipal(ctx))
                {
                    query.SamAccountName = newUser.Nickname;
                    query.EmailAddress   = newUser.Email;
                    query.SetPassword(newUser.Password);
                    query.DisplayName = $"{newUser.Surname} {newUser.Name} {newUser.Patronomic}";
                    query.GivenName   = newUser.Name;
                    query.Surname     = newUser.Surname;
                    query.MiddleName  = newUser.Patronomic;
                    query.Enabled     = true;
                    query.ExpirePasswordNow();
                    query.Save();
                }

            return(Right <Error, Success>(Success.ItsSuccess));
        }
        private void btnFinish_Click(object sender, EventArgs e)
        {
            try
            {
                if (ckChangePass.Checked)
                {
                    upUserToCreate.ExpirePasswordNow();
                }

                if (ckCannotChange.Checked)
                {
                    upUserToCreate.UserCannotChangePassword = true;
                }

                if (ckPNeverExpires.Checked)
                {
                    upUserToCreate.PasswordNeverExpires = true;
                }

                if (ckAccountDisable.Checked)
                {
                    upUserToCreate.Enabled = false;
                }
                else
                {
                    upUserToCreate.Enabled = true;
                }
                upUserToCreate.Save();
                MessageBox.Show("User created Successfully!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Close();
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("denied"))
                {
                    MessageBox.Show("Access Denied!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                if (ex.Message.Contains("exists"))
                {
                    MessageBox.Show("This users already exists on: \n" + destOu, "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Exemple #26
0
        public AccountStatus CreateNewLdapAccount(UserInfo userInfo, out string errorText, bool pswdPolicyChk = false)
        {
            errorText = string.Empty;
            if (LdapHelper.LdapAccountExists(userInfo, RootPrincipal))
            {
                return(AccountStatus.AccountAlreadyExists);
            }

            try
            {
                userInfo.FirstName = LdapHelper.EscapeChars(userInfo.FirstName);
                userInfo.LastName  = LdapHelper.EscapeChars(userInfo.LastName);
                var preNewUserInfo = LdapHelper.GetUniqueFirstNameLastName(userInfo, RootPrincipal);
                var newUser        = new UserPrincipal(RootPrincipal)
                {
                    SamAccountName    = preNewUserInfo.SamName,
                    DisplayName       = String.Format("{0} {1}", preNewUserInfo.FirstName, preNewUserInfo.LastName),
                    Surname           = preNewUserInfo.LastName,
                    GivenName         = preNewUserInfo.FirstName,
                    UserPrincipalName = preNewUserInfo.Email,
                    EmailAddress      = preNewUserInfo.Email,
                };

                if (!String.IsNullOrEmpty(userInfo.Password))
                {
                    newUser.Enabled = true;
                    newUser.PasswordNeverExpires = true;
                    newUser.SetPassword(userInfo.Password);
                }
                else
                {
                    newUser.ExpirePasswordNow();
                }
                newUser.Save();
                return(AccountStatus.NewAccount);
            }
            catch (Exception ex)
            {
                errorText = String.Format("Exception creating LDAP account for {0} with exception {1}", userInfo.Email, ex.Message);
                return(AccountStatus.AccountCreationFailed);
            }
        }
 public void CreateUser(string username, string firstName, string lastName, string password, string emailAddress = "", bool passNeverExpires = false, bool userCannotChangePW = false, bool changePWOnNextLogon = false)
 {
     using (var pc = new PrincipalContext(ContextType.Domain))
     {
         using (var up = new UserPrincipal(pc))
         {
             up.SamAccountName = username;
             up.EmailAddress   = emailAddress;
             up.SetPassword(password);
             up.Enabled = true;
             up.PasswordNeverExpires     = passNeverExpires;
             up.UserCannotChangePassword = userCannotChangePW;
             if (changePWOnNextLogon)
             {
                 up.ExpirePasswordNow();
             }
             up.Save();
         }
     }
 }
Exemple #28
0
        public ActionResult ResetPassword(string id)
        {
            //i get the user by its SamaccountName to change his password
            PrincipalContext context = new PrincipalContext
                                           (ContextType.Domain, "ad.balkangraph.com", "OU=TestOU,DC=ad,DC=balkangraph,DC=com");
            UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.DistinguishedName, id);

            //Enable Account if it is disabled
            user.Enabled = true;
            //Reset User Password
            string newPassword = "******";

            user.SetPassword(newPassword);
            //Force user to change password at next logon (optional)
            user.ExpirePasswordNow();

            user.Save();

            return(RedirectToAction("OrgChart"));
        }
Exemple #29
0
        public JsonResult ResetPassword(string UserName)
        {
            if (Authorize.InGroup(Authorize.IT))
            {
                PrincipalContext Context = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "username", "password");
                UserPrincipal    user    = UserPrincipal.FindByIdentity(Context, IdentityType.SamAccountName, UserName);

                user.SetPassword("password"); //Not the best idea to hardcode this
                user.ExpirePasswordNow();
                bool isLocked = user.IsAccountLockedOut();
                if (isLocked)
                {
                    user.UnlockAccount();
                }

                return(Json(AD.LockedUsersToList(), JsonRequestBehavior.AllowGet));
            }

            return(null);
        }
Exemple #30
0
        private void join()
        {
            using (PrincipalContext pc = new PrincipalContext(ctx, dmn, container, ContextOptions.Negotiate, uname, pwd))
            {
                try
                {
                    using (UserPrincipal up = new UserPrincipal(pc, nu.log_on_name, "Temp123!", true))
                    {
                        up.Name           = nu.log_on_name;
                        up.SamAccountName = up.Name;
                        up.DisplayName    = nu.first_name + " " + nu.last_name;
                        up.ExpirePasswordNow();
                        if (aduser == true)
                        {
                            up.GivenName         = nu.first_name;
                            up.Surname           = nu.last_name;
                            up.UserPrincipalName = nu.UPN;
                        }
                        up.Save();
                        foreach (string i in group)
                        {
                            try
                            {
                                GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, i);
                                gp.Members.Add(pc, IdentityType.SamAccountName, up.SamAccountName);
                                gp.Save();
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message.ToString());
                            }
                        }
//                        createO365 ouser = new createO365(o365creds, up.DisplayName, nu.log_on_name + "@viatechpub.com", nu.first_name, nu.last_name, location.dmn);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message.ToString());
                }
            }
        }