Beispiel #1
0
        public async Task <IActionResult> Register(RegisterViewModel registerViewModel)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName   = registerViewModel.Email,
                    ImageUrl   = registerViewModel.ImageUrl,
                    Email      = registerViewModel.Email,
                    FirstName  = registerViewModel.FirstName,
                    LastName   = registerViewModel.LastName,
                    LockoutEnd = DateTimeOffset.Now,
                    IsBlocked  = false
                };


                var result = await _userManager.CreateAsync(user, registerViewModel.Password);

                if (result.Succeeded)
                {
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var returnUrl = Url.Action("ConfirmEmail", "Home", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);

                    //user.LastTimeLogin = DateTimeOffset.Now;
                    //user.IsActive = true;
                    //await _userManager.UpdateAsync(user);
                    EmailService emailService = new EmailService();
                    await emailService.SendEmailAsync(registerViewModel.Email, "Подтверждение почты", $"Для подтверждения почты перейдите по <a href='{returnUrl}'>ссылке</a>");

                    return(Json(new { isValid = true }));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            return(Json(new
                        { isValid = false, html = HelperForJSON.RenderRazorViewToString(this, "Register", registerViewModel) }));
        }
Beispiel #2
0
        public async Task <IActionResult> ChangePassword(ChangePasswordViewModel changePasswordViewModel)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(User.Identity.Name);

                if (user != null)
                {
                    IdentityResult result = await _userManager.ChangePasswordAsync(user,
                                                                                   changePasswordViewModel.CurrentPassword, changePasswordViewModel.NewPassword);

                    if (result.Succeeded)
                    {
                        //   user.IsActive = false;
                        await _userManager.UpdateAsync(user);

                        await _signInManager.RefreshSignInAsync(user);

                        return(Json(new{ isValid = true }));
                    }
                    else
                    {
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError(string.Empty, error.Description);
                        }

                        return(Json(new { isValid = false, html = HelperForJSON.RenderRazorViewToString(this, "ChangePassword", changePasswordViewModel) }));
                    }
                }
                else
                {
                    return(RedirectToAction("Index"));
                }
            }
            else
            {
                return(View(changePasswordViewModel));
            }
        }
Beispiel #3
0
        public async Task <IActionResult> CreateTag(CreateTagViewModel createTagViewModel)
        {
            try
            {
                IEnumerable <Tag> tagsList = await _unitOfWork.Tag.GetAllAsync();

                var model = _mapper.Map <Tag>(createTagViewModel);
                if (ModelState.IsValid)
                {
                    if (String.IsNullOrEmpty(model.TagTitle) || String.IsNullOrEmpty(model.TagDescription))
                    {
                        ModelState.AddModelError("", "");
                        return(Json(new
                                    { isValid = false, textMessage = "Значение не может быть пустым", html = HelperForJSON.RenderRazorViewToString(this, "CreateTag", createTagViewModel) }));
                    }

                    foreach (var tagLists in tagsList)
                    {
                        if (model.TagTitle == tagLists.TagTitle)
                        {
                            ModelState.AddModelError("", "");
                            return(Json(new
                                        { isValid = false, textMessage = "Недопустимы названия одинаковых меток", html = HelperForJSON.RenderRazorViewToString(this, "CreateTag", createTagViewModel) }));
                        }
                    }

                    await _unitOfWork.Tag.InsertAsync(model);

                    await _unitOfWork.SaveAsync();
                }
                return(Json(new { isValid = true }));
            }
            catch
            {
                return(View());
            }
        }
Beispiel #4
0
        public async Task <IActionResult> ChangeNameProfile(ChangeNameProfileViewModel changeNameProfileViewModel)
        {
            var user = await _userManager.FindByEmailAsync(User.Identity.Name);

            if (changeNameProfileViewModel.FirstName == null || changeNameProfileViewModel.LastName == null)
            {
                return(Json(new { isValid = false, textMessage = "Поля не должны быть пустыми!", html = HelperForJSON.RenderRazorViewToString(this, "ChangeNameProfile", changeNameProfileViewModel) }));
            }
            else
            {
                user.FirstName = changeNameProfileViewModel.FirstName;
                user.LastName  = changeNameProfileViewModel.LastName;
                await _userManager.UpdateAsync(user);

                return(Json(new { isValid = true }));
            }
        }
Beispiel #5
0
        public async Task <IActionResult> Login(string returnUrl, LoginViewModel model)
        {
            string errorMessage = null;

            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                ApplicationUser user = await _userManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    errorMessage = "Указанный пользователь не найден!";
                    ModelState.AddModelError(String.Empty, String.Empty);
                    return(Json(new { isValid = false, textMessage = errorMessage, html = HelperForJSON.RenderRazorViewToString(this, "Login", model) }));
                }
                if (user.IsBlocked == true)
                {
                    errorMessage = "Указанный пользователь не найден!";
                    ModelState.AddModelError(String.Empty, String.Empty);
                    return(Json(new { isValid = false, textMessage = errorMessage, html = HelperForJSON.RenderRazorViewToString(this, "Login", model) }));
                }

                //if (!user.EmailConfirmed)
                //{
                //    errorMessage = "Для входа в аккаунт необходимо подтверждение электронной почты!";
                //    ModelState.AddModelError(String.Empty, String.Empty);
                //    return Json(new { isValid = false, textMessage = errorMessage, html = HelperForJSON.RenderRazorViewToString(this, "Login", model) });
                //}
                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe,
                                                                      lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    if (user.ImageUrl == null)
                    {
                        user.ImageUrl = "standart.jpg";
                    }
                    user.IsActive      = true;
                    user.LastTimeLogin = DateTimeOffset.Now;
                    await _userManager.UpdateAsync(user);

                    return(Json(new { isValid = true, html = HelperForJSON.RenderRazorViewToString(this, "Index", model) }));
                }

                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa",
                                          new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));
                }

                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    errorMessage = "Некорректный ввод логина!";
                    ModelState.AddModelError(String.Empty, String.Empty);
                    return(Json(new { isValid = false, textMessage = errorMessage, html = HelperForJSON.RenderRazorViewToString(this, "Login", model) }));
                }
            }


            // If we got this far, something failed, redisplay form
            return(Json(new { isValid = false, html = HelperForJSON.RenderRazorViewToString(this, "Login", model) }));
        }