public ActionResult RecoverPassword(string rt)
        {
            using (var db = new DBContext())
            {
                bool any = (from j in db.tbl_webpages_Membership
                            where j.PasswordVerificationToken == rt
                            select j).Any();

                if (any == true)
                {
                    bool expire = (from j in db.tbl_webpages_Membership
                                   where j.PasswordVerificationToken == rt &&
                                   (j.PasswordVerificationTokenExpirationDate < DateTime.Now)
                                   select j).Any();
                    if (!expire)
                    {
                        RecoverPasswordModel model = new RecoverPasswordModel();
                        model.ReturnToken = rt;
                        return(View(model));
                    }
                    else
                    {
                        ModelState.AddModelError("", "This link has expired.");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The recovery link you just used is not valid.");
                }
            }

            return(View());
        }
Beispiel #2
0
        public ActionResult RecoverPassword(RecoverPasswordModel model)
        {
            var url = "";

            try
            {
                var email = new EmailAddressAttribute();
                if (!email.IsValid(model.Email))
                {
                    ModelState.AddModelError("", "Please enter a valid email!");
                    return(View(model));
                }

                Account account = _dc.Accounts.FirstOrDefault(a => a.Email == model.Email);

                if (account != null)
                {
                    account.ResetPassword    = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 22).Replace("/", "_").Replace("+", "-");
                    _dc.Entry(account).State = EntityState.Modified;
                    _dc.SaveChanges();
                    var currentURL = Request.Url.Scheme + Uri.SchemeDelimiter + Request.Url.Host;
                    url += currentURL + "/Account/ResetPassword/" + account.ResetPassword;
                    string body = "<!DOCTYPE html> <html> <head> <title>Reset Password</title> <style> body{ font-family: 'Source Sans Pro', sans-serif; color: #7f8186; } .btn{ display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 50px; background: #D54E40;\r\n    background: -moz-linear-gradient(left,  #D54E40 0%, #C41F4F 100%);\r\n    background: -webkit-linear-gradient(left,  #D54E40 0%,#C41F4F 100%); background: linear-gradient(to right,  #D54E40 0%,#C41F4F 100%);filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\'#D54E40\', endColorstr=\'#C41F4F\',GradientType=1 );} .text-center{ text-align: center; } .img-responsive { margin: 0 auto; } .btn{ width: 100%; font-weight: bold; font-size: 20px; height: 50px; background-color: #D54D3F; border-radius: 0; box-shadow: none; color: #fff; } .btn:hover, .btn:focus{ background-color: #D54D3F; color: #fff; } a{ color: #fff; } a:hover, a:focus{ text-decoration: none; color: #fff; } </style> </head> <body> <div class='container'> <div class='text-center'> </br> </br> <img src='http://i.imgur.com/t7DZoQs.png' class='img-responsive' width='200' height='200'><br> <h2>Hi " + account.FirstName + " " + account.LastName + "!</h2><br> <h4>We've recived a request to reset your password. If you didn't make the request,<br> just ignore this email. Otherwise, you can reset you password using this link:</h4><br> <a href=" + url + "><button class='btn btn-default'>Reset password</button></a> <h4>Thanks,</h4> <h4>IT Friends Team</h4> </div> </div> </body> </html>";
                    SendSimpleMessage(account.Email, body);


                    //MailMessage mail = new MailMessage();
                    //mail.To.Add(model.Email);
                    //mail.From = new MailAddress("*****@*****.**", "IT Friends", System.Text.Encoding.UTF8);
                    //mail.Subject = "IT Friends - Reset Password";
                    //mail.SubjectEncoding = System.Text.Encoding.UTF8;
                    //mail.Body = "<!DOCTYPE html> <html> <head> <title>Reset Password</title> <style> body{ font-family: 'Source Sans Pro', sans-serif; color: #7f8186; } .btn{ display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 50px; background: #D54E40;\r\n    background: -moz-linear-gradient(left,  #D54E40 0%, #C41F4F 100%);\r\n    background: -webkit-linear-gradient(left,  #D54E40 0%,#C41F4F 100%); background: linear-gradient(to right,  #D54E40 0%,#C41F4F 100%);filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\'#D54E40\', endColorstr=\'#C41F4F\',GradientType=1 );} .text-center{ text-align: center; } .img-responsive { margin: 0 auto; } .btn{ width: 100%; font-weight: bold; font-size: 20px; height: 50px; background-color: #D54D3F; border-radius: 0; box-shadow: none; color: #fff; } .btn:hover, .btn:focus{ background-color: #D54D3F; color: #fff; } a{ color: #fff; } a:hover, a:focus{ text-decoration: none; color: #fff; } </style> </head> <body> <div class='container'> <div class='text-center'> </br> </br> <img src='http://i.imgur.com/t7DZoQs.png' class='img-responsive' width='200' height='200'><br> <h2>Hi " + account.FirstName + " " + account.LastName + "!</h2><br> <h4>We've recived a request to reset your password. If you didn't make the request,<br> just ignore this email. Otherwise, you can reset you password using this link:</h4><br> <a href=" + url + "><button class='btn btn-default'>Reset password</button></a> <h4>Thanks,</h4> <h4>IT Friends Team</h4> </div> </div> </body> </html>";
                    //mail.BodyEncoding = System.Text.Encoding.UTF8;
                    //mail.IsBodyHtml = true;
                    //mail.Priority = MailPriority.High;
                    //SmtpClient client = new SmtpClient();
                    //client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "konanpass123-");
                    //client.Port = 587;
                    //client.Host = "smtp.gmail.com";
                    //client.EnableSsl = true;
                    //client.Send(mail);



                    return(RedirectToAction("Index", "Home"));
                }

                ModelState.AddModelError("", "This email is not associated with a user.");
                return(View(model));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "This service is blocked by the host.\nGo to: " + url);
                return(View(model));
            }
        }
        public void RecoverPassword(RecoverPasswordModel recoverPasswordModel)
        {
            Task <IdentityResult> taskResult = _userRepository.ResetPassword(recoverPasswordModel.UserId, recoverPasswordModel.Token, recoverPasswordModel.Password);
            var result = taskResult.Result;

            if (!result.Succeeded)
            {
                throw new BusinessException(OperationResultCode.InvalidUser, "Non authorized operation.");
            }
        }
Beispiel #4
0
        public ActionResult RecoverPassword(RecoverPasswordModel recoverPasswordModel)
        {
            if (!ModelState.IsValid)
            {
                return(View("RecoverPassword"));
            }

            var email = new Email();

            email.SendForgotPasswordEmail(recoverPasswordModel.GetId(), recoverPasswordModel.Email);

            return(View("ForgotPasswordEmailSent"));
        }
Beispiel #5
0
        public async Task <IHttpActionResult> RecoverPassword(RecoverPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorsMessages = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage));
                return(ErrorApiResult(1, errorsMessages));
            }
            var user  = _userManager.FindByEmailAsync(model.Email);
            var token = await _userManager.GeneratePasswordResetTokenAsync(user.Result.Id);

            var callbackUrl = String.Format("{0}/recover?email={1}&token={2}", _urlSettings.SiteUrl, model.Email, WebUtility.UrlEncode(token));
            await _userManager.SendEmailAsync(user.Result.Id, "RecoverPassword", callbackUrl);

            return(EmptyApiResult());
        }
        public ActionResult RecoverPassword(RecoverPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                using (var db = new DBContext())
                {
                    var foundUserId = (from u in db.tbl_UserProfile
                                       where u.UserName == model.Email
                                       select u.UserId).FirstOrDefault();

                    if (foundUserId > 0)
                    {
                        bool any = (from j in db.tbl_webpages_Membership
                                    where (j.PasswordVerificationToken == model.ReturnToken) &&
                                    (j.UserId == foundUserId)
                                    select j).Any();
                        if (any == true)
                        {
                            bool resetResponse = WebSecurity.ResetPassword(model.ReturnToken, model.Password);
                            if (resetResponse)
                            {
                                var foundUserName = (from u in db.tbl_UserProfile
                                                     where u.UserName == model.Email
                                                     select u.UserName).FirstOrDefault();

                                WebSecurity.Login(foundUserName, model.Password, false);

                                return(RedirectToAction("Index", "Home"));
                            }
                            else
                            {
                                ModelState.AddModelError("", "Something went wrong!");
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("", "Email and recovery link not maching.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Email address not found.");
                    }
                }
            }

            return(View(model));
        }
        public void CanUserRecoverPasswordTest()
        {
            IMateDAO <Mate> MateDAO  = new MateDAO(_connection);
            Mate            testMate = new Mate();

            testMate.FirstName   = "Samuel";
            testMate.LastName    = "Cunha";
            testMate.UserName    = "******";
            testMate.Password    = "******";
            testMate.Email       = "*****@*****.**";
            testMate.Description = "Quero recuperar a pass";
            testMate.Address     = "Aparecida";
            testMate.Categories  = new[] { Categories.GARDENING };
            testMate.Rank        = Ranks.MATE;
            testMate.Range       = 10;

            Mate returned = MateDAO.Create(testMate);

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes("RQj!O9+Sq|D8XjYa|}kgnk|}ZaQUso)EMF48Fx1~0n~^~%]n|O{NqH(&5RqXbx7");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Email, testMate.Email.ToString())
                }),
                Expires            = DateTime.UtcNow.AddMinutes(10),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var    token         = tokenHandler.CreateToken(tokenDescriptor);
            var    tokenString   = tokenHandler.WriteToken(token);
            String auxResetToken = tokenString;

            PasswordOperations.NewPasswordRequest("*****@*****.**", auxResetToken);

            LoginDAO             loginDAO        = new LoginDAO(_connection);
            RecoverPasswordModel recoverPassword = new RecoverPasswordModel();

            recoverPassword.Email           = "*****@*****.**";
            recoverPassword.Password        = "******";
            recoverPassword.ConfirmPassword = "******";
            recoverPassword.Token           = tokenString;

            Assert.True(loginDAO.RecoverPassword(recoverPassword, returned.Email));

            _fixture.Dispose();
        }
Beispiel #8
0
        public ActionResult RecoverPassword(RecoverPasswordModel Model)
        {
            int userID;

            if (IsResetPasswordRequestValid(Model.AdditionalData, out userID))
            {
                if (ModelState.IsValid)
                {
                    UserRepo.TSP_Users(3, ID: userID, Password: Model.Password);
                    Session.SetUser(UserRepo.GetSingle(userID));
                    HandleStandardMessaging(UserRepo.IsError);
                    return(RedirectToAction("Profile", "Account"));
                }
                return(View("RecoverPassword", Model));
            }
            return(HttpNotFound());
        }
Beispiel #9
0
        public void RecoverPassword(RecoverPasswordModel model)
        {
            var  id   = Guid.Parse(model.UserId);
            User user = _userRepository.Get().FirstOrDefault(x => x.Id == id);

            if (user == null)
            {
                throw new BusinessException("User not found", -2);
            }

            IdentityResult result = _userRepository.ResetPassword(user, model.Password, model.Token);

            if (!result.Succeeded)
            {
                throw new BusinessException("Resetting password failed", -1);
            }
        }
Beispiel #10
0
        public async Task <IActionResult> ResetPasswordWithStamp([FromBody] RecoverPasswordModel model)
        {
            using (var contextProvider = _contextProviderFactory.Create())
            {
                var found =
                    contextProvider.GetTable <AspNetUser>()
                    .Where(t => t.Id == model.UserId &&
                           !(t.IsBanned ?? false) &&
                           t.SecurityStamp == model.Signature &&
                           (t.EmailConfirmed ?? false));

                if (!found.Any())
                {
                    return(this.BadRequestCustom(BadRequestError.UserNotFound));
                }

                if (found.Count() > 1)
                {
                    return(this.BadRequestCustom(BadRequestError.MoreThanOneUserFound));
                }

                var user =
                    found.First();

                var passwordHash =
                    _passwordHasher.HashPassword(user, model.Password);

                var res =
                    await contextProvider.GetTable <AspNetUser>()
                    .Where(t => t.Id == model.UserId &&
                           !(t.IsBanned ?? false) &&
                           t.SecurityStamp == model.Signature &&
                           (t.EmailConfirmed ?? false))
                    .UpdateAsync(netUser => new AspNetUser()
                {
                    PasswordHash = passwordHash
                });

                if (res != 1)
                {
                    throw new InvalidOperationException("Нарушена целостность бд!");
                }

                return(Ok(true));
            }
        }
        public void CanUserRecoverPasswordTest()
        {
            IUserDAO <User> UserDAO  = new UserDAO(_connection);
            User            testUser = new User();

            testUser.Email        = "*****@*****.**";
            testUser.Password     = "******";
            testUser.FirstName    = "Samuel";
            testUser.LastName     = "Cunha";
            testUser.Localization = "Travessa de Figueiredo 44, 4620-784, Torno, Portugal";
            testUser.Image        = "imagePath";

            User returnedUser = UserDAO.Create(testUser);

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes("RQj!O9+Sq|D8XjYa|}kgnk|}ZaQUso)EMF48Fx1~0n~^~%]n|O{NqH(&5RqXbx7");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Email, testUser.Email.ToString())
                }),
                Expires            = DateTime.UtcNow.AddMinutes(10),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var    token         = tokenHandler.CreateToken(tokenDescriptor);
            var    tokenString   = tokenHandler.WriteToken(token);
            String auxResetToken = tokenString;

            PasswordLost.NewPasswordRequest("*****@*****.**", auxResetToken);
            LoginDAO             loginDAO        = new LoginDAO(_connection);
            RecoverPasswordModel recoverPassword = new RecoverPasswordModel();

            recoverPassword.Email           = "*****@*****.**";
            recoverPassword.Password        = "******";
            recoverPassword.ConfirmPassword = "******";
            recoverPassword.Token           = tokenString;

            Assert.True(loginDAO.RecoverPassword(recoverPassword, returnedUser.Email));

            _fixture.Dispose();
        }
Beispiel #12
0
        /// <summary>
        /// Método para recuperar a password
        /// </summary>
        /// <param name="newPass">Nova Password</param>
        /// <param name="email">Email do user que vai alterar a password</param>
        /// <returns>Retorna bool</returns>
        public bool RecoverPassword(RecoverPasswordModel newPass, string email)
        {
            using (SqlCommand cmd = _connection.Fetch().CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "UPDATE dbo.[User] SET Password = @pass, PasswordSalt = @salt " +
                                  "WHERE Email = @email";

                cmd.Parameters.Add("@email", SqlDbType.NVarChar).Value = email;
                var password = PasswordEncrypt.Encrypt(newPass.Password);
                cmd.Parameters.Add("@pass", SqlDbType.NVarChar).Value = password.Item2;
                cmd.Parameters.Add("@salt", SqlDbType.NVarChar).Value = password.Item1;

                newPass.Password = password.Item2;

                cmd.ExecuteNonQuery();
            }
            return(true);
        }
Beispiel #13
0
        public async Task <IHttpActionResult> RecoverPassword(RecoverPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorsMessages = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage));
                return(ErrorApiResult(1, errorsMessages));
            }

            var user = await _userManager.FindByNameAsync(model.Phone);

            await _userManager.RemovePasswordAsync(user.Id);

            var newPassword = await _userManager.GeneratePassword();

            await _userManager.AddPasswordAsync(user.Id, newPassword);

            await _userManager.SendSmsAsync(user.Id, newPassword);

            return(EmptyApiResult());
        }
        public ActionResult Password(RecoverPasswordModel requestModel)
        {
            using (var dataContext = new InnostarModelsContext())
            {
                var recoverRepository = new RecoverPasswordRequestRepository(dataContext);

                var request = recoverRepository._Get(u => u.Id == requestModel.RequestId &&
                                                     u.RequestKey == requestModel.RequestKey &&
                                                     u.IsActive).FirstOrDefault();


                if (request == null)
                {
                    throw new Exception("Данного запроса не существует");
                }

                var userRepository = new ChatUserRepository(dataContext);
                var user           = userRepository._Get(e => e.Id == request.UserId).FirstOrDefault();

                if (user == null)
                {
                    throw new Exception("Произошла ошибка в обработке запроса. Обратитесь в службу поддержки");
                }

                if (!string.IsNullOrEmpty(requestModel.NewPassword))
                {
                    var pu = new PasswordUtility(requestModel.NewPassword.ToCharArray());
                    user.PasswordHash = pu.Hash;
                    user.PasswordSalt = pu.Salt;
                }

                userRepository._Update(user);
                userRepository._Save();

                //request.IsActive = false;
                //recoverRepository.Update(request);
                //recoverRepository.Save();

                return(RedirectToAction("Index", "Home"));
            }
        }
        public async Task <IActionResult> PasswordRecoveryStep2([FromBody] RecoverPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(BadRequest());
            }

            var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);

            if (result.Succeeded)
            {
                return(Ok("Password succesfully reset."));
            }
            return(BadRequest(result));
        }
Beispiel #16
0
        public bool RecoverPasswordToken(RecoverPasswordModel recoverPassword)
        {
            var user = _context.User
                       .Where(u => u.Email == recoverPassword.Email)
                       .Where(u => u.IsActive == true)
                       .SingleOrDefault();

            if (user == null)
            {
                return(false);
            }

            var passwordToken = _tokenService.CreateUserToken(user.Id, _passwordTokenType);


            _context.UserTokens.Add(passwordToken);
            _context.SaveChanges();

            string fullName = user.FirstName + " " + user.LastName;

            var emailMsg = new EmailMessageModel
            {
                ToEmailAddress = user.Email,
                ToName         = fullName,
                Subject        = "Password recovery",
                Body           = string.Format(
                    "To {0}, \n" +
                    "You have requested a password recovery token, please find token attached" +
                    "You must use at the following link: \n" +
                    "PUT user/recover/password \n" +
                    "Body = Token, Password, Email \n" +
                    "Token: {1}"
                    , fullName, passwordToken.TokenValue)
            };

            _mailService.SendEmail(emailMsg);

            return(true);
        }
Beispiel #17
0
        public ActionResult RecoverPassword([FromBody] RecoverPasswordModel model)
        {
            if (model == null ||
                string.IsNullOrWhiteSpace(model.Password) ||
                string.IsNullOrWhiteSpace(model.Token))
            {
                return(CreateResponse("None of the parameters can be null."));
            }

            Validator validator = new Validator();

            List <string> passwordErrors = validator.IsValidPassword(model.Password);

            if (passwordErrors.Count() > 0)
            {
                return(CreateResponse(string.Join("\n", passwordErrors)));
            }

            DataResult <RecoveryRequest> dr = userCore.Recovery(model.Password, model.Token);

            return(CreateResponse(success: dr.Success));
        }
Beispiel #18
0
        public IActionResult ResetPassword(RecoverPasswordModel recoverPasswordModel)
        {
            if (ModelState.IsValid)
            {
                UserDAO userDAO = new UserDAO(_connection);
                User    user    = userDAO.FindUserByEmail(recoverPasswordModel.Email);

                if (user != null && recoverPasswordModel.Email == auxEmail && recoverPasswordModel.Token == auxResetToken)
                {
                    LoginDAO loginDAO = new LoginDAO(_connection);
                    loginDAO.RecoverPassword(recoverPasswordModel, recoverPasswordModel.Email);

                    return(Ok(new SuccessMessageModel("Password alterada com sucesso! Pode fazer login com a password nova")));
                }
                else
                {
                    return(BadRequest(new ErrorMessageModel("O email que introduziu não é o seu ou o token é inválido! Erro!")));
                }
            }

            return(BadRequest(new ErrorMessageModel("Dados não correspondem ao formulário!")));
        }
Beispiel #19
0
        public ActionResult RecoverPassword(RecoverPasswordModel model)
        {
            //
            ViewBag.Popup = false;
            if (ModelState.IsValid)
            {
                MembershipUser user     = Membership.GetUser(model.UserID);
                string         password = Membership.GeneratePassword(6, 0);
                user.ChangePassword(user.GetPassword(), password);

                //Set flag that forces user to change password on next login
                System.Web.Profile.ProfileBase profile = System.Web.Profile.ProfileBase.Create(model.UserID);
                profile.PropertyValues["PasswordReset"].PropertyValue = true;
                profile.Save();

                //Send an email
                EmailGateway esvcs = new EmailGateway();
                esvcs.SendPasswordResetMessage(user.UserName, user.Email, password);
                ViewBag.Popup = true;
            }
            return(View(model));
        }
        public async Task <IActionResult> RecoverPassword(RecoverPasswordModel model)
        {
            var user = await _userService.FindByEmail(model.Email);

            string code = await _userService.GetRecoveryToken(user);

            string recoveryLink = Url.Action("RecoveryLink", "AppUser", new
            {
                UserId = user.Id,
                Code   = code
            }, protocol: HttpContext.Request.Scheme);

            bool finalRes = _userService.ResetPW(user, recoveryLink);

            if (finalRes)
            {
                return(Ok(finalRes));
            }
            else
            {
                return(BadRequest(new { message = "No such user with this email" }));
            }
        }
Beispiel #21
0
        public void GetId_ReturnsUserIdBasedOnEmail()
        {
            const string email = "*****@*****.**";

            UserRegistrationModel userRegistrationModel = new UserRegistrationModel
            {
                Name              = "nume",
                Email             = email,
                Password          = "******",
                ConfirmedPassword = "******",
            };

            userRegistrationModel.Save();

            UserEntity expectedUser = new UserRepository().GetBy(email);

            var actualUser = new RecoverPasswordModel
            {
                Email = email
            };

            Assert.AreEqual(expectedUser.Id, actualUser.GetId());
        }
Beispiel #22
0
        public IActionResult RecoverPasswordToken([FromBody] RecoverPasswordModel recoverPassword)
        {
            var token = _userService.RecoverPasswordToken(recoverPassword);

            if (!token)
            {
                return(BadRequest(new
                {
                    Message = "Unable to obtain a user reset token"
                }));
            }

            return(Ok(new {
                Message = "Please check you inbox for the reset token",
                URI = "user/recover/password",
                HttpType = "PUT",
                Body = new PasswordResetModel
                {
                    Token = "xxxx",
                    Password = "******",
                    Email = recoverPassword.Email,
                }
            }));
        }
Beispiel #23
0
        public ActionResult RecoverPassword(RecoverPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                var response = this.VerifyRecaptcha();
                if (!response)
                {
                    return(View(model));
                }
                ///////////////////////////////////////////////////////////////////////////////////
                ///////////////////////////////////////////////////////////////////////////////////
                //tài khoản phải được kích hoạt rồi mới có thể recover password

                var accountService = IoCConfig.Service <IAccountService>();
                var acc            = accountService.GetAccountByIdentity(model.Username);

                if (!CheckAccount(acc))
                {
                    return(View(model));
                }

                //Đã tồn tại key => check email
                if (!string.IsNullOrEmpty(acc.Account_RecoverPasswordKey) &&
                    acc.Account_RecoverPasswordExpired.HasValue &&
                    acc.Account_RecoverPasswordExpired.Value > DateTime.Now)
                {
                    SetCustomError("Chúng tôi đã gửi email khích hoạt cho bạn. Vui lòng làm theo hướng dẫn trong email.");
                }

                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                //send request email to recover password
                //1. Tạo 1 key lưu vào account table
                //2. Send key đến email user qua link có attach key
                //VD: http://www.alotro.com/RecoverPasswordFinish?key=...
                //3. Trang RecoverPasswordFinish: get key va get luon account info
                //Input new password va confirm password
                //Submit => Update pass

                var key         = Guid.NewGuid().ToString();
                var expired_day = DateTime.Now.AddDays(1);
                acc.Account_RecoverPasswordKey     = key;
                acc.Account_RecoverPasswordExpired = expired_day;
                acc = accountService.Update(acc);

                if (acc != null)
                {
                    //start sending email
                    EmailHelper.SendMail_RecoverPassword(this.ControllerContext, acc);
                    //end sending email
                    SetSuccess("Gửi email thành công! Vui lòng kiểm tra email và làm theo những bước hướng dẫn trong email để khôi phục mật khẩu");
                }
                else
                {
                    SetCustomError("Có lỗi xảy ra. Vui lòng thực hiện lại");
                }
            }

            return(View(model));
        }
 protected override RecoverPasswordResult InternalExecute(
     RecoverPasswordModel model)
 {
     throw new System.NotImplementedException();
 }
Beispiel #25
0
 public ApiResponse RecoverPassword([FromBody] RecoverPasswordModel recoverPasswordModel)
 {
     _authService.RecoverPassword(recoverPasswordModel);
     return(new ApiResponse());
 }