Пример #1
0
 public IActionResult Get(string storeName)
 {
     try
     {
         var store = _storeService.GetStore(storeName);
         if (store == null)
         {
             throw new AppException("Витрина недоступна!");
         }
         var hash = AppFileSystem.GetUserMD5(store.UserInfo.Id, store.UserInfo.Login);
         _storeService.AddVisit(store.Id);
         _logger.LogInformation($"Visit store #{store.Id}");
         return(Ok(new
         {
             Store = _mapper.Map <StoreForClientDto>(store),
             Hash = hash
         }));
     }
     catch (AppException ex)
     {
         return(BadRequest(ex.Message));
     }
     catch (Exception ex)
     {
         _logger.LogCritical($"{ex}");
         return(BadRequest("Service error!"));
     }
 }
Пример #2
0
        public async Task <IActionResult> UploadFile(int id)
        {
            try
            {
                var file = Request.Form.Files.FirstOrDefault();
                if (file == null)
                {
                    throw new AppException("Empty file!");
                }
                if (file.Length > _appSettings.MaxImageSize * 1024)
                {
                    throw new AppException("Слишком большое изображени");
                }
                //combine path to user folder using md5 hash
                var userId = Convert.ToInt32(User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value);

                _logger.LogInformation($"User #{userId}, UploadProductPhoto #{id}");


                var userName = User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
                var hash     = AppFileSystem.GetUserMD5(userId, User.Identity.Name);
                //create directory in not exist
                var path = $"{Directory.GetCurrentDirectory()}{_appSettings.PhotoFolder}{hash}";
                //if (!Directory.Exists(path))
                //  Directory.CreateDirectory(path);
                //path += $"\\{id}_p";

                //if (System.IO.File.Exists(path + ".jpg"))
                //  System.IO.File.Delete(path + ".jpg");
                //using (FileStream fstream = new FileStream(path + ".new", FileMode.Create))
                //{
                //  await file.CopyToAsync(fstream);
                //}
                if (!await AppFileSystem.SaveFileAsync(path, $"{id}_p", file))
                {
                    _logger.LogError($"File {path} was not saved!");
                    throw new AppException("Ошибка загрузки файла.");
                }
                path += $"\\{id}_p";
                if (!AppFileSystem.CompressImage(path, _appSettings.PhotoProductSize))
                {
                    _logger.LogError($"File {path} was not compressed and deleted!");
                    throw new AppException("Ошибка загрузки файла.");
                }
                _userService.SetPhotoFlag(userId, id);
                return(Ok(new
                {
                }));
            }
            catch (AppException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (Exception ex)
            {
                _logger.LogCritical($"{ex}");
                return(BadRequest("Service error!"));
            }
        }
Пример #3
0
        public async Task <IActionResult> Authenticate([FromBody] UserDto userDto)
        {
            try
            {
                var user = _userService.Authenticate(userDto.Login, userDto.Password);

                if (user == null)
                {
                    throw new AppException("Неверный логин-пароль!");
                }
                if (user.TimeZoneOffset != userDto.TimeZoneOffset)
                {
                    _userService.UpdateTimeZone(user, userDto.TimeZoneOffset);
                }
                var claims = new[] {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Name),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                };
                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret);
                //var tokenDescriptor = new JwtSecurityToken(
                //  "http://localhost:4200/",
                //  _appSettings.IsUser,
                //  claims,
                //  expires: DateTime.Now.AddMinutes(30),
                //  signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
                //  );
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, user.Login),
                        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    }),
                    //Audience = _appSettings.IsUser,
                    //Issuer = _appSettings.IsUser,
                    Expires            = DateTime.UtcNow.AddDays(_appSettings.PassDaysExpired),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
                };
                //new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
                var token       = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);
                var hash        = AppFileSystem.GetUserMD5(user.Id, user.Login);
                _logger?.LogInformation($"User #{user.Id} was logged.");

                var res = _userService.IncomeBonus(user.Id, _appSettings.BonusTypes.Login, _appSettings.Bonuses.Login, _appSettings.BonusLimitPerDay.Login);

                if (res)
                {
                    _logger?.LogInformation($"User #{user.Id}, {_appSettings.Bonuses.Login} bonus incomes");
                }

                if (user.UseTelegram.HasValue && user.UseTelegram.Value)
                {
                    await _notificationService.SendTelegramNotification(user.TelegramChatId, "Произведен вход в систему.");
                }

                return(Ok(new
                {
                    Token = tokenString,
                    Hash = hash
                }));
            }
            catch (AppException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (Exception ex)
            {
                _logger?.LogCritical($"{ex}");
                return(BadRequest("Service error!"));
            }
        }