Esempio n. 1
0
        public async Task <UserLoginResponse> Handle(UserLoginCommand input)
        {
            await new UserLoginCommandValidator().ValidateAndThrowAsync(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 expiredTokens = _movieLibContext.UserApiTokens.Where(UserApiToken.IsExpired);

            _movieLibContext.UserApiTokens.RemoveRange(expiredTokens);
            await _movieLibContext.SaveChangesAsync();

            var newToken = new UserApiToken
            {
                UserId             = user.Id,
                ExpirationDateTime = input.RememberMe ? (DateTime?)null : DateTime.Now.AddDays(1)
            };

            await _movieLibContext.UserApiTokens.AddAsync(newToken);

            await _movieLibContext.SaveChangesAsync();

            return(new UserLoginResponse {
                Token = newToken.ApiToken
            });
        }
Esempio n. 2
0
        public async Task <UserLogoutResponse> Handle(UserLogoutCommand input)
        {
            var token = await _movieLibContext.UserApiTokens.FirstOrDefaultAsync(t => t.ApiToken == input.Token);

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

            _movieLibContext.UserApiTokens.Remove(token);
            await _movieLibContext.SaveChangesAsync();

            return(new UserLogoutResponse());
        }
Esempio n. 3
0
        public async Task <AddEditMovieResponse> Handle(AddEditMovieCommand input)
        {
            await new AddEditMovieCommandValidator().ValidateAndThrowAsync(input);

            var token = await _movieLibContext.UserApiTokens.Include(apiToken => apiToken.User)
                        .FirstOrDefaultAsync(apiToken => apiToken.ApiToken == input.Token);

            if (token == null)
            {
                throw new AuthenticationException("Такого токена нет");
            }

            if (UserApiToken.IsExpired.IsSatisfiedBy(token))
            {
                throw new AuthenticationException("Токен истек");
            }

            var user = token.User;

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

            Movie movie;

            if (input.Id == null)
            {
                movie    = _mapper.Map <Movie>(input);
                movie.Id = Guid.NewGuid().ToString();
                movie.CreatedByUserId = user.Id;
                movie.HavePoster      = input.PosterFile != null;

                await _movieLibContext.Movies.AddAsync(movie);

                await _movieLibContext.SaveChangesAsync();
            }
            else
            {
                movie = await _movieLibContext.Movies.FirstOrDefaultAsync(m => m.Id == input.Id);

                if (movie == null)
                {
                    throw new NotFoundException("Фильм не найден");
                }
                if (movie.CreatedByUserId != user.Id)
                {
                    throw new AuthorizationException(
                              "Этот фильм создан другим пользователем, вам запрещено его изменять");
                }

                movie            = _mapper.Map(input, movie);
                movie.HavePoster = input.PosterFile != null;

                _movieLibContext.Movies.Update(movie);
                await _movieLibContext.SaveChangesAsync();
            }

            var posterDirectoryPath = _webHostEnvironment.ContentRootPath + _configuration["PostersPath"];

            if (!Directory.Exists(posterDirectoryPath))
            {
                Directory.CreateDirectory(posterDirectoryPath);
            }

            if (input.PosterFile != null)
            {
                await using var fileStream = new FileStream(
                                posterDirectoryPath + movie.Id,
                                FileMode.Create);
                await input.PosterFile.CopyToAsync(fileStream);
            }
            else if (input.Id != null)
            {
                var filePath = posterDirectoryPath + movie.Id;
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }


            return(new AddEditMovieResponse());
        }