Ejemplo n.º 1
0
 public IActionResult ForgotPassword(ForgotPasswordDTO model)
 {
     try
     {
         var result = ChangeForgottenPassword(model);
         if (result != HttpStatusCode.OK)
         {
             if (result == HttpStatusCode.NotFound)
             {
                 _logger.LogInformation("No existe una cuenta de usuario asociada al e-mail {0}", model.Email);
                 SetTempData("No existe una cuenta de usuario asociada al e-mail ingresado. ", "warning");
                 return(View("ForgotPassword", model));
             }
             else
             {
                 _logger.LogError("Ocurrio un error al recuperar contraseña para el e-mail {0}", model.Email);
                 SetTempData("No fue posible procesar su solicitud. Intente de nuevo más tarde.", "danger");
                 return(View("ForgotPassword", model));
             }
         }
         else
         {
             _logger.LogInformation("El Usuario Existe, Token Creado");
             return(View("ForgotPasswordConfirmation", model));
         }
     }
     catch (Exception ex)
     {
         _logger.LogErrorException(ex, "Ocurrió un error al recuperar contraseña para el email {0}.", model.Email);
         SetTempData("No fue posible procesar su solicitud. Intente de nuevo más tarde.", "danger");
         return(View("ForgotPassword", model));
     }
 }
        public async Task <IActionResult> ForgotPassword(ForgotPasswordDTO forgotPassword)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _userManager.FindByEmailAsync(forgotPassword.Email);

            if (user == null)
            {
                return(NotFound($"Usuário '{forgotPassword.Email}' não encontrado."));
            }
            else
            {
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var resetPassword = new ResetPasswordDTO();
                resetPassword.Code   = code;
                resetPassword.Email  = user.Email;
                resetPassword.UserId = user.Id;
                return(Ok(resetPassword));

                // Comentando o trecho de codigo de envio de email
                //var forgot = await ForgotMainPassword(user);
                //if (forgot.Enviado)
                //return Ok();
                //return Unauthorized(forgot.error);
            }
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> ForgotPassword(
            [FromBody] ForgotPasswordDTO forgotPasswordDTO)
        {
            //Return bad request not "email not found". Could be used to work out which emails exists in the database.
            var user = await _userManager.FindByEmailAsync(forgotPasswordDTO.Email);

            if (user == null)
            {
                return(BadRequest("Invalid Request"));
            }

            var token = await _userManager.GeneratePasswordResetTokenAsync(user);

            var param = new Dictionary <string, string>
            {
                { "token", token },
                { "email", forgotPasswordDTO.Email }
            };

            var callback = QueryHelpers.AddQueryString(forgotPasswordDTO.ClientURI, param);
            //builds the string for the reset password email
            var message = new Message(new string[] { user.Email }, "Reset password token",
                                      callback, null);

            await _emailSender.SendEmailAsync(message);

            return(Ok());
        }
        public async Task <ResultDTO> ForgotPassword(ForgotPasswordDTO forgotPasswordDTO)
        {
            var user = await _userManager.FindByEmailAsync(forgotPasswordDTO.Email);

            if (user == null)
            {
                return(new ResultDTO(false, "User not found", user));
            }

            var token = await _userManager.GeneratePasswordResetTokenAsync(user);

            var result = await ResetPassword(user, token).ConfigureAwait(false);

            if (result.Success == false)
            {
                return(result);
            }

            //TODO
            await _mailService.SendEmailAsync(
                forgotPasswordDTO.Email,
                "Forgot password.",
                "<h1>Acess with your new password and change. </h1>" +
                $"<p>Your new password is: {result.Data} </p>");

            return(new ResultDTO(true, $"A new password has been sent to the email: {forgotPasswordDTO.Email}", null));
        }
        public async Task <IActionResult> ForgotPasswordAsync([FromBody] ForgotPasswordDTO ForgotPasswordDTO)
        {
            Guard.Against.NullItem(ForgotPasswordDTO);

            ApplicationUser applicationUser = await _userManager.FindByNameAsync(ForgotPasswordDTO.UserName);

            if (applicationUser == null)
            {
                return(NotFound(new { message = "No user found with such email, provide a valid email" }));
            }

            IList <UserLoginInfo> externalUserList = await _userManager.GetLoginsAsync(applicationUser);

            if (externalUserList.Count > 0)
            {
                return(StatusCode(401, new { message = "External users not authorized to change password, change password with the login-provider" }));
            }

            await _userManager.RemovePasswordAsync(applicationUser);

            IdentityResult changePasswordResult = await _userManager.AddPasswordAsync(applicationUser, ForgotPasswordDTO.NewPassword);

            if (!changePasswordResult.Succeeded)
            {
                return(BadRequest(new { message = changePasswordResult.GetIdentityResultErrorMessage() }));
            }

            return(Ok(new { message = "Password changed successfully" }));
        }
Ejemplo n.º 6
0
        public string SaveOTP(ForgotPasswordDTO forgotPassword)
        {
            var forgotPasswordItem = _dbContext.ForgotPasswords.FirstOrDefault(x => x.UserId == forgotPassword.UserId);

            if (forgotPasswordItem == null)
            {
                var newforgotPasswordItem = new ForgotPassword();
                newforgotPasswordItem.CreatedDate = forgotPassword.TokenCreationDate;
                newforgotPasswordItem.OTP         = forgotPassword.OTP;
                newforgotPasswordItem.UserId      = forgotPassword.UserId;
                _dbContext.ForgotPasswords.Add(newforgotPasswordItem);
                return(forgotPassword.OTP);
            }
            else
            {
                if (forgotPasswordItem.CreatedDate.AddMinutes(30) > DateTime.Now)
                {
                    return(forgotPasswordItem.OTP);
                }
                else
                {
                    forgotPasswordItem.OTP         = forgotPassword.OTP;
                    forgotPasswordItem.CreatedDate = forgotPassword.TokenCreationDate;
                    return(forgotPassword.OTP);
                }
            }
        }
        public async Task <IActionResult> ForgotPassword(ForgotPasswordDTO forgotPassword)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _userManager.FindByNameAsync(forgotPassword.Email);

            if (user == null)
            {
                return(NotFound($"Usuário '{forgotPassword}' não encontrado."));
            }
            else
            {
                var forgotMail = await ForgotMainPassword(user);

                if (forgotMail.Enviado)
                {
                    return(Ok());
                }

                return(Unauthorized(forgotMail.error));
            }
        }
Ejemplo n.º 8
0
 public async Task <ActionResult> ForgotPassword(FormCollection collection)
 {
     try
     {
         var forgotPasswordViewModel = new ForgotPasswordViewModel();
         if (TryUpdateModel(forgotPasswordViewModel))
         {
             var forgotPasswordDTO = new ForgotPasswordDTO
             {
                 Email = forgotPasswordViewModel.Email,
             };
             var response = _accountService.RequestPasswordReset(forgotPasswordDTO).Result;
             if (response)
             {
                 return(RedirectToAction("ForgotPasswordConfirmation"));
             }
             else
             {
                 ModelState.AddModelError("", "There is a problem with this operation.");
                 return(View());
             }
         }
         else
         {
             return(View());
         }
     }
     catch (Exception)
     {
         ModelState.AddModelError("", "This operation could not be completed, please try again.");
         return(View());
     }
 }
        public void Email_Deve_Ser_Um_testeArrobaTestePontoCom(string email)
        {
            var forgotPasswordDto = new ForgotPasswordDTO {
                Email = email
            };

            Assert.AreEqual(email, forgotPasswordDto.Email);
        }
Ejemplo n.º 10
0
        public async Task ForgotPassword(ForgotPasswordDTO model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            var token = _userManager.GeneratePasswordResetTokenAsync(user);

            // send email with generate token and email
        }
        public void Check_Email_Is_Valid(string email)
        {
            var forgotPasswordDto = new ForgotPasswordDTO {
                Email = email
            };

            forgotPasswordDto.Validate();
            Assert.IsTrue(forgotPasswordDto.Valid);
        }
Ejemplo n.º 12
0
        //HTTP methods for calling the API POST, PUT, GET etc
        public async Task <HttpStatusCode> ForgotPassword(ForgotPasswordDTO forgotPasswordDTO)
        {
            forgotPasswordDTO.ClientURI =
                Path.Combine(_navManager.BaseUri, "resetPassword");

            var result = await _client.PostAsJsonAsync("account/forgotpassword",
                                                       forgotPasswordDTO);

            return(result.StatusCode);
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordDTO data)
        {
            if (ModelState.IsValid)
            {
                await personalCabinetService.ForgotPassword(data, "link to form with ResetPasswordDTO");

                await unitOfWork.SaveChanges();

                return(NoContent());
            }
            return(Conflict(ModelState));
        }
Ejemplo n.º 14
0
        public async Task <bool> ForgotPassword([FromBody] ForgotPasswordDTO forgotPasswordDTO)
        {
            UserFilter userFilter = new UserFilter()
            {
                Username = forgotPasswordDTO.Username,
                Email    = forgotPasswordDTO.Email
            };

            await this.userService.ForgotPassword(userFilter);

            return(true);
        }
Ejemplo n.º 15
0
        public bool VerifyUser(ForgotPasswordDTO forgotPasswordDTO)
        {
            bool isValid = false;

            var userProfile = db.UserProfiles.FirstOrDefault(Usr => Usr.Email == forgotPasswordDTO.Email);

            if (userProfile != null && userProfile.Membership.IsConfirmed.GetValueOrDefault(false))
            {
                isValid = true;
            }

            return(isValid);
        }
        public void Check_Email(string email)
        {
            var forgotPasswordDto = new ForgotPasswordDTO();

            Assert.IsNull(forgotPasswordDto.Email);

            forgotPasswordDto.Email = email;

            Assert.AreEqual(email, forgotPasswordDto.Email);

            forgotPasswordDto.Validate();
            Assert.IsTrue(forgotPasswordDto.Invalid);
        }
        public async Task <ActionResult> ForgotPassword([FromBody] ForgotPasswordDTO model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user != null)
            {
                string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);

                SendForgotPasswordEmail(user, resetToken);
            }

            return(Ok());
        }
Ejemplo n.º 18
0
 public IHttpActionResult ForgotPassword([FromBody] ForgotPasswordDTO forgotPasswordDTO)
 {
     try
     {
         if (forgotPasswordDTO == null)
         {
             throw new ArgumentNullException("NULL");
         }
         return(Ok(_loginService.ForgotPassword(forgotPasswordDTO)));
     }
     catch (PlatformModuleException exception)
     {
         return(Ok(ResponseHelper.CreateResponseDTOForException(exception.Message)));
     }
 }
        public async Task <bool> RequestPasswordReset(ForgotPasswordDTO forgotPassword)
        {
            var    content = JsonConvert.SerializeObject(forgotPassword);
            string uri     = $"{_baseUrl}/ExpectingEndPoint/";
            var    res     = await _httpClient.PostAsync(uri, new StringContent(content, Encoding.UTF8, "application/json")).ConfigureAwait(false);

            var textData = await res.Content.ReadAsStringAsync();

            if (res.IsSuccessStatusCode)
            {
                return(JsonConvert.DeserializeObject <bool>(textData));
            }
            var errorMessage = ParseErrorResponse(textData);

            throw new Exception(errorMessage);
        }
Ejemplo n.º 20
0
        public ActionResult ForgotPassword(ForgotPasswordDTO model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            string errorMsg = string.Empty;
            bool   resetUserPasswordStatus = UserDetailsFacade.ResetUserPassword(model.Email, out errorMsg);

            model.FPStatusMessage = resetUserPasswordStatus ?
                                    "An email has been sent to your registered email with new code" : "The server encountered an error processing password reset. Please try again later.";

            model.FPStatus = true;
            return(View("~/Views/Account/ForgotPassword.cshtml", model));
        }
Ejemplo n.º 21
0
        public ResponseDTO ForgotPassword(ForgotPasswordDTO forgotPasswordDTO)
        {
            ResponseDTO responseDTO = new ResponseDTO();

            if (forgotPasswordDTO.LoginType == LoginType.VLC)
            {
                VLC vLC = unitOfWork.VLCRepository.GetByUserName(forgotPasswordDTO.UserName);
                if (vLC != null)
                {
                    string otp = OTPGenerator.GetSixDigitOTP();
                    vLC.Pin = otp;
                    this.SendOTP(otp, vLC.Contact, NatrajComponent.VLC);
                    unitOfWork.VLCRepository.Update(vLC);
                    unitOfWork.SaveChanges();
                    responseDTO.Status  = true;
                    responseDTO.Message = string.Format("A OTP has been sent to registered mobile number - {0} OTP -{1}", vLC.Contact, vLC.Pin);
                    responseDTO.Data    = new object();
                }
                else

                {
                    throw new PlatformModuleException("The User Name Does Not Exist");
                }
            }
            else if (forgotPasswordDTO.LoginType == LoginType.DistributionCenter)
            {
                DistributionCenter distributionCenter = unitOfWork.DistributionCenterRepository.GetDistributionCenterByMobileNumber(forgotPasswordDTO.UserName);
                if (distributionCenter != null)
                {
                    string otp = OTPGenerator.GetSixDigitOTP();
                    distributionCenter.Pin = otp;
                    this.SendOTP(otp, distributionCenter.Contact, NatrajComponent.DC);
                    unitOfWork.DistributionCenterRepository.Update(distributionCenter);
                    unitOfWork.SaveChanges();
                    responseDTO.Status  = true;
                    responseDTO.Message = string.Format("A OTP has been sent to registered mobile number - {0},OTP-{1}", distributionCenter.Contact, distributionCenter.Pin);
                    responseDTO.Data    = new object();
                }
                else

                {
                    throw new PlatformModuleException("The User Name Does Not Exist");
                }
            }
            return(responseDTO);
        }
Ejemplo n.º 22
0
        public bool ChangeForgottenPassword(ForgotPasswordDTO model)
        {
            var user = _uow.UsuarioRepository.Find(x => x.Email == model.Email);

            if (user != null)
            {
                //Envío mail pass temporal y link para cambio...
                try
                {
                    var tokenGuid = Guid.NewGuid().ToString();
                    var token     = new UsuarioToken()
                    {
                        UsuarioId       = user.UsuarioId,
                        FechaExpiracion = DateTime.Now.AddMinutes(Convert.ToDouble(Helper.Parametro.GetValue("TiempoExpiracionTokenMail"))),
                        Usado           = false,
                        Token           = tokenGuid
                    };

                    var mailModel = new MailUsuarioModel()
                    {
                        TokenUrl        = tokenGuid,
                        UsuarioApellido = user.Apellido,
                        UsuarioNombre   = user.Nombre,
                        Email           = user.Email
                    };

                    //Envio mail de contraseña olvidada...
                    sender.SendMailForgotPassword(mailModel);

                    _uow.UsuarioTokenRepository.Create(token);
                    _uow.UsuarioTokenRepository.Save();
                    _logger.LogInformation("Envio de email correctamente");
                    return(true);
                }
                catch (Exception ex)
                {
                    _logger.LogErrorException(ex, "[Token-Mail] - Ocurrió un error al intentar enviar EMAIL para restablecer contraseña olvidada.");
                    throw;
                }
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 23
0
        public IHttpActionResult Forgotpassword(ForgotPasswordDTO dto)
        {
            var customer = new CustomerBO().GetCustomer(new Customer {
                MobileNo = dto.MobileNo
            });

            if (customer != null && customer.OTP == dto.OTP)
            {
                customer.Password = dto.NewPassword;
                new CustomerBO().SaveCustomer(customer);

                return(Ok("Password updated...!"));
            }
            else
            {
                return(NotFound());
            }
        }
Ejemplo n.º 24
0
        public IHttpActionResult Forgotpassword(ForgotPasswordDTO forgot)
        {
            var customer = new CustomerBO().GetCustomer(new Customer {
                MobileNo = forgot.MobileNo
            });

            if (customer != null && customer.OTP == forgot.OTP)
            {
                customer.Password = forgot.NewPassword;
                new CustomerBO().SaveCustomer(customer);

                return(Ok("Password updated...!"));
            }
            else
            {
                return(Ok(UTILITY.FAILURESTATUS));
            }
        }
Ejemplo n.º 25
0
        public ActionResult ForgotPassword(ForgotPasswordDTO model)
        {
            if (ModelState.IsValid)
            {
                using (HttpClientWrapper httpClient = new HttpClientWrapper(Session))
                {
                    //Call confirm account API method
                    var responseMessage = httpClient.PostAsJsonAsync("/api/AccountAPI/VerifyUser", model).Result;
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        var isValid = JsonConvert.DeserializeObject <bool>(responseMessage.Content.ReadAsStringAsync().Result);
                        if (!isValid)
                        {
                            // Don't reveal that the user does not exist or is not confirmed
                            return(View("ForgotPasswordConfirmation"));
                        }
                        else
                        {
                            //Generate and send a reset password token to the users email.
                            var responseMessage2 = httpClient.PostAsJsonAsync("/api/AccountAPI/ResetPasswordToken", model).Result;
                            //If registration worked, then need to send email confirmation
                            if (responseMessage2.IsSuccessStatusCode)
                            {
                                var confirmationToken = JsonConvert.DeserializeObject <string>(responseMessage2.Content.ReadAsStringAsync().Result);
                                var confURL           = WebUI.Common.Common.GetDomainFromRequest(HttpContext.Request) + "/Account/ResetPassword/" + confirmationToken.ToString();
                                MessagingService.PasswordReset(model.Email, confURL);

                                return(RedirectToAction("ForgotPasswordConfirmation", "Account"));
                            }
                            else
                            {
                                var error = JsonConvert.DeserializeObject <System.Web.Http.HttpError>(responseMessage2.Content.ReadAsStringAsync().Result);

                                ModelState.AddModelError(String.Empty, error.Message);
                            }
                        }
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 26
0
        public ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            if (!string.IsNullOrEmpty(model.Email))
            {
                var ASPUser = UserManager.FindByName(model.Email);
                //bool confirm = UserManager.IsEmailConfirmed(user.Id);
                //if (user == null || !confirm)
                //{
                //    // Don't reveal that the user does not exist or is not confirmed
                //    return View("ForgotPasswordConfirmation");
                //}
                var user = db.Users.Where(c => c.Email == model.Email).FirstOrDefault();
                if (user == null || ASPUser == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }
                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                string            code              = UserManager.GeneratePasswordResetToken(ASPUser.Id);
                var               callbackUrl       = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                ForgotPasswordDTO forgotPasswordDTO = new ForgotPasswordDTO()
                {
                    FName       = user.FName,
                    LName       = user.LName,
                    MName       = user.MName,
                    callbackUrl = callbackUrl
                };
                EmailTemplate Email     = new EmailTemplate();
                string        path      = @"~/Common/ForgotPasswordEmailTemplate.html";
                var           emailHtml = Email.ReadTemplateEmail(forgotPasswordDTO, path);
                GmailSender.SendEmail("*****@*****.**", "Serious!1", new List <string>()
                {
                    model.Email
                }, "Reset Password", emailHtml, null);

                UserManager.SendEmailAsync(ASPUser.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                return(RedirectToAction("ForgotPasswordConfirmation", "Account"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 27
0
 public HttpStatusCode ChangeForgottenPassword([FromBody] ForgotPasswordDTO model)
 {
     try
     {
         var result = _pass.ChangeForgottenPassword(model);
         if (result)
         {
             return(HttpStatusCode.OK);
         }
         else
         {
             return(HttpStatusCode.NotFound);
         }
     }
     catch (Exception ex)
     {
         return(HttpStatusCode.BadRequest);
     }
 }
        public async Task <IActionResult> ForgotPassword(
            [FromServices] IAuthenticationService _services,
            [FromBody] ForgotPasswordDTO forgotPasswordDTO)
        {
            forgotPasswordDTO.Validate();
            if (forgotPasswordDTO.Invalid)
            {
                return(BadRequest(new ResultDTO(false, "Wrong email, please verify and try again.", forgotPasswordDTO.Notifications)));
            }

            var result = await _services.ForgotPassword(forgotPasswordDTO);

            if (result.Success == false)
            {
                return(BadRequest(result));
            }

            return(Ok(result));
        }
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordDTO model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            AppUser user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(BadRequest(Errors.AddErrorToModelState("user_not_found", "Invalid email address", ModelState)));
            }
            var emailConfirmationToken = await _userManager.GeneratePasswordResetTokenAsync(user);

            var tokenVerificationUrl = Url.Action("ResetPassword", "Accounts", new { id = user.Id, token = emailConfirmationToken }, Request.Scheme);

            await _messageService.Send(user.Email, "Reset Password", $"Please reset your password by using this: \"{ emailConfirmationToken}\"");

            return(Ok("Check your email!"));
        }
Ejemplo n.º 30
0
        public async Task <bool> ForgotPassword(ForgotPasswordDTO forgotPasswordDTO)
        {
            if (forgotPasswordDTO?.Username != null && forgotPasswordDTO?.NewPassword != null)
            {
                var user = await GetBy(f => f.Username == forgotPasswordDTO.Username);

                if (user?.Id > 0)
                {
                    user.Password = forgotPasswordDTO.NewPassword;
                    var isUpdated = await Update(user);

                    if (isUpdated > 0)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }