예제 #1
0
        public async Task <ResultResponse <IEnumerable <QuestionDto> > > GetQuestionListAsync(int userId)
        {
            try
            {
                var user = await _usersRepository.GetAsync(userId);

                if (user == null)
                {
                    return(ResultResponse <IEnumerable <QuestionDto> > .GetBadResponse(StatusCode.NotFound, "Пользователь не найден"));
                }
                var questionViews = await _questionsViewRepository.GetAsync("WHERE is_active = TRUE");

                var questionMiddleDtos = _mapper.Map <IEnumerable <QuestionFullDto> >(questionViews);              // Конвертируем в промежуточный ДТО
                var questionDtos       = _mapper.Map <IEnumerable <QuestionDto> >(questionMiddleDtos);
                foreach (var q in questionDtos)
                {
                    q.IsVoted = await IsUserVotedInQuestion(userId, q.Id);
                }
                return(ResultResponse <IEnumerable <QuestionDto> > .GetSuccessResponse(questionDtos));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { userId }, GetType().Name, nameof(GetQuestionListAsync));
                return(ResultResponse <IEnumerable <QuestionDto> > .GetInternalServerErrorResponse());
            }
        }
예제 #2
0
        public async Task <ResultResponse> RegisterAsync(UserRegisterDto dto)
        {
            try
            {
                var user = (await _userRepository.GetAsync($"where lower(email) = lower('{dto.Email}')")).FirstOrDefault();
                if (user != null)
                {
                    return(ResultResponse.GetBadResponse(StatusCode.BadRequest, "Пользователь с таким Email уже зарегистрирован"));
                }

                var newUser = _mapper.Map <User>(dto);
                newUser.registered    = DateTime.Now;
                newUser.salt          = GenerateSalt();
                newUser.password_hash = await _passwordHashService.GetPasswordHashWithSalt(dto.Password, newUser.salt);

                var added = await _userRepository.AddAsync(newUser);

                if (added != null)
                {
                    return(ResultResponse.GetSuccessResponse());
                }
                else
                {
                    return(ResultResponse.GetInternalServerErrorResponse());
                }
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, dto, GetType().Name, nameof(RegisterAsync));
                return(ResultResponse.GetInternalServerErrorResponse());
            }
        }
예제 #3
0
        public async Task <ResultResponse <IEnumerable <UserDto> > > GetMembersAsync()
        {
            try
            {
                var users = await _usersRepository.GetAsync("where is_government_member = TRUE");

                var userDtos = _mapper.Map <IEnumerable <UserDto> >(users);
                return(ResultResponse <IEnumerable <UserDto> > .GetSuccessResponse(userDtos));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, null, GetType().Name, nameof(GetMembersAsync));
                return(ResultResponse <IEnumerable <UserDto> > .GetInternalServerErrorResponse());
            }
        }
예제 #4
0
        public async Task <ResultResponse <IEnumerable <AdvertisementDto> > > GetAdvertisementListAsync()
        {
            try
            {
                var advertisementViews = await _advertisementViewsRepository.GetAsync("WHERE is_active = TRUE");

                var advertisementDtos = _mapper.Map <IEnumerable <AdvertisementDto> >(advertisementViews);
                return(ResultResponse <IEnumerable <AdvertisementDto> > .GetSuccessResponse(advertisementDtos));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, null, GetType().Name, nameof(GetAdvertisementListAsync));
                return(ResultResponse <IEnumerable <AdvertisementDto> > .GetInternalServerErrorResponse());
            }
        }
예제 #5
0
        public async Task <ResultResponse <IEnumerable <DebtorFileDto> > > GetListAsync()
        {
            try
            {
                var debtorFiles = await _debtorFilesRepository.GetAsync($"WHERE is_active = TRUE");

                var debtorFileDtos = _mapper.Map <IEnumerable <DebtorFileDto> >(debtorFiles);
                return(ResultResponse <IEnumerable <DebtorFileDto> > .GetSuccessResponse(debtorFileDtos));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, null, GetType().Name, nameof(GetListAsync));
                return(ResultResponse <IEnumerable <DebtorFileDto> > .GetInternalServerErrorResponse());
            }
        }
예제 #6
0
        public async Task <ResultResponse <IEnumerable <LegislationDto> > > GetListAsync()
        {
            try
            {
                var legislations = await _legislationsRepository.GetAsync();

                var legislationDtos = _mapper.Map <IEnumerable <LegislationDto> >(legislations);
                return(ResultResponse <IEnumerable <LegislationDto> > .GetSuccessResponse(legislationDtos));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, null, GetType().Name, nameof(GetListAsync));
                return(ResultResponse <IEnumerable <LegislationDto> > .GetInternalServerErrorResponse());
            }
        }
예제 #7
0
        public async Task <ResultResponse <JwtAuthorizationDto> > LoginAsync(string login, string password)
        {
            try
            {
                var identity = await GetIdentityAsync(login, password);

                if (identity == null)
                {
                    return(ResultResponse <JwtAuthorizationDto> .GetBadResponse(StatusCode.BadRequest, "Неверный логин и(или) пароль"));
                }

                DateTime?endLifeTime = null;
                DateTime?notBefore   = null;
                DateTime?expires     = null;

                if (_authSettings.ValidateLifetime)                 // Если токен валидируется по времени
                {
                    notBefore = DateTime.UtcNow;
                    expires   = notBefore.Value.Add(TimeSpan.FromMinutes(_authSettings.Lifetime));
                }

                // Создаем JWT-токен
                var jwt = new JwtSecurityToken(
                    issuer: _authSettings.Issuer,
                    audience: _authSettings.Audience,
                    notBefore: notBefore,
                    claims: identity.Claims,
                    expires: expires,
                    signingCredentials: new SigningCredentials(_authSettings.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                return(ResultResponse <JwtAuthorizationDto> .GetSuccessResponse(
                           new JwtAuthorizationDto
                {
                    UsedLifetime = _authSettings.ValidateLifetime,
                    EndLifetime = endLifeTime,

                    Token = encodedJwt
                }));
            }
            catch (Exception ex)
            {
                _progressLogger.Error(ex, new { login, password }, GetType().Name, nameof(LoginAsync));
                return(ResultResponse <JwtAuthorizationDto> .GetInternalServerErrorResponse());
            }
        }
예제 #8
0
 public async Task <ResultResponse <DocumentDto> > GetDocumentAsync(int documentId)
 {
     try
     {
         var document = (await _documentViewsRepository.GetAsync($"WHERE id = {documentId} AND is_active = TRUE")).FirstOrDefault();
         if (document == null)
         {
             return(ResultResponse <DocumentDto> .GetBadResponse(StatusCode.NotFound, "Не найден файл с указанным идентификатором"));
         }
         var documentDto = _mapper.Map <DocumentDto>(document);
         return(ResultResponse <DocumentDto> .GetSuccessResponse(documentDto));
     }
     catch (Exception ex)
     {
         _progressLogger.Error(ex, documentId, GetType().Name, nameof(GetDocumentAsync));
         return(ResultResponse <DocumentDto> .GetInternalServerErrorResponse());
     }
 }
예제 #9
0
        /// <summary>
        /// Загрузить файл
        /// </summary>
        /// <param name="file">Файл</param>
        /// <param name="allowedFormats">Разрешенные форматы при загрузке файла. Например, jpg, png</param>
        /// <returns>Результат операции по загрузке файла</returns>
        public async Task <FileOperationResult> UploadFileAsync(FileDto file, string[] allowedFormats = null)
        {
            try
            {
                file.FileName = file.FileName.Replace(' ', '_');                 // Заменяем все пробелы в названии на нижнее подчеркивание

                if (file.FileName.Contains("\\") || file.FileName.Contains("/"))
                {
                    return(new FileOperationResult {
                        IsSuccess = false, ErrorDescription = "Названия файлов не должны содержать слешей (/ и \\)"
                    });
                }
                var splitted      = file.FileName.Split('.');
                var fileExtension = splitted.Length > 0 ? splitted[splitted.Length - 1] : null;                 // Расширение файла
                if (allowedFormats != null &&
                    allowedFormats.Any(x => x.ToLower() == fileExtension.ToLower()) == false)
                {
                    return(new FileOperationResult {
                        IsSuccess = false, ErrorDescription = $"Файл недопустимого расширения. Доступные расширения файлов: {string.Join(", ", allowedFormats)}"
                    });
                }

                if (Directory.Exists(_absolutePath) == false)
                {
                    Directory.CreateDirectory(_absolutePath);
                }

                var    hypotheticalFilePath = Path.Combine(_absolutePath, file.FileName);
                string realUniqueFilePath;                 // Физический путь к файлу (Включает кучу папок, букву диска и т.д.)
                string realFileName;
                if (File.Exists(hypotheticalFilePath))
                {
                    realFileName       = DateTime.Now.ToString("yyyy-MM-dd_mm-ss-fff") + "_" + file.FileName;
                    realUniqueFilePath = Path.Combine(_absolutePath, realFileName);
                }
                else
                {
                    realFileName       = file.FileName;
                    realUniqueFilePath = hypotheticalFilePath;
                }
                string serverFilePath = Path.Combine(_baseAddress, _folder, realFileName);                  // Путь к файлу через сервер (<протокол><домен><путь>)

                await File.WriteAllBytesAsync(realUniqueFilePath, file.Bytes);

                return(new FileOperationResult {
                    IsSuccess = true, FilePath = serverFilePath
                });
            }
            catch (Exception ex)
            {
                _progressLogger?.Error(ex, new { file }, GetType().Name, nameof(UploadFileAsync));
                return(new FileOperationResult {
                    IsSuccess = false, ErrorDescription = "Произошла неизвестная ошибка при загрузке файла"
                });
            }
        }
예제 #10
0
 public async Task <ResultResponse <string> > GetValueAsync(string key)
 {
     try
     {
         var value = (await _valuePairsRepository.GetAsync($"WHERE key='{key}'")).FirstOrDefault()?.value;
         return(ResultResponse <string> .GetSuccessResponse(value));
     }
     catch (Exception ex)
     {
         _progressLogger.Error(ex, key, GetType().Name, nameof(GetValueAsync));
         return(ResultResponse <string> .GetInternalServerErrorResponse());
     }
 }
예제 #11
0
		public async Task<ResultResponse<IEnumerable<PostGetDto>>> GetPostsAsync()
		{
			try
			{
				var posts = await _postsViewRepository.GetAsync();
				var postDtos = _mapper.Map<IEnumerable<PostGetDto>>(posts);
				return ResultResponse<IEnumerable<PostGetDto>>.GetSuccessResponse(postDtos);
			}
			catch (Exception ex)
			{
				_progressLogger.Error(ex, null, GetType().Name, nameof(GetPostsAsync));
				return ResultResponse<IEnumerable<PostGetDto>>.GetInternalServerErrorResponse();
			}
		}