Esempio n. 1
0
        public async Task <ForgotPasswordResponse> ForgotPasswordAsync(ForgotPasswordRequest request)
        {
            var response = new ForgotPasswordResponse();
            await Task.Run(() => { });

            return(response);
        }
Esempio n. 2
0
    public static void ForgotUserPassword(ForgotPasswordPayload payload, ResponseCallback callback, ResponseFallback fallback)
    {
        HttpClient httpClient = new HttpClient();

        Request request = new Request(HttpClient.Method.POST, Route.FORGOT_PASSWORD_ROUTE, payload);

        httpClient.Request(
            request,
            (statusCode, response) => {
            ForgotPasswordResponse forgotPasswordResponse = Deserialize(response);
            callback(forgotPasswordResponse);
        },
            (statusCode, error) => {
            if (statusCode == StatusCodes.CODE_VALIDATION_ERROR)
            {
                ValidationError validationError = ErrorDeserilizer.DeserializeValidationErrorData(error);
                fallback(statusCode, validationError);
            }
            else
            {
                GenericError genericError = ErrorDeserilizer.DeserializeGenericErrorData(error);
                fallback(statusCode, genericError);
            }
        }
            );
    }
Esempio n. 3
0
        public async Task <ForgotPasswordResponse> ForgotPasswordAsync(ForgotPasswordRequest request)
        {
            var response = new ForgotPasswordResponse();
            var user     = await _users.FirstOrDefaultAsync(d => d.UserName == request.UserName);

            if (user == null)
            {
                return(response.ReturnWithCode(AuthenticationMessageHelper.Code.ForgotPasswordFailedInvalidUser.Value(), AuthenticationMessageHelper.ResponseMessages));
            }
            switch (user.UserStatus)
            {
            case UserStatus.Fired:
                return(response.ReturnWithCode(AuthenticationMessageHelper.Code.ForgotPasswordFailedYouAreFired.Value(), AuthenticationMessageHelper.ResponseMessages));

            case UserStatus.Inactive:
                return(response.ReturnWithCode(AuthenticationMessageHelper.Code.ForgotPasswordFailedYouAreInactive.Value(), AuthenticationMessageHelper.ResponseMessages));
            }
            var token = await SendAndGetForgotPasswordTokenAsync(user);

            await SetEmailTokenAsync(user.Id, token);

            await _unitOfWork.SaveChangesAsync();

            return(response.ReturnWithCode(AuthenticationMessageHelper.Code.ForgotPasswordSuccess.Value(), AuthenticationMessageHelper.ResponseMessages));
        }
Esempio n. 4
0
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordRequest forgotPasswordRequest)
        {
            ForgotPasswordResponse response = new ForgotPasswordResponse();

            try
            {
                var user = await _userManager.FindByEmailAsync(forgotPasswordRequest.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    response.Errors = new List <string> {
                        "User not found or not confirmed email"
                    };
                }
                else
                {
                    var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                    var urlConfirmation = $"{Request.Scheme}://{Request.Host}/account/changepassword/?code={HttpUtility.UrlEncode(code)}";
                    await _emailSender.SendMail(user.Email, "Reset password", $"Please reset your password by <a href='{urlConfirmation}'>clicking here</a>");

                    response.IsSuccess = true;
                }
                return(Ok(response));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Forgot password error: {ex.Message} - Email: {forgotPasswordRequest.Email}");
                response.Errors = new List <string> {
                    ex.Message
                };
                return(Ok(response));
            }
        }
        public async Task <ForgotPasswordResponse> ForgotPassword(ForgotPasswordRequest request)
        {
            var response = new ForgotPasswordResponse();

            UserEntity user;

            using (var uow = _uowFactory.GetUnitOfWork())
            {
                user = await uow.UserRepo.GetUserByEmail(new Infrastructure.Repositories.UserRepo.Models.GetUserByEmailRequest()
                {
                    Email_Address = request.EmailAddress
                });

                uow.Commit();
            }

            if (user != null)
            {
                await _emailService.SendResetPassword(new Models.ServiceModels.Email.SendResetPasswordRequest()
                {
                    UserId = user.Id
                });
            }

            response.Notifications.Add("We have sent a reset password link to your email address if it matches our records", NotificationTypeEnum.Success);
            return(response);
        }
Esempio n. 6
0
        public static ForgotPasswordResponse ForgotPassword(ForgotPasswordRequest request)
        {
            request.mobile_number = Common.GetStandardMobileNumber(request.mobile_number);
            ForgotPasswordResponse response = new ForgotPasswordResponse();

            //string newPassword = TokenGenerator.GenerateResetPassword();
            try
            {
                using (AgentAdminDao dao = new AgentAdminDao())
                {
                    AgentAdmin agentAdmin = dao.FindByMobileNumber(request.mobile_number);
                    if (agentAdmin == null)
                    {
                        MakeNouserResponse(response);
                        return(response);
                    }
                    OTPServices.SendOTPForForgotPassword(response, request.mobile_number, agentAdmin.AgadmID, "A");
                    return(response);
                }
            }
            catch (Exception ex)
            {
                response.MakeExceptionResponse(ex);
                return(response);
            }
        }
        public ForgotPasswordResponse ForgotPassword(ForgotPasswordRequest request)
        {
            request.mobile_number = Common.GetStandardMobileNumber(request.mobile_number);
            ForgotPasswordResponse response = new ForgotPasswordResponse();
            //string newPassword = TokenGenerator.GenerateResetPassword();
            Consumer consumer = null;

            try
            {
                using (UserDao dao = new UserDao())
                {
                    consumer = dao.FindByMobileNumber(request.mobile_number);
                    if (consumer == null)
                    {
                        MakeNouserResponse(response);
                        return(response);
                    }
                    OTPServices.SendOTPForForgotPassword(response, request.mobile_number, consumer.ConsID, "C");
                    return(response);
                }
            }
            catch (Exception ex)
            {
                response.MakeExceptionResponse(ex);
                return(response);
            }
        }
Esempio n. 8
0
        public static void SendOTPForForgotPassword(ForgotPasswordResponse response, string mobileNumber, int userId, string userType)
        {
            if (response == null)
            {
                response = new ForgotPasswordResponse();
            }
            if (response.reset_password == null)
            {
                response.reset_password = new ForgotPasswordDto();
            }
            string otp = SMSService.SendOTP(mobileNumber);

            if (string.IsNullOrWhiteSpace(otp))
            {
                response.code         = 1;
                response.has_resource = 0;
                response.message      = MessagesSource.GetMessage("otp.not.sent");
                return;
            }
            if (SaveOTP(otp, userId, userType))
            {
                response.reset_password.new_password_otp_sent = 1; // state that OTP has been sent.
            }
            response.code         = 0;
            response.has_resource = 1;
            response.message      = MessagesSource.GetMessage("otp.sent");
        }
Esempio n. 9
0
        public ActionResult ResetPassword(string Email)
        {
            ForgotPasswordResponse Response = new ForgotPasswordResponse();
            Users users = new Users();

            try
            {
                Response = objUserManager.resetPassword(Email);

                if (Response.header.ErrorCode == 200)
                {
                    string Body = Helper.PopulateBody(Helper.FirstLetterToUpper(Response.fullName), ConfigurationManager.AppSettings["ResetPasswordEmailTemplate"].ToString());

                    BAL.Helper.Helper.SendEmail(Email, "zeusMetrics", Body);
                    ViewBag.Success_Msg = "A mail on your registered mail is sent. Please check your Email.";
                    return(RedirectToRoute("login"));
                }
                else
                {
                    ViewBag.Error_Msg = Response.header.ErrorMessage;
                    return(View());
                }
            }
            catch (Exception ex)
            {
                ViewBag.Error_Msg = ex.Message.ToString();
                BAL.Common.LogManager.LogError("ResetPassword Post Method", 1, Convert.ToString(ex.Source), Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                return(View());
            }
        }
Esempio n. 10
0
        public async Task <ForgotPasswordResponse> ForgotPasswordAsync(string emailUser)
        {
            ForgotPasswordResponse response = new ForgotPasswordResponse();

            // E-mail validation
            Email            email          = new Email(emailUser);
            EmailValidator   emailValidator = new EmailValidator();
            ValidationResult emailResult    = await emailValidator.ValidateAsync(email);

            if (!emailResult.IsValid)
            {
                response.AddErrorValidationResult(emailResult);
                return(response);
            }

            // Verify is e-mail not exist
            bool emailExist = await _unitOfWork.UserRepository.IsEmailExistsAsync(emailUser);

            if (emailExist == false)
            {
                response.SetError(new ErrorResponse("Email", Msg.EmailDoesnotExist));
                return(response);
            }

            // Persistence
            UserSecurity security = await _unitOfWork.UserSecurityRepository.GetByEmailAsync(email.EmailAddress);

            security.GenerateTokenForgotPassword();
            _unitOfWork.UserSecurityRepository.Update(security);

            // Send mail
            //emailService.SendEmailForgotPassword(email.EmailAddress, security.TokenForgotPassword.Value);

            return(response);
        }
Esempio n. 11
0
        public ForgotPasswordResponse resetPassword(string Email)
        {
            objResponse            Response = new objResponse();
            ForgotPasswordResponse results  = new ForgotPasswordResponse();

            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://zmetricsapi.cruzata.com/auth/resetpassword");

                    //HTTP POST
                    var postTask = client.PostAsJsonAsync <string>("resetpassword", Email);
                    postTask.Wait();

                    var result = postTask.Result;
                    if (result.IsSuccessStatusCode)
                    {
                        var readTask = result.Content.ReadAsAsync <ForgotPasswordResponse>();
                        readTask.Wait();

                        results = readTask.Result;
                    }
                }
            }
            catch (Exception ex)
            {
                results.header.ErrorMessage = ex.Message.ToString();
                BAL.Common.LogManager.LogError("validate User", 1, Convert.ToString(ex.Source), Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
            }

            return(results);
        }
Esempio n. 12
0
        public async Task <ActionResult <ForgotPasswordResponse> > ForgotPassword(ForgotPasswordRequest forgotPasswordRequest)
        {
            var response = new ForgotPasswordResponse();
            var user     = await _userManager.FindByEmailAsync(forgotPasswordRequest.Email);

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

            if (!(await _userManager.IsEmailConfirmedAsync(user)))
            {
                response.Errors = new List <string> {
                    "Not confirmed email"
                };
            }
            else
            {
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var urlConfirmation = $"{Request.Scheme}://{Request.Host}/account/changepassword/?code={HttpUtility.UrlEncode(code)}";

                _emailService.SendMail(_configuration["MailSettingsSmtpNetworkUserName"], user.Email, "Reset password", $"Please reset your password by <a href='{urlConfirmation}'>clicking here</a>");

                response.IsSuccess = true;
            }

            return(Ok(response));
        }
        /// <summary>
        /// Allows the user to reset their password using an asynchronous call. Should be used in
        /// conjunction with the ConfirmPasswordAsync method
        /// </summary>
        public async Task <CodeDeliveryDetailsType> ForgotPasswordAsync()
        {
            ForgotPasswordRequest forgotPassRequest = CreateForgotPasswordRequest();

            ForgotPasswordResponse response = await Provider.ForgotPasswordAsync(forgotPassRequest).ConfigureAwait(false);

            return(response.CodeDeliveryDetails);
        }
Esempio n. 14
0
        private ApiResponse <ForgotPasswordResponse> GetForgotPasswordResponse()
        {
            var response = new ForgotPasswordResponse();

            response.ReasonByErrorMapping.Add("Email/Phone not found with a user account.", "Please make sure you entered the right email or phone number.");
            var apiResponse = response.AsNotFoundApiResponse();

            return(apiResponse);
        }
Esempio n. 15
0
        private async void XFBtnForgotPassword_Clicked(object sender, EventArgs e)
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;
            try
            {
                if (!CrossConnectivity.Current.IsConnected)
                {
                    await DisplayAlert("", "No Network Connection!", "(X)");
                }
                else
                {
                    if (string.IsNullOrEmpty(_objForgotPasswordRequest.emailId))

                    {
                        await DisplayAlert("", "please fill the email first!", "(X)");
                    }
                    else
                    {
                        if (!IsValid)
                        {
                            await DisplayAlert("", "Invalid Email!", "(X)");
                        }
                        else

                        {
                            _objForgotPasswordRequest.mobileNum = string.Empty;
                            _objForgotPasswordResponse          = await _apiService.ForgotPasswordAsync(new Get_API_Url().CommonBaseApi(_baseUrl), false, new HeaderModel(), _objForgotPasswordRequest);

                            var Response = _objForgotPasswordResponse.response;
                            if (Response.statusCode == 200)
                            {
                                await DisplayAlert("", " OTP has been sent to your register emailid !!", "(X)");

                                await App.NavigationPage.Navigation.PushAsync(new ResetPasswordPage());
                            }
                            else
                            {
                                await DisplayAlert("", "Please try again!", "(X)");
                            }
                        }
                    }
                }
                //
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
            }
            finally
            {
                IsBusy = false;
            }
        }
        /// <summary>
        /// Requests forgotten account information when a user cannot rememeber their authentication details.
        /// </summary>
        /// <param name="vm">Account forgot view model instance contain partial account details.</param>
        /// <returns>Response information indicating whether the call was successful or not.</returns>
        public async Task <ForgotPasswordResponse> ForgotPasswordAsync(AccountForgotViewModel vm, CancellationToken ct)
        {
            var response = new ForgotPasswordResponse()
            {
                IsValid = true, Message = "Your password has been sent to your e-mail!"
            };
            await Task.Delay(2000, ct);

            return(response);
        }
Esempio n. 17
0
 public ForgotPasswordPage()
 {
     InitializeComponent();
     NavigationPage.SetHasNavigationBar(this, false);
     _objForgotPasswordRequest  = new ForgotPasswordRequest();
     BindingContext             = _objForgotPasswordRequest;
     _objForgotPasswordResponse = new ForgotPasswordResponse();
     _apiServices = new RestApi();
     _baseUrl     = Settings.Url + Domain.ForgotPasswordApiConstant;
 }
Esempio n. 18
0
        public async Task <IActionResult> ForgotPassword(string email)
        {
            ForgotPasswordResponse response = await _accountService.ForgotPasswordAsync(email);

            if (response.IsValid())
            {
                return(Ok(response));
            }

            return(BadRequest(response.GetErrors()));
        }
Esempio n. 19
0
 public ForgotPasswordPage()
 {
     InitializeComponent();
     // NavigationPage.SetHasNavigationBar(this, false);
     NavigationPage.SetBackButtonTitle(this, "");
     _objForgotPasswordRequest  = new ForgotPasswordRequest();
     this.BindingContext        = _objForgotPasswordRequest;
     _objForgotPasswordResponse = new ForgotPasswordResponse();
     _apiService = new RestApi();
     _baseUrl    = Domain.Url + Domain.ForgotPasswordApiConstant;
 }
Esempio n. 20
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            TurningpointDataComponent dataComponent = new TurningpointDataComponent();
            ForgotPasswordResponse    response      = dataComponent.VerifyUserAnswer(txt_username.Text.ToUpper(), txt_answer.Text.ToUpper());

            if (response.Status == false)
            {
                lbl_password.Text = "Your answer was incorrect. Please contact your administrator for assistance.";
            }
            else
            {
                lbl_password.Text = "Your password is: " + response.Password.ToString();
            }
        }
Esempio n. 21
0
    private static ForgotPasswordResponse Deserialize(object response)
    {
        var responseJson = (string)response;

        var data = fsJsonParser.Parse(responseJson);

        object deserialized = null;

        serializer.TryDeserialize(data, typeof(ForgotPasswordResponse), ref deserialized);

        ForgotPasswordResponse serializedData = deserialized as ForgotPasswordResponse;

        return(serializedData);
    }
        private async void BtnSendEmail_Clicked(object sender, EventArgs e)
        {
            try
            {
                if (!CrossConnectivity.Current.IsConnected)
                {
                    DependencyService.Get <IToast>().Show("No Network Connection!!");
                }
                else
                {
                    if (string.IsNullOrEmpty(_objForgotPasswordRequest.Email))
                    {
                        DependencyService.Get <IToast>().Show("Email is Required!!");
                    }
                    else
                    {
                        if (!IsValid)
                        {
                            DependencyService.Get <IToast>().Show("Email is not in a correct format!");
                        }
                        else
                        {
                            await Navigation.PushPopupAsync(new LoadingPopPage());

                            _objForgotPasswordResponse = await _apiServices.ForgotPasswordAsync(new Get_API_Url().CommonBaseApi(_baseUrl), false, new HeaderModel(), _objForgotPasswordRequest);

                            var Response = _objForgotPasswordResponse;
                            if (Response.StatusCode == 200)
                            {
                                DependencyService.Get <IToast>().Show(Response.Message);
                                await Navigation.PopAllPopupAsync();

                                await App.NavigationPage.Navigation.PushAsync(new ConfirmOTPPage());
                            }
                            else
                            {
                                await Navigation.PopAllPopupAsync();

                                DependencyService.Get <IToast>().Show(Response.Message);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                await Navigation.PopAllPopupAsync();
            }
        }
Esempio n. 23
0
        public object Any(ForgotPassword request)
        {
            var res  = new ForgotPasswordResponse();
            var user = UserAuthRepository.GetUserAuthByUserName(request.Email);

            if (null == user)
            {
                res.Success = false;
                res.Message = "Invalid email address.";
                return(res);
            }

            var secret = Regex.Replace(SessionExtensions.CreateRandomBase62Id(32), @"[^\w\d]", "",
                                       RegexOptions.IgnoreCase);
            var link    = $"{Configuration.Web.Domain}{Configuration.Web.PasswordResetLinkFormat.Fmt(user.Email, secret)}";
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(Configuration.Mail.From));
            message.To.Add(new MailboxAddress(user.Email));
            message.Subject = "[Derprecated] Password Reset";
            message.Body    = new TextPart("html")
            {
                Text =
                    $@"
                <html>
                    <head></head>
                    <body>
                        <p>
                            Click on the following link to reset your password:
                            <br/><br/>
                            <a href=""{
                        link}"">{link
                        }</a>
                            <br/><br/>
                            This link will expire in 4 hours.
                        </p>
                    </body>
                </html>
                "
            };

            Cache.Set($"password:secret:{user.Email}", secret, Expiration);
            SmtpClient.Send(message);

            res.Success = true;
            res.Message = null;

            return(res);
        }
Esempio n. 24
0
        private async void BtnForgotPassSub_Clicked(object sender, EventArgs e)
        {
            try
            {
                if (!CrossConnectivity.Current.IsConnected)
                {
                    DependencyService.Get <IToast>().Show("No Internet Connection!");
                }
                else
                {
                    if (string.IsNullOrEmpty(_objForgotPasswordRequest.EmailId))
                    {
                        DependencyService.Get <IToast>().Show("Please Enter Email !");
                    }
                    else
                    {
                        if (!IsValid)
                        {
                            DependencyService.Get <IToast>().Show("Email is not valid!");
                        }
                        else
                        {
                            await Navigation.PushPopupAsync(new LoadingPopPage());

                            _objForgotPasswordResponse = await _apiServices.ForgotPasswordAsync(new Get_API_Url().ForgotPasswordApi(_baseUrl), false, new HeaderModel(), _objForgotPasswordRequest);

                            if (_objForgotPasswordResponse.Response.StatusCode == 200)
                            {
                                await App.NavigationPage.Navigation.PushAsync(new LoginPage());

                                DependencyService.Get <IToast>().Show(_objForgotPasswordResponse.Response.Message + " " + _objForgotPasswordResponse.Response.Description);
                                await Navigation.PopAllPopupAsync();
                            }
                            else
                            {
                                DependencyService.Get <IToast>().Show(_objForgotPasswordResponse.Response.Message + " " + _objForgotPasswordResponse.Response.Description);
                                await Navigation.PopAllPopupAsync();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                DependencyService.Get <IToast>().Show(_objForgotPasswordResponse.Response.Message + " " + _objForgotPasswordResponse.Response.Description);
                await Navigation.PopAllPopupAsync();
            }
        }
Esempio n. 25
0
        private void setquestion(string name)
        {
            TurningpointDataComponent databasecomp = new TurningpointDataComponent();
            ForgotPasswordResponse    response     = databasecomp.GetUserQuestion(name.ToUpper());

            if (response.Question != null && response.Question != String.Empty)
            {
                txt_question.Text = response.Question.ToString().Trim();
            }
            else
            {
                name = name.ToUpper();
                txt_question.Text = String.Format(
                    "No question was found for username {0}. Please contact your administrator", name);
            }
        }
Esempio n. 26
0
        public ForgotPasswordResponse Handle(ForgotPasswordRequest request)
        {
            var response = new ForgotPasswordResponse();

            response.Errors = Validate(request);

            if (response.HasErrors)
            {
                return(response);
            }


            // updatinti user pass i guida isiusti emaila
            //TODO repositorijoje parasyti metoda, kad gautu pagal emaila ir switchintu passworda bet cia dar ir daugiau xujnios


            return(response);
        }
Esempio n. 27
0
        //[ActionName("ForgotPassword")]
        //public HttpResponseMessage ForgotPassword(string EmailAddress)
        public HttpResponseMessage ForgotPassword()
        {
            string EmailAddress = HttpContext.Current.Request.Form["EmailAddress"];
            var    response     = new ForgotPasswordResponse();

            if (!string.IsNullOrEmpty(EmailAddress))
            {
                MembershipUser currentUser = Membership.GetUser(EmailAddress, false);
                string         newPassword = string.Empty;

                //var user = _db.ProformaUsers.FirstOrDefault(a => a.Email.ToLower() == EmailAddress.ToLower());
                if (null == currentUser)
                {
                    response.Flag    = "false";
                    response.MESSAGE = "Email not exists";
                }
                else
                {
                    newPassword = currentUser.ResetPassword();
                    Guid currentUserId = new Guid(currentUser.ProviderUserKey.ToString());
                    // var tempPass = KeyGenerator.GetUniqueKey(10);
                    var user = _db.ProformaUsers.FirstOrDefault(a => a.AspUserId == currentUserId);
                    user.TempPassword       = newPassword;
                    user.TempPassActiveTill = DateTime.Now.AddDays(1); //Active for one week.
                    _db.Entry(user).State   = System.Data.Entity.EntityState.Modified;
                    _db.SaveChanges();
                    response.Flag              = "true";
                    response.MESSAGE           = "Temporary code generated";
                    response.TemporaryPassword = newPassword;

                    //Send Mail
                    string from = "*****@*****.**", from_name = "Proforma", to = EmailAddress, cc = "", bcc = "", subject = "Forgot Password";
                    string body   = "<div><p>Hello " + EmailAddress + "</p></div><div><p>Your new temporary code is <b>" + newPassword + "</b></p><p>NOTE: This code is valid until <b>" + user.TempPassActiveTill + "</b>. Please use this code for first login and reset your password.</p></div>";
                    bool   isHtml = true;
                    Emails.SendEmail(from, from_name, to, cc, bcc, subject, body, isHtml);
                }
            }
            else
            {
                response.Flag    = "false";
                response.MESSAGE = "Insufficient data";
            }
            return(Request.CreateResponse(HttpStatusCode.OK, response));
        }
Esempio n. 28
0
        public async Task <ForgotPasswordResponse> ForgotPassword(ForgotPasswordRequest request)
        {
            var user = await _applicationUserManager.FindByEmailAsync(request.Username);

            if (user == null)
            {
                return(ForgotPasswordResponse.Fail("Our system don't recognize your email."));
            }
            try
            {
                var token = await _applicationUserManager.GeneratePasswordResetTokenAsync(user);

                var url = $"{request.ConfirmationUrl}?token={EncodeToken(token)}&username={request.Username}";

                var filePath = _hostingEnvironment.ContentRootPath;

                var emailTemplate = System.IO.Path.Combine(filePath, "Template", "Emails", "ForgotPassword.html");
                var emailFile     = System.IO.File.ReadAllText(emailTemplate);
                var emailContent  = ReplaceEmail(emailFile, new Dictionary <string, string> {
                    ["url"] = url
                });

                var wrapperTemplate = System.IO.Path.Combine(filePath, "Template", "Emails", "_Email_Wrapper.html");
                var wrapperFile     = System.IO.File.ReadAllText(wrapperTemplate);
                var result          = ReplaceEmail(wrapperFile, new Dictionary <string, string> {
                    ["emailContent"] = emailContent
                });

                var emailMessage = new EmailMessage
                {
                    To          = request.Username,
                    Subject     = "FindYourData.io Password Reset",
                    HtmlContent = result
                };

                await _emailService.SendEmailAsync(emailMessage);
            }
            catch (Exception e)
            {
                return(ForgotPasswordResponse.Fail("Failed to send email, please try later!"));
            }

            return(ForgotPasswordResponse.Succeed());
        }
Esempio n. 29
0
        public async Task <IActionResult> GenerateTemporaryPassword(ForgotPasswordModel forgotPasswordModel)
        {
            string temporaryPassword = "";
            bool   isEmailSent       = false;
            ForgotPasswordResponse forgotPasswordResponse = null;

            try
            {
                var Email = flightDBContext.FlightUsers.Where(x => x.Username == forgotPasswordModel.Username)
                            .Select(x => x.Email).FirstOrDefault();

                var IsUserExists = flightDBContext.FlightUsers.
                                   Where(x => x.Email == Email &&
                                         x.DateOfBirth == forgotPasswordModel.DateOfBirth)
                                   .Any();
                if (IsUserExists)
                {
                    temporaryPassword = GenerateTemporaryPassword();
                    string             mailBodyContent = BuildMailContentBody(temporaryPassword);
                    List <MailMessage> mailMessages    =
                        GetMailMessage(Email, mailBodyContent);
                    isEmailSent = SendEmails(mailMessages);
                }
                if (isEmailSent && IsUserExists)
                {
                    forgotPasswordResponse = new ForgotPasswordResponse();
                    forgotPasswordResponse.IsUserExists      = IsUserExists;
                    forgotPasswordResponse.TemporaryPassword = temporaryPassword;
                    return(Ok(SerializeIntoJson(forgotPasswordResponse)));
                }
                else
                {
                    forgotPasswordResponse = new ForgotPasswordResponse();
                    forgotPasswordResponse.IsUserExists      = IsUserExists;
                    forgotPasswordResponse.TemporaryPassword = "******";
                    return(Ok(SerializeIntoJson(forgotPasswordResponse)));
                }
            }
            catch (Exception e)
            {
                return(BadRequest("Invalid Request" + e.StackTrace + e.Message));
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            ForgotPasswordResponse response = new ForgotPasswordResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("CodeDeliveryDetails", targetDepth))
                {
                    var unmarshaller = CodeDeliveryDetailsTypeUnmarshaller.Instance;
                    response.CodeDeliveryDetails = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return(response);
        }
        public IHttpActionResult ForgotPassword(ForgotPasswordRequest request)
        {
            var response = new ForgotPasswordResponse();

            try
            {
                var isValidRequest = false;

                var member = MembershipAdapter.GetMember(request.Email);

                if (request.IsValidModel())
                {
                    if (member.Exists())
                    {
                        if (member.ConfirmedRegistration())
                        {
                            isValidRequest = true;
                        }
                    }
                }

                if (isValidRequest)
                {
                    MemberToken memberToken = new MemberToken();

                    memberToken.MemberId = member.Id;
                    memberToken.TokenType = TokenTypes.PasswordReset;
                    memberToken.RequestDate = DateTime.Now.ToUniversalTime();
                    memberToken.ExpirationDate = memberToken.RequestDate.AddHours(ConfigHelper.PasswordResetExpiration);

                    var memberTokens = MembershipAdapter.GetMemberTokens(member.Id, TokenTypes.PasswordReset, true);

                    if (!memberTokens.Any())
                    {
                        memberToken.Token = Guid.NewGuid();

                        memberToken = MembershipAdapter.CreateToken(memberToken);
                    }
                    else
                    {
                        memberToken.Token = memberTokens.ElementAt(0).Token;

                        memberToken = MembershipAdapter.UpdateToken(memberToken);
                    }

                    var email = new ForgotPasswordEmail
                    {
                        DomainName = ConfigHelper.DomainName,
                        DomainBaseUrl = ConfigHelper.DomainBaseUrl,
                        Alias = member.Profile.Alias,
                        Token = memberToken.Token
                    };

                    var emailBuilder = new EmailBuilder(EmailReference.HTML.Templates.Main, EmailReference.HTML.Contents.ForgotPassword);
                    var emailBody = emailBuilder.BuildBody<ForgotPasswordEmail>(email);
                    var emailResult = EmailHelper.SendEmail(ConfigHelper.NoReplayEmailAddress,
                                                            ConfigHelper.DomainName,
                                                            member.Email,
                                                            member.Profile.Alias,
                                                            email.Subject,
                                                            emailBody,
                                                            true);
                    if (emailResult)
                    {
                        response.IsSuccessful = true;
                        response.StatusMessage = "Forgot password succeeded";
                    }

                }
                else
                {
                    response.IsSuccessful = false;
                    response.StatusMessage = "Forgot password was unsuccessful";
                    response.Errors.AddRange(request.GetErrors());
                }
            }
            catch (Exception ex)
            {
                this.Log<ForgotPasswordRequest>(LogCategories.Error, request, ex.Message);

                response.IsSuccessful = false;
                response.StatusMessage = this.StatusMessageForExpection;
                response.Errors.Add(ex.Message);
            }

            return Ok(response);
        }
Esempio n. 32
0
 public ForgotPasswordResponse ForgotPasswordByEmail(string sessionId, string email)
 {
     var response = new ForgotPasswordResponse();
     using (new ApplicationContextScope(new ApplicationContext()))
     {
         ApplicationContext.SetSessionId(sessionId);
         try
         {
             bool accountExists;
             IAccountProvider accountProvider = AccountProviderFactory.GetAccountProvider();
             if (accountProvider.ForgotPasswordByEmail(email, out accountExists))
             {
                 response.IsSuccess = true;
             }
             else if (!accountExists)
             {
                 response.ErrorMessage = email +
                                         " doesn't exist. Please register.";
             }
         }
         catch (Exception exception)
         {
             response.ErrorMessage = "Something is not quite right here. Please try again later.";
             Logger.LogException(exception, Source, "ForgotPasswordByEmail", Severity.Critical);
         }
     }
     return response;
 }