public ActionResult Login(LoginViewModel lvm)
        {
            if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
            {
                string userToken = MVCUtils.GetUserToken(lvm.Email, lvm.Psw);

                if (userToken != null)
                {
                    Session["userToken"] = userToken;

                    HttpClient client = MVCUtils.GetClient("");
                    client = MVCUtils.GetClient(Session["userToken"].ToString());
                    ApplicationUserViewModel appUser = JsonConvert.DeserializeObject <ApplicationUserViewModel>(client.GetStringAsync("api/ApplicationUser/GetLoggedUser").Result);

                    Session["userId"]    = appUser.Id;
                    Session["userPhoto"] = appUser.ImgUrl;
                    Session["userName"]  = appUser.UserName;
                    return(RedirectToAction("Home", "User"));
                }

                ViewBag.Message   = "Senha incorreta ou usuário não encontrado";
                ViewBag.publicKey = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];
                return(View(lvm));
            }

            ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);
            ViewBag.publicKey           = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];

            return(View());
        }
Example #2
0
        public virtual async Task <ActionResult> Index(ContactUsModel model)
        {
            if (CurrentSettings.UseGoogleRecaptchaForContactUs)
            {
                ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey;
                if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey))
                {
                    ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
                    return(View(model));
                }
            }

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

            await _userMessagingService.AddAsync(new TblUserMessages()
            {
                Email       = model.Email,
                Message     = model.Message,
                Name        = model.Name,
                ReceiveDate = DateTime.Now,
                Subject     = model.Subject,
                UserId      = WorkContext.CurrentUser?.Id
            });

            SuccessNotification(_localizationService.GetResource("YourMessageHasBeenReceived"));

            return(RedirectToAction("Index"));
        }
Example #3
0
        public ActionResult CheckUserModel(UserModel viewModel)
        {
            //Checks if the user is valid and has agreed to the terms and validated the captcha
            if (viewModel.Agreement && ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
            {
                UserDTO userDTO = new UserDTO
                {
                    Password     = ComputeHash(viewModel.Password),    //Put Hash of password in the database
                    SecretAnswer = ComputeHash(viewModel.SecretAnswer) //Put Hash of secret answer in the database
                };
                foreach (PropertyInfo property in userDTO.GetType()
                         .GetProperties()
                         .Where(property => property.Name != "ID" && property.Name != "Password" && property.Name != "SecretAnswer"))
                {
                    property.SetValue(userDTO, viewModel.GetType().GetProperty(property.Name).GetValue(viewModel).ToString());
                }

                //Submits the user to the database via the service
                _service.Insert(userDTO);

                return(View());
            }
            //User info was not valid, so the model is stored and you are prompted to create the user
            else
            {
                ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);

                ViewBag.publicKey = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];

                TempData["agreement"] = "You have not agreed to our terms and conditions";
                TempData["userModel"] = viewModel;
                return(RedirectToAction("Create"));
            }
        }
Example #4
0
        public virtual async Task <ActionResult> ResetPassword(ResetPasswordModel model)
        {
            var currentLanguage = WorkContext.CurrentLanguage;

            model.Settings        = CurrentSettings;
            model.CurrentLanguage = currentLanguage;

            if (CurrentSettings.UseGoogleRecaptchaForResetPassword && CurrentSettings.ShowRecaptchaAfterNFailedAttempt - 1 <= FailedAttempts)
            {
                ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey;


                if (CurrentSettings.ShowRecaptchaAfterNFailedAttempt <= FailedAttempts)
                {
                    if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey))
                    {
                        IncreaseFailedAttempts();
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
                        return(View(model));
                    }
                }
            }

            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByIdAsync(model.UserId);

                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    IncreaseFailedAttempts();
                    ModelState.AddModelError("Email", _localizationService.GetResource("UserNotExist"));
                    return(View(model));
                }

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

                if (result.Succeeded)
                {
                    EventPublisher.Publish(new UserResetPasswordEvent(user));
                    return(View("ResetPasswordConfirmation"));
                }

                foreach (var error in result.Errors)
                {
                    if (error.ToLower().Trim() == "Invalid token.".ToLower())
                    {
                        ModelState.AddModelError("", _localizationService.GetResource("InvalidToken"));
                    }
                    else
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }

            IncreaseFailedAttempts();
            return(View(model));
        }
Example #5
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
                {
                    if (!ModelState.IsValid)
                    {
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);
                        ViewBag.publicKey           = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];

                        ViewBag.ReturnUrl = returnUrl;
                        return(View(model));
                    }

                    // This doesn't count login failures towards account lockout
                    // To enable password failures to trigger account lockout, change to shouldLockout: true
                    var result =
                        await
                        SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false);

                    switch (result)
                    {
                    case SignInStatus.Success:
                        return(RedirectToLocal(returnUrl));

                    case SignInStatus.LockedOut:
                        return(View("Lockout"));

                    case SignInStatus.RequiresVerification:
                        return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, model.RememberMe }));

                    case SignInStatus.Failure:
                    default:
                        ModelState.AddModelError("", "Invalid login attempt.");
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);
                        ViewBag.publicKey           = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];
                        ViewBag.ReturnUrl           = returnUrl;
                        return(View(model));
                    }
                }

                ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);

                ViewBag.publicKey = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];
                return(View(model));
            }
            catch (Exception)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }
Example #6
0
        public virtual async Task <ActionResult> ForgotPassword(ForgotPasswordModel model)
        {
            var currentLanguage = WorkContext.CurrentLanguage;

            model.Settings        = CurrentSettings;
            model.CurrentLanguage = currentLanguage;

            if (CurrentSettings.UseGoogleRecaptchaForResetPassword && CurrentSettings.ShowRecaptchaAfterNFailedAttempt - 1 <= FailedAttempts)
            {
                ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey;


                if (CurrentSettings.ShowRecaptchaAfterNFailedAttempt <= FailedAttempts)
                {
                    if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey))
                    {
                        IncreaseFailedAttempts();
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
                        return(View(model));
                    }
                }
            }

            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    IncreaseFailedAttempts();
                    ModelState.AddModelError("Email", _localizationService.GetResource("UserNotExist"));
                    return(View(model));
                }

                var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "User", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await _emailService.SendEmailFromTemplateAsync("ResetPassword", _localizationService.GetResource("ResetPassword"), model.Email, new
                {
                    Url          = callbackUrl,
                    UserFullName = user.FirstName + " " + user.LastName
                });

                return(View("ForgotPasswordConfirmation"));
            }

            // If we got this far, something failed, redisplay form
            IncreaseFailedAttempts();
            return(View(model));
        }
Example #7
0
        public ActionResult Enter(UserModel model)
        {
            if (_service.Get(model.ID).Password == ComputeHash(model.Password))
            {
                return(View());
            }

            //If there doesn't exist one, go back to the login screen
            ViewBag.ErrorMessage        = "Username or Password was incorrect. Try again.";
            ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
            ViewBag.publicKey           = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];
            TempData["userModel"]       = model;
            return(RedirectToAction("Login"));
        }
Example #8
0
        public async Task <ActionResult> Register(RegisterViewModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
                {
                    if (IsPhoneNumbersExits(model.PhoneNumber) && IsEmailExits(model.Email))
                    {
                        if (model.Role == "0" && model.UserType == "professional")
                        {
                            ModelState.AddModelError("", "Select user type");
                        }

                        if (ModelState.IsValid)
                        {
                            SendOtp(model.PhoneNumber);
                            TempData["regmodel"] = model;
                            return(RedirectToAction("ConfirmRegistration", "Account"));
                        }
                    }
                    else
                    {
                        if (!IsPhoneNumbersExits(model.PhoneNumber))
                        {
                            ErrorNotification("Phone number already exists.");
                        }

                        if (!IsEmailExits(model.Email))
                        {
                            ErrorNotification("Email already exists.");
                        }
                    }
                }
                var capErr = ReCaptcha.GetLastErrors(this.HttpContext);
                if (capErr != null)
                {
                    ErrorNotification("Oops!! Invalid Captcha.");
                }

                ViewBag.publicKey  = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];
                model.UserRoleList = GetUserTypeList();
                return(View(model));
            }
            catch (Exception)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            var IPAddress = Server.HtmlEncode(Request.UserHostAddress);

            ViewBag.IPAddress = IPAddress;
            var subject    = "Account Registration";
            var instigator = "Registration System";
            var system     = "Account Controller";

            if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    instigator = model.Email;
                    await Logger.CreateNewLog($"Successful registration for {model.Email} on IPAddress {IPAddress}", subject, instigator, system);

                    // await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    // 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 = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    await SMTP.SendNewEmail("*****@*****.**", model.Email, "Basically Prepared", "", "Confirm Account Create", "Please confirm your account by clicking <a href=\"" + callbackUrl + $"\">{callbackUrl}</a>.<br />You can also copy and paste it to your browser if your email does not allow you to click the link.", "NewAccount");

                    ViewBag.RegisteredEmail = model.Email;
                    return(View("RegistrationSuccessful"));
                }
                AddErrors(result);
            }
            await Logger.CreateNewLog($"Failed registration for {model.Email} on IPAddress {IPAddress}", subject, instigator, system);

            ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);

            ViewBag.publicKey = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #10
0
        public virtual async Task <ActionResult> CommentEditor(CommentEditorModel model)
        {
            var isAdmin     = HttpContext.User.IsInRole("Admin");
            var currentUser = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            var currentUserId = currentUser?.Id ?? "";

            if (CurrentSettings.UseGoogleRecaptchaForComment)
            {
                ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey;
                if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey))
                {
                    ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
                    return(View(model));
                }
            }

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

            var published = CurrentSettings.AutoPublishComments;

            if (isAdmin)
            {
                published = model.Published;
            }

            await _commentsService.AddAsync(
                await _commentModelFactory.PrepareTblCommentsAsync(model, currentUser?.Id, published), true);

            if (published || isAdmin)
            {
                TempData["SuccessNotification"] = _localizationService.GetResource("YourCommentSubmitted");
            }
            else
            {
                TempData["SuccessNotification"] = _localizationService.GetResource("YourCommentSubmittedAndPublishAfterReview");
            }

            return(RedirectToAction("CommentEditor", new { postId = model.PostId }));
        }
        public async Task <ActionResult> Create(UserViewModel user)
        {
            if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
            {
                // создаем переменную типа AppUser
                AppUser _user = new AppUser()
                {
                    UserName = user.Name, Email = user.Email
                };
                // Сохраняем в базу
                IdentityResult _result = await UserManager.CreateAsync(_user, user.Password);

                if (_result.Succeeded)
                {
                    // Создаем корневую директорию пользователя
                    _user.CreateMainFolder();
                    // Сохраняем это
                    IdentityResult _res = await UserManager.UpdateAsync(_user);

                    return(RedirectToAction("Index", "File"));
                }
                else
                {
                    AddErrors(_result);
                }
            }

            var captchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);

            if (captchaLastErrors == null)
            {
                ViewBag.Recaptcha = ReCaptcha.GetHtml(ConfigurationManager.AppSettings["ReCaptcha:SiteKey"]);
            }
            else
            {
                ViewBag.RecaptchaLastErrors = captchaLastErrors;
            }

            ViewBag.publicKey = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];
            return(View(user));
        }
        public ActionResult Submit(int id)
        {
            if (!ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]) || !ModelState.IsValid)
            {
                ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);
                return(RedirectToAction("Review", new { id = id }));
            }
            var applicant   = GetCurrentApplicant();
            var application =
                _context.Applications.Where(x => x.Id == id)
                .Include(x => x.StatusHistory)
                .Include(x => x.Forms)
                .FirstOrDefault();

            if (application == null)
            {
                return(RedirectToAction("Index"));
            }
            if (application.Applicants.All(x => x.Id != applicant.Id))
            {
                return(RedirectToAction("Index"));
            }

            // Find Fee Schedule Item
            if (!application.SubmitAndFinalize())
            {
                return(RedirectToAction("Review", new { id = id }));
            }
            if (application.CurrentStatusLog.Status == EApplicationStatus.Submitted)
            {
                GenerateInvoice(application, EInvoicePurpose.InitialPayment);
            }
            _context.SaveChanges();

            return(RedirectToAction("Submitted", new { id = id }));
        }
Example #13
0
        public async Task <ActionResult> Register(RegisterViewModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
                {
                    if (IsPhoneNumbersExits(model.PhoneNumber) && IsEmailExits(model.Email))
                    {
                        if (model.Role == "0" && model.UserType == "professional")
                        {
                            ModelState.AddModelError("", "Select user type");
                        }

                        if (ModelState.IsValid)
                        {
                            //SendOtp(model.PhoneNumber);
                            // TempData["regmodel"] = model;
                            // return RedirectToAction("ConfirmRegistration", "Account");
                            var user = new ApplicationUser
                            {
                                UserName                  = model.PhoneNumber,
                                Email                     = model.Email,
                                LastName                  = model.LastName,
                                FirstName                 = model.FirstName,
                                LastIpAddress             = "192.168.225.1",
                                IsEmailUnsubscribed       = false,
                                IsPhoneNumberUnsubscribed = true,
                                LastLoginDateUtc          = DateTime.UtcNow,
                                CreatedOnUtc              = DateTime.UtcNow,
                                PhoneNumber               = model.PhoneNumber,
                                TwoFactorEnabled          = true
                            };
                            var result = await UserManager.CreateAsync(user, model.Password);

                            if (result.Succeeded)
                            {
                                if (model.UserType.ToLowerInvariant() == "professional")
                                {
                                    await this.UserManager.AddToRoleAsync(user.Id, model.Role);

                                    var doctor = new Doctor {
                                        DoctorId = user.Id, RegistrationNumber = model.RegistrationNumber
                                    };
                                    _doctorService.AddDoctor(doctor);
                                }
                                //gives content to sending thanks email
                                await UserManager.SendEmailAsync(user.Id, "Thank you for registering at Doctor 365", "Thank you!!");

                                await SignInManager.SignInAsync(user, false, false);

                                return(RedirectToAction("Index", "Home"));
                            }
                            string errorNotify = string.Empty;
                            foreach (var item in result.Errors)
                            {
                                errorNotify += item + " ,";
                            }
                            if (!string.IsNullOrWhiteSpace(errorNotify))
                            {
                                ErrorNotification(errorNotify.TrimEnd(','));
                            }

                            ViewBag.ReturnUrl = returnUrl;
                            AddErrors(result);
                        }
                    }
                    else
                    {
                        if (!IsPhoneNumbersExits(model.PhoneNumber))
                        {
                            ErrorNotification("Phone number already exists.");
                        }

                        if (!IsEmailExits(model.Email))
                        {
                            ErrorNotification("Email already exists.");
                        }
                    }
                }
                var capErr = ReCaptcha.GetLastErrors(this.HttpContext);
                if (capErr != null)
                {
                    ErrorNotification("Oops!! Invalid Captcha.");
                }

                ViewBag.publicKey  = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];
                model.UserRoleList = GetUserTypeList();
                return(View(model));
            }
            catch (Exception)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }
Example #14
0
        public virtual async Task <ActionResult> SignUp(SignUpModel model)
        {
            var currentLanguage = WorkContext.CurrentLanguage;
            var countries       = await _countriesService.GetAsSelectListAsync();

            model.UserMustAcceptTerms    = CurrentSettings.ShowAcceptTermsSignUp;
            model.CurrentLanguage        = currentLanguage;
            model.CountriesList          = countries;
            model.ExternalLoginProviders = _externalLoginProviderManager.GetAvailableLoginProvidersInfo();

            if (CurrentSettings.UseGoogleRecaptchaForSignup && CurrentSettings.ShowRecaptchaAfterNFailedAttempt - 1 <= FailedAttempts)
            {
                ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey;

                if (CurrentSettings.ShowRecaptchaAfterNFailedAttempt <= FailedAttempts)
                {
                    if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey))
                    {
                        IncreaseFailedAttempts();
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
                        return(View(model));
                    }
                }
            }

            if (!CurrentSettings.ShowAcceptTermsSignUp)
            {
                ModelState.Remove("AcceptTerms");
            }
            if (!ModelState.IsValid)
            {
                IncreaseFailedAttempts();
                return(View(model));
            }

            var duplicatedEmail = await UserManager.FindByEmailAsync(model.Email);

            if (duplicatedEmail != null)
            {
                ModelState.AddModelError("Email", string.Format(_localizationService.GetResource("DuplicateEmail"), model.Email));
                IncreaseFailedAttempts();
                return(View(model));
            }

            var user = new TblUsers()
            {
                UserName      = model.Email,
                Email         = model.Email,
                RegisterDate  = DateTime.Now,
                FirstName     = model.FName,
                LastName      = model.LName,
                UserCountryId = model.Country,
            };

            var result = await UserManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                EventPublisher.Publish(new UserSignupEvent(user));

                var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                if (CurrentSettings.ConfirmUserEmailAddress)
                {
                    var callbackUrl = Url.Action("ConfirmEmail", "User", new { userId = user.Id, code = code }, Request.Url.Scheme);
                    await _emailService.SendEmailFromTemplateAsync("ConfirmEmail", _localizationService.GetResource("ConfirmAccount"), model.Email, new
                    {
                        Url          = callbackUrl,
                        UserFullName = user.FirstName + " " + user.LastName
                    });

                    return(View("DisplayEmailConfirm"));
                }

                var confirmEmailResult = await UserManager.ConfirmEmailAsync(user.Id, code);

                return(View(confirmEmailResult.Succeeded ? "RegistrationCompleted" : "ErrorMessage"));
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
            IncreaseFailedAttempts();
            return(View(model));
        }
Example #15
0
        public async Task <ActionResult> Register(RegisterViewModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
                {
                    if (model.Role == "0" && model.UserType == "professional")
                    {
                        ModelState.AddModelError("", "Select user type");
                    }

                    if (ModelState.IsValid)
                    {
                        //SendOtp(model.PhoneNumber);
                        //  TempData["regmodel"] = model;
                        //return RedirectToAction("ConfirmRegistration", "Account");
                        var user = new ApplicationUser
                        {
                            UserName                  = model.Email,
                            Email                     = model.Email,
                            LastName                  = model.LastName,
                            FirstName                 = model.FirstName,
                            LastIpAddress             = "192.168.225.1",
                            IsEmailUnsubscribed       = false,
                            IsPhoneNumberUnsubscribed = true,
                            LastLoginDateUtc          = DateTime.UtcNow,
                            CreatedOnUtc              = DateTime.UtcNow,
                            PhoneNumber               = model.PhoneNumber,
                            TwoFactorEnabled          = true
                        };
                        var result = await UserManager.CreateAsync(user, model.Password);

                        if (result.Succeeded)
                        {
                            if (model.UserType == "professional")
                            {
                                await this.UserManager.AddToRoleAsync(user.Id, model.Role);

                                var doctor = new Doctor {
                                    DoctorId = user.Id, RegistrationNumber = model.RegistrationNumber
                                };
                                _doctorService.AddDoctor(doctor);
                            }

                            await SignInManager.SignInAsync(user, false, false);

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

                ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);

                ViewBag.publicKey  = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];
                model.UserRoleList = GetUserTypeList();

                return(View(model));
            }
            catch (Exception)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }
Example #16
0
        public virtual async Task <ActionResult> Login(LoginModel model)
        {
            var currentLanguage = WorkContext.CurrentLanguage;

            model.CurrentLanguage        = currentLanguage;
            model.ExternalLoginProviders = _externalLoginProviderManager.GetAvailableLoginProvidersInfo();

            if (CurrentSettings.UseGoogleRecaptchaForLogin && CurrentSettings.ShowRecaptchaAfterNFailedAttempt - 1 <= FailedAttempts)
            {
                ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey;


                if (CurrentSettings.ShowRecaptchaAfterNFailedAttempt <= FailedAttempts)
                {
                    if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey))
                    {
                        IncreaseFailedAttempts();
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
                        return(View(model));
                    }
                }
            }

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

            var user = UserManager.FindByEmail(model.Email);

            if (CurrentSettings.ConfirmUserEmailAddress)
            {
                if (user != null && !UserManager.IsEmailConfirmed(user.Id))
                {
                    var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "User", new { userId = user.Id, code = code },
                                                 Request.Url.Scheme);
                    await _emailService.SendEmailFromTemplateAsync("ConfirmEmail", _localizationService.GetResource("ConfirmAccount"),
                                                                   model.Email, new
                    {
                        Url          = callbackUrl,
                        UserFullName = user.FirstName + " " + user.LastName
                    });

                    return(View("DisplayEmailConfirm"));
                }
            }

            var signIn = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe,
                                                                 CurrentSettings.UserLockoutEnabled);

            switch (signIn)
            {
            case SignInStatus.Success:
                EventPublisher.Publish(new UserLoggedinEvent(user));
                return(RedirectToLocal(model.ReturnUrl));

            case SignInStatus.LockedOut:
                IncreaseFailedAttempts();
                return(View("Lockout"));

            default:
                IncreaseFailedAttempts();
                ModelState.AddModelError("", _localizationService.GetResource("InvalidLogin"));
                return(View(model));
            }
        }
Example #17
0
        public virtual async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationModel model)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToLocal(model.ReturnUrl));
            }

            var currentLanguage = WorkContext.CurrentLanguage;
            var countries       = await _countriesService.GetAsSelectListAsync();

            model.UserMustAcceptTerms = CurrentSettings.ShowAcceptTermsSignUp;
            model.CurrentLanguage     = currentLanguage;
            model.CountriesList       = countries;

            if (CurrentSettings.UseGoogleRecaptchaForSignup && CurrentSettings.ShowRecaptchaAfterNFailedAttempt - 1 <= FailedAttempts)
            {
                ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey;

                if (CurrentSettings.ShowRecaptchaAfterNFailedAttempt <= FailedAttempts)
                {
                    if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey))
                    {
                        IncreaseFailedAttempts();
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
                        return(View(model));
                    }
                }
            }

            if (!CurrentSettings.ShowAcceptTermsSignUp)
            {
                ModelState.Remove("AcceptTerms");
            }

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

            var duplicatedEmail = await UserManager.FindByEmailAsync(model.Email);

            if (duplicatedEmail != null)
            {
                ModelState.AddModelError("Email", string.Format(_localizationService.GetResource("DuplicateEmail"), model.Email));
                IncreaseFailedAttempts();
                return(View(model));
            }


            // Get the information about the user from the external login provider
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(View("Error"));
            }

            var user = new TblUsers()
            {
                UserName       = loginInfo.Email,
                Email          = loginInfo.Email,
                RegisterDate   = DateTime.Now,
                FirstName      = model.FName,
                LastName       = model.LName,
                UserCountryId  = model.Country,
                EmailConfirmed = true,
                Avatar         = (await DownloadUserAvatar(model.Avatar)).SaveToAppData("socialAvatar.png")
            };
            var result = await UserManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                EventPublisher.Publish(new UserSignupEvent(user));

                result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : true, rememberBrowser : false);

                    EventPublisher.Publish(new UserLoggedinEvent(user));
                    return(RedirectToLocal(model.ReturnUrl));
                }
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
            IncreaseFailedAttempts();
            return(View(model));
        }