Exemple #1
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ProfileSettingsModel settings = (ProfileSettingsModel)validationContext.ObjectInstance;

            if (!BackgroundColorValid(settings.BackgroundColor))
            {
                return(new ValidationResult("Input a valid background color."));
            }
            if (string.IsNullOrWhiteSpace(settings.DarkThemeEnabled))
            {
                return(new ValidationResult("Invalid theme selection."));
            }
            if (string.IsNullOrWhiteSpace(settings.LogoutThreshold))
            {
                return(new ValidationResult("Logout threshold must be a number."));
            }
            if (!int.TryParse(settings.LogoutThreshold, out int a))
            {
                return(new ValidationResult("Logout threshold must be a number."));
            }
            else
            {
                if (a < 0)
                {
                    return(new ValidationResult("Logout threshold must be greater than one."));
                }
            }
            return(ValidationResult.Success);
        }
        public async Task <ActionResult> _ProfileSettings(ProfileSettingsModel model, HttpPostedFileBase photo)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView(model));
            }

            UserDTO userDto = _mapper.Map <UserDTO>(model);

            if (photo != null)
            {
                userDto.ProfilePhoto = await _imageService.GetImageData(photo);
            }

            OperationDetails result = await _userManagementService.UpdateUserProfileInfo(UserId, userDto);

            if (result.Succeeded)
            {
                TempData["PartialMessageSuccess"] = result.Message;
            }
            else
            {
                TempData["PartialMessageFailure"] = result.Message;
            }

            return(RedirectToAction("_ProfileSettings"));
        }
        public ActionResult ProfileSettings(ProfileSettingsModel model)
        {
            try
            {
                switch (model.FileType)
                {
                case FileType.Document:
                    break;

                case FileType.Image:
                    ImageTools.SaveImage(model.File, model.FileArea, isDefault: true);
                    break;

                case FileType.Archive:
                    break;

                default:
                    break;
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "Во время сохранения изображения произошли ошибки");
            }

            return(View(model));
        }
        public async Task <ActionResult> _ProfileSettings()
        {
            UserDTO userDto = await _userDataService.GetUserInfo(UserId);

            ProfileSettingsModel model = _mapper.Map <ProfileSettingsModel>(userDto);

            return(PartialView(model));
        }
        public ActionResult ProfileSettings()
        {
            ProfileSettingsModel model = new ProfileSettingsModel();

            var result = FileService.Get(x =>
                                         x.IsDefault && x.FileArea == FileArea.Profile && x.FileType == FileType.Image)
                         .FirstOrDefault();

            model.IsEmptyDefaultPicture = result == null;

            return(View(model));
        }
        public async Task<IActionResult> Profile(ProfileSettingsModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            if (!await _captcha.IsCaptchaValidAsync())
            {
                ModelState.AddModelError(_captcha.CaptchaValidationError().Key, _captcha.CaptchaValidationError().Value);
                return View();
            }

            ApplicationUser goliathUser = await _accountRepository.GetUserFromContextAsync(User);

            if (!await _timeouts.CanRequestProfileSettingsUpdateAsync(goliathUser.Id))
            {
                ModelState.AddModelError(string.Empty, "Please wait before updating your profile again.");
                return View();
            }

           #region Simple value updates

            // ** Values which do not need database checking
            goliathUser.BackgroundColor = model.BackgroundColor;
            goliathUser.DarkTheme = model.DarkThemeEnabled;
            goliathUser.LogoutThreshold = int.Parse(model.LogoutThreshold);
            // ** If settings which require a two-factor code are updated.
            bool requiresTwoFactor = false;

            #endregion Simple value updates

            #region Validating email

            if (!string.IsNullOrWhiteSpace(model.NewEmail))
            {
                if (await _accountRepository.DoesEmailExistAsync(model.NewEmail))
                {
                    ModelState.AddModelError(string.Empty, $"The email {model.NewEmail} is currently in use.");
                    return View();
                }
                else
                {
                    goliathUser.UnverifiedNewEmail = model.NewEmail;
                    requiresTwoFactor = true;
                }
            }

            #endregion Validating email

            #region Validating phone number

            if (!string.IsNullOrWhiteSpace(model.NewPhoneNumber))
            {
                if (await _accountRepository.DoesPhoneNumberExistAsync(model.NewPhoneNumber))
                {
                    ModelState.AddModelError(string.Empty, $"The phone number {model.NewPhoneNumber} is currently in use.");
                    return View();
                }
                else
                {
                    goliathUser.UnverifiedNewPhone = model.NewPhoneNumber;
                    requiresTwoFactor = true;
                }
            }

            #endregion Validating phone number

            #region Validating password

            if (!string.IsNullOrWhiteSpace(model.NewPassword))
            {
                if (await _accountRepository.IsPasswordValidAsync(goliathUser, model.NewPassword))
                {
                    ModelState.AddModelError(string.Empty, "Your new password must be different then your previous password.");
                    return View();
                }
                IdentityResult result = await _accountRepository.UpdatePasswordAsync(goliathUser, model.CurrentPassword, model.NewPassword);
                if (!result.Succeeded)
                {
                    _captcha.DeleteCaptchaCookie();
                    ModelState.AddModelError(string.Empty, "Your entry in \"Current Password\" does not match your current password.");
                    return View();
                }
                goliathUser.LastPasswordUpdate = DateTime.UtcNow.ToString();
                requiresTwoFactor = true;
            }

            #endregion Validating password

            #region Check two-factor codes

            if (goliathUser.TwoFactorEnabled && requiresTwoFactor)
            {
                if (string.IsNullOrWhiteSpace(model.TwoFactorCode))
                {
                    _captcha.DeleteCaptchaCookie();
                    ModelState.AddModelError(string.Empty, "Your two-factor code is invalid.");
                    return View();
                }
                if (!await _accountRepository.TwoFactorCodeValidAsync(goliathUser, model.TwoFactorCode))
                {
                    _captcha.DeleteCaptchaCookie();
                    ModelState.AddModelError(string.Empty, "Your two-factor code is invalid.");
                    return View();
                }
            }

            #endregion Check two-factor codes

            #region Sending potential verification emails

            // If all of the user settings are correct then check if we need to send messages to
            // update phone/email.
            if (!string.IsNullOrWhiteSpace(model.NewEmail))
            {
                await _accountRepository.GenerateNewEmailConfirmationTokenAsync(goliathUser, new DeviceParser(GetClientUserAgent(), GetRemoteClientIPv4()));
            }
            if (!string.IsNullOrWhiteSpace(model.NewPhoneNumber))
            {
                await _accountRepository.GenerateNewPhoneConfirmationTokenAsync(goliathUser, new DeviceParser(GetClientUserAgent(), GetRemoteClientIPv4()));
            }

            #endregion Sending potential verification emails

            #region Updating/Caching
            // Update all of the changed values.
            await _accountRepository.UpdateUserAsync(goliathUser);
            await _captcha.CacheNewCaptchaValidateAsync();
            await _timeouts.UpdateRequestAsync(goliathUser.Id, UserRequest.UpdateProfileSettings);
            #endregion Updating/Caching

            ModelState.Clear();
            _logger.LogInformation($"{goliathUser.Id} ({goliathUser.UserName}) - Updated profile settings successfully.");
            TempData[TempDataKeys.Redirect] = RedirectPurpose.SettingsUpdatedSuccess;
            return View();
        }