public async Task <DiaryAddRecordResponse> Handle(DiaryAddRecordCommand input)
        {
            await new DiaryAddRecordCommandValidator().ValidateAndThrowAsync(input);

            var tokenString = _httpContextAccessor.HttpContext.GetJwtToken();
            var user        = await _userManager.Users.FirstOrDefaultAsync(u =>
                                                                           u.UserJwtTokens.Any(jwtToken => jwtToken.Token == tokenString));

            if (user == null)
            {
                throw new NotFoundException("Пользователь не найден");
            }

            var diaryRecord = await _arterialPressureContext.DiaryRecords.FirstOrDefaultAsync(record =>
                                                                                              record.UserId == user.Id && record.Date == input.Date && record.IsMorning == input.IsMorning);

            if (diaryRecord != null)
            {
                diaryRecord = _mapper.Map(input, diaryRecord);
                _arterialPressureContext.DiaryRecords.Update(diaryRecord);
            }
            else
            {
                diaryRecord        = _mapper.Map <DiaryRecord>(input);
                diaryRecord.UserId = user.Id;
                await _arterialPressureContext.AddAsync(diaryRecord);
            }

            await _arterialPressureContext.SaveChangesAsync();

            return(new DiaryAddRecordResponse());
        }
        public async Task <UserSendResetPasswordEmailResponse> Handle(UserSendResetPasswordEmailCommand input)
        {
            await new UserSendResetPasswordEmailCommandValidator().ValidateAndThrowAsync(input);

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

            if (user == null)
            {
                throw new NotFoundException("Пользователь с таким Email не найден");
            }

            var passwordResetToken = await _userManager.GeneratePasswordResetTokenAsync(user);

            var token = new UserResetPasswordToken
            {
                Id      = Guid.NewGuid().ToString(),
                UserId  = user.Id,
                Token   = passwordResetToken,
                ValidTo = DateTime.Now + TimeSpan.FromDays(1)
            };

            await _arterialPressureContext.UserResetPasswordTokens.AddAsync(token);

            await _arterialPressureContext.SaveChangesAsync();

            //TODO: Подумать. Возможно не стоит дожидаться отправки письма
            var url = HttpUtility.HtmlEncode($"{input.ChangePasswordUrl}{token.Id}");
            await _emailSender.SendEmailAsync(input.Email, "Смена пароля",
                                              $"Чтобы сменить пароль перейдите по ссылке: <a href='{url}'>link</a>");

            return(new UserSendResetPasswordEmailResponse());
        }
Пример #3
0
        public async Task <UserLogoutResponse> Handle(UserLogoutCommand input)
        {
            var tokenString = _httpContextAccessor.HttpContext.GetJwtToken();
            var token       = await _arterialPressureContext.UserJwtTokens.FirstOrDefaultAsync(t => t.Token == tokenString);

            if (token == null)
            {
                throw new NotFoundException("Такого токена не существует");
            }

            _arterialPressureContext.UserJwtTokens.Remove(token);
            await _arterialPressureContext.SaveChangesAsync();

            return(new UserLogoutResponse());
        }
Пример #4
0
        public async Task <UserLoginResponse> Handle(UserLoginCommand input)
        {
            var user = await _userManager.FindByEmailAsync(input.Email);

            //Возвращаем одинаковые ошибки, избегаем подбора
            if (user == null)
            {
                throw new AuthenticationException("Неверный email или пароль");
            }

            var isPasswordOk = await _userManager.CheckPasswordAsync(user, input.Password);

            if (!isPasswordOk)
            {
                var identityResult = await _userManager.AccessFailedAsync(user);

                throw !identityResult.Succeeded
                    ? (Exception) new IdentityResultException(identityResult)
                    : new AuthenticationException("Неверный email или пароль");
            }

            var tokenString = await _jwtGetTokenStringForUserHandler.Handle(user);

            await _arterialPressureContext.UserJwtTokens.AddAsync(new UserJwtToken
            {
                UserId             = user.Id,
                Token              = tokenString,
                ExpirationDateTime = input.RememberMe ? (DateTime?)null : DateTime.Now.AddDays(1)
            });

            await _arterialPressureContext.SaveChangesAsync();

            return(new UserLoginResponse {
                Token = tokenString, EmailConfirmed = user.EmailConfirmed
            });
        }