Example #1
0
        protected void Recover_Click(object sender, EventArgs e)
        {
            String user = User.Text;
            String email = Email.Text;
            if (user != "" && email != "")
            {

                ApplicationDbContext context = new ApplicationDbContext();
                String idUser = SqlCode.SelectForString("select id from AspNetUsers where UserName = '" + user + "'");
                ApplicationUser userr = context.Users.Find(idUser);

                if (userr.IsNotNull())
                {
                    if (userr.Email == email)
                    {
                        //gets user manager
                        UserManager manager = new UserManager();
                        //removes user pass
                        IdentityResult result = manager.RemovePassword(idUser);
                        //generates new pass
                        String newPass = (Guid.NewGuid().ToString("N").Substring(1, 8) + ".").Trim();
                        //updates the pass
                        result = manager.AddPassword(idUser, newPass);

                        if (result.Succeeded)
                        {
                            EmailClass.SendEmailRecover(email, newPass);
                            PlaceHolder1.Visible = true;
                            FailureText.Text = "Password of user changed email has been send";
                            Thread.Sleep(1000);
                            Response.Redirect("~/Account/Login.aspx");

                        }
                        else
                        {
                            PlaceHolder1.Visible = true;
                            FailureText.Text = "Error reseting the password";
                        }

                    }
                    else
                    {
                        PlaceHolder1.Visible = true;
                        FailureText.Text = "User does not match email!!";
                    }
                }
                else
                {
                    PlaceHolder1.Visible = true;
                    FailureText.Text = "User is invalid";
                }

            }
            else
            {
                PlaceHolder1.Visible = true;
                FailureText.Text = "User or password fields are empty!!";
            }
        }
        public ActionResult ResetPassword(ResetPasswordViewModel model)
        {
            var um = new UserManager<ApplicationUser>(
                new UserStore<ApplicationUser>(new ApplicationDbContext()));
            string userId = um.FindByName(model.UserName).Id;
            bool hasPassword = HasPassword(userId);
            ViewBag.HasLocalPassword = hasPassword;
            ViewBag.ReturnUrl = Url.Action("ResetPassword");
            if (hasPassword)
            {
                if (ModelState.IsValid)
                {
                    //IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
                    IdentityResult result = um.RemovePassword(userId);
                    if (result.Succeeded)
                    {
                        result = um.AddPassword(userId, model.NewPassword);
                        if (result.Succeeded)
                        {
                            return RedirectToAction("ResetPassword", new
                            {
                                Message = ManageMessageId.ChangePasswordSuccess
                               ,
                                userName = model.UserName
                            });
                        }
                        else
                        {
                            AddErrors(result);
                        }
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Example #3
0
        public JsonResult ChangeUserPassword(string userId, string password)
        {
            UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
            userManager.RemovePassword(userId);
            userManager.AddPassword(userId, password);

            return Json(new { success = true });
        }
Example #4
0
        public ActionResult Edit(EditAccountModel editModel)
        {
            var userManager = new UserManager<Account>(new UserStore<Account>(DbContext));
            Account editAccount = userManager.FindByName(editModel.UserName);

            if (editAccount == null)
            {
                return RedirectErrorPage();
            }

            // Kiểm tra tên tài khoản đã tồn tại hay chưa
            Account accountDb;
            if (editAccount.UserName != editModel.UserName)
            {
                accountDb = userManager.FindByName(editModel.UserName);
                if (accountDb != null)
                {
                    ModelState.AddModelError("UserName", "Tên tài khoản đã được sử dụng.");
                }
            }

            if (editAccount.Email != editModel.Email)
            {
                accountDb = userManager.FindByEmail(editModel.Email);
                if (accountDb != null)
                {
                    ModelState.AddModelError("Email", "Email đã được sử dụng.");
                }
            }
            if (editAccount.Profile.Identity != editModel.Identity)
            {
                accountDb = DbContext.Accounts.FirstOrDefault(s => s.Profile.Identity == editModel.Identity);
                if (accountDb != null)
                {
                    ModelState.AddModelError("Identity", "Mã số này đã được sử dụng.");
                }
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var acc = userManager.FindByName(editModel.UserName);
                    acc.Email = editModel.Email;
                    acc.PhoneNumber = editModel.PhoneNumber;
                    acc.Profile.BirthDate = editModel.BirthDate;
                    acc.Profile.FirstName = editModel.FirstName;
                    acc.Profile.LastName = editModel.LastName;
                    acc.Profile.Notes = editModel.Notes;
                    acc.Profile.Actived = editModel.Actived;
                    acc.Profile.Identity = editModel.Identity;
                    var result = userManager.Update(acc);
                    if (result.Succeeded)
                    {
                        if (!string.IsNullOrEmpty(editModel.Password))
                        {
                            userManager.RemovePassword(acc.Id);
                            userManager.AddPassword(acc.Id, editModel.Password);
                        }
                        if (editModel.Role == "Admin")
                        {
                            userManager.AddToRole(acc.Id, "Admin");
                            userManager.AddToRole(acc.Id, "Teacher");
                        }
                        else if (editModel.Role == "Teacher")
                        {
                            userManager.AddToRole(acc.Id, "Teacher");
                        }
                        else
                        {
                            userManager.AddToRole(acc.Id, "Student");
                        }

                        return Redirect(null);
                    }
                    ModelState.AddModelError("", "Đã có lỗi xảy ra. Vui lòng thử lại sau.");
                }
                catch
                {
                    ModelState.AddModelError("", "Đã có lỗi xảy ra. Vui lòng thử lại sau.");
                }
            }
            ViewBag.IsEdit = true;
            InitFormData(editModel);
            return View(editModel);
        }
        public ActionResult Rights_User_SetPassword(SetUserPasswordViewModel model)
        {
            ModelState state = ModelState["NewPassword"];

            if (ModelState.IsValid)
            {
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_identityDb));
                userManager.UserValidator = new UserValidator<ApplicationUser>(userManager) { AllowOnlyAlphanumericUserNames = false };
                
                var result2 = userManager.RemovePassword(model.userId);
                var result = userManager.AddPassword(model.userId, model.NewPassword);
                return RedirectToAction("Rights");
            }

            return View();
        }
Example #6
0
        public ActionResult ResetPassword(FormCollection coll)
        {                    
            string[] randomAdjectives = {"thrutinn", "sleipur", "lodinn", "bonadur", "gradur", "brundadur", "siginn",
                                    "risinn", "lepjandi", "litill", "stor", "langur", "stuttur", "stinnur"};
            string[] randomNouns = {"angus", "besefi", "brusi", "lokur", "redur", "skondull", "tilli", "volsi", "skaufi"};

            var rand = new Random();
            int adjectiveNumber = rand.Next(0, 13);
            int nounNumber = rand.Next(0, 8);
            int randomNumber = rand.Next(1, 999);

            string newPass = randomAdjectives[adjectiveNumber] + randomNouns[nounNumber] + randomNumber.ToString();

            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());            
            var userService = new UserService();
            var email = coll["Email"];
            if(userService.getUserByEmail(email) != null)
            {
                var userId = userService.getUserByEmail(email).Id;
                userManager.RemovePassword(userId);
                userManager.AddPassword(userId, newPass);
                var message = new MailMessage();
                message.To.Add(new MailAddress(email));
                message.From = new MailAddress("Skilaboðaskjóðan");
                message.Subject = "Your password has been reset. ";
                message.Body = "<h2>Your password was reset on " + DateTime.Now.ToString() + "</h2>" + "<h3>Your new password is: " + newPass + "</h2>";
                message.IsBodyHtml = true;
                var smtp = new SmtpClient();

                var credential = new NetworkCredential
                {
                    UserName = "[email protected]",
                    Password = "smegma123"
                };
                smtp.Credentials = credential;
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.Send(message);
            }        
            return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri);
        
        }
        protected void usersListview_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "SaveUserRoles")
            {
                string userId = e.CommandArgument.ConvertTo<string>();
                UserManager manager = new UserManager();
                CheckBoxList userRolesCheckboxList = e.Item.FindFirstControl<CheckBoxList>("userRolesCheckboxList");
                foreach (ListItem item in userRolesCheckboxList.Items)
                {
                    if (item.Selected)
                    {
                        manager.AddToRole(userId, item.Text);
                    }
                    else
                    {
                        manager.RemoveFromRole(userId, item.Text);
                    }
                }
                SuccessMessageUser = "Roles of user saved";
                successMessageUser.Visible = true;
            }
            else if (e.CommandName == "ChangePassword")
            {
                TextBox passwordTextBox = e.Item.FindFirstControl<TextBox>("NewPassword");
                TextBox confirmPasswordTextBox = e.Item.FindFirstControl<TextBox>("ConfirmNewPassword");

                if (!passwordTextBox.Equals("") && !confirmPasswordTextBox.Equals("") &&
                    passwordTextBox.Text == confirmPasswordTextBox.Text)
                {
                    string userId = e.CommandArgument.ConvertTo<string>();
                    UserManager manager = new UserManager();
                    IdentityResult result = manager.RemovePassword(userId);
                    result = manager.AddPassword(userId, passwordTextBox.Text);
                    if (result.Succeeded)
                    {
                        successMessageUser.Visible = true;
                        SuccessMessageUser = "Password of user changed";
                    }
                    else
                    {
                        successMessageUser.Visible = true;
                        AddErrors(result);
                        return;
                    }
                }
            }
        }