コード例 #1
0
        public void AddPhoto_Unauthorized_UserClaims_ReturnsUnauthorized()
        {
            var userId = 1;

            _repoMock.Setup(x => x.GetUser(userId)).ReturnsAsync(GetFakeUserList().FirstOrDefault(x => x.Id == userId));

            var content  = "Hello World from a Fake File";
            var fileName = "test.pdf";
            var ms       = new MemoryStream();
            var writer   = new StreamWriter(ms);

            writer.Write(content);
            writer.Flush();
            ms.Position = 0;
            _fileMock.Setup(_ => _.OpenReadStream()).Returns(ms);
            _fileMock.Setup(_ => _.FileName).Returns(fileName);
            _fileMock.Setup(_ => _.Length).Returns(ms.Length);

            var file = _fileMock.Object;

            var userPhotoForCreationDto = new UserPhotoForCreationDto()
            {
                Url      = "*****@*****.**",
                PublicId = "*****@*****.**",
                File     = file
            };

            var result = _photosController.AddPhotoForUser(userId, userPhotoForCreationDto).Result;

            Assert.IsType <UnauthorizedResult>(result);
        }
コード例 #2
0
        public async Task <UserPhotoForReturnDto> UploadProfilePhoto(FileUploadDto uploadDto)
        {
            var claimId = int.Parse(httpContextAccessor.HttpContext.User?.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value);

            if (claimId != uploadDto.AnnounceId)
            {
                throw new RestException(HttpStatusCode.BadRequest, new { AlreadyExist = Messages.OperationDenied });
            }

            var checkAnnounceById = await userDal.GetAsync(x => x.Id == uploadDto.AnnounceId);

            if (checkAnnounceById == null)
            {
                throw new RestException(HttpStatusCode.BadRequest, new { NotFound = Messages.UserNotFound });
            }

            var uploadFile = await upload.Upload(uploadDto.File, "userprofile");

            var mapForCreate = new UserPhotoForCreationDto();

            mapForCreate.Name      = uploadFile.Name;
            mapForCreate.FullPath  = uploadFile.FullPath;
            mapForCreate.UserId    = uploadDto.AnnounceId;
            mapForCreate.IsConfirm = false;
            mapForCreate.IsMain    = false;
            var mapForDb    = mapper.Map <UserPhoto>(mapForCreate);
            var createPhoto = await userPhotoDal.Add(mapForDb);

            return(mapper.Map <UserPhoto, UserPhotoForReturnDto>(createPhoto));
        }
コード例 #3
0
        public async Task <UserPhotoForReturnDto> MakeMainPhotoAsync(UserPhotoForCreationDto creationDto, int userId)
        {
            var claimId = int.Parse(httpContextAccessor.HttpContext.User?.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value);

            if (claimId != userId)
            {
                throw new RestException(HttpStatusCode.BadRequest, new { AlreadyExist = Messages.OperationDenied });
            }

            var checkByIdFromRepo = await userPhotoDal.GetAsync(x => x.Id == creationDto.Id);

            if (checkByIdFromRepo == null)
            {
                throw new RestException(HttpStatusCode.BadRequest, new { NotFound = Messages.NotFound });
            }

            var mainPhotoFromRepo = await userPhotoDal.GetAsync(x => x.IsMain == true && x.UserId == creationDto.UserId);

            if (mainPhotoFromRepo != null)
            {
                mainPhotoFromRepo.IsMain = false;
                await userPhotoDal.Update(mainPhotoFromRepo);
            }

            var mapForUpdate = mapper.Map(creationDto, checkByIdFromRepo);
            var updatePhoto  = await userPhotoDal.Update(mapForUpdate);

            return(mapper.Map <UserPhoto, UserPhotoForReturnDto>(updatePhoto));
        }
コード例 #4
0
        public ActionResult AddUserPhoto(int userId, [FromForm] UserPhotoForCreationDto userPhotoForCreationDto)
        {
            UsersContext _context = new UsersContext();
            var          user     = _userDal.GetUserById(userId);

            if (user == null)
            {
                return(BadRequest("Cloud not find the user."));
            }
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (currentUserId != user.Id)
            {
                return(Unauthorized());
            }
            var file         = userPhotoForCreationDto.File;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams
                    {
                        File = new FileDescription(file.Name, stream)
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }
            userPhotoForCreationDto.Url      = uploadResult.Uri.ToString();
            userPhotoForCreationDto.PublicId = uploadResult.PublicId;
            var photo = _mapper.Map <UserPhoto>(userPhotoForCreationDto);

            photo.user = user;
            if (!user.UserPhotos.Any(p => p.IsMain))
            {
                photo.IsMain = true;
            }
            user.UserPhotos.Add(photo);
            photo.UserId = user.Id;
            _userPhotoDal.Add(photo);
            _context.SaveChanges();

            /*if (_context.SaveChanges()>0)
             * {
             *  var photoToReturn = _mapper.Map<UserPhotoForReturnDto>(photo);
             *  return CreatedAtRoute("GetUserPhoto", new { Id = photo.Id }, photoToReturn);
             * }*/
            return(Ok(201));
        }
コード例 #5
0
        public async Task <UserPhotoForReturnDto> Update(UserPhotoForCreationDto updateDto)
        {
            var checkByIdFromRepo = await userPotoDal.GetAsync(x => x.Id == updateDto.UserId);

            if (checkByIdFromRepo == null)
            {
                throw new RestException(HttpStatusCode.BadRequest, new { NotFound = Messages.NotFound });
            }

            var mapForUpdate = mapper.Map(updateDto, checkByIdFromRepo);
            var updatePhoto  = await userPotoDal.Update(mapForUpdate);

            return(mapper.Map <UserPhoto, UserPhotoForReturnDto>(updatePhoto));
        }
コード例 #6
0
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] UserPhotoForCreationDto userPhotoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repository.GetUser(userId);

            var file         = userPhotoForCreationDto.File;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            userPhotoForCreationDto.Url      = uploadResult.Uri.ToString();
            userPhotoForCreationDto.PublicId = uploadResult.PublicId;

            var userPhoto = _mapper.Map <UserPhoto>(userPhotoForCreationDto);

            if (!userFromRepo.UserPhotos.Any(p => p.IsMain))
            {
                userPhoto.IsMain = true;
            }

            userFromRepo.UserPhotos.Add(userPhoto);

            if (await _repository.SaveAll())
            {
                var userPhotoToReturn = _mapper.Map <UserPhotoForReturnDto>(userPhoto);
                return(CreatedAtRoute("GetPhoto", new { id = userPhoto.Id }, userPhotoToReturn));
            }

            return(BadRequest("Nie można dodać zdjęcia"));
        }
コード例 #7
0
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] UserPhotoForCreationDto photoDto)
        {
            var userFromRepo = await _repo.GetUser(userId);

            var file = photoDto.File;

            photoDto.UserId = userId;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                };
            }

            photoDto.Url      = uploadResult.Uri.ToString();
            photoDto.PublicId = uploadResult.PublicId;

            var photo = _mapper.Map <UserPhoto>(photoDto);

            photo.User   = userFromRepo;
            photo.UserId = userFromRepo.Id;

            userFromRepo.UserPhoto = photo;

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <UserPhotoForDetailedDto>(photo);
                return(CreatedAtRoute("GetUserPhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add photo"));
        }
コード例 #8
0
        public async Task <UserPhotoForReturnDto> Create(FileUploadDto uploadDto)
        {
            var checkAnnounceById = await userDal.GetAsync(x => x.Id == uploadDto.AnnounceId);

            if (checkAnnounceById == null)
            {
                throw new RestException(HttpStatusCode.BadRequest, new { NotFound = Messages.UserNotFound });
            }

            var uploadFile = await upload.Upload(uploadDto.File, "userprofile");

            var mapForCreate = new UserPhotoForCreationDto();

            mapForCreate.Name      = uploadFile.Name;
            mapForCreate.FullPath  = uploadFile.FullPath;
            mapForCreate.UserId    = uploadDto.AnnounceId;
            mapForCreate.IsConfirm = false;
            mapForCreate.UnConfirm = false;
            var mapForDb    = mapper.Map <UserPhoto>(mapForCreate);
            var createPhoto = await userPotoDal.Add(mapForDb);

            return(mapper.Map <UserPhoto, UserPhotoForReturnDto>(createPhoto));
        }
コード例 #9
0
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] UserPhotoForCreationDto userPhotoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _recipeRepo.GetUser(userId);

            // Delete existing photo if exists
            var currentUserPhoto = userFromRepo.UserPhotos.FirstOrDefault();

            if (currentUserPhoto != null)
            {
                if (currentUserPhoto.PublicId != null)
                {
                    var deleteParams = new DeletionParams(currentUserPhoto.PublicId);

                    var result = _cloudinary.Destroy(deleteParams);

                    if (result.Result == "ok")
                    {
                        _recipeRepo.Delete(currentUserPhoto);
                    }
                }

                if (currentUserPhoto.PublicId == null)
                {
                    _recipeRepo.Delete(currentUserPhoto);
                }
            }

            // Adding new photo
            var file = userPhotoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Folder         = "RecipeApp/user_photos/",
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            userPhotoForCreationDto.Url      = uploadResult.Url.ToString();
            userPhotoForCreationDto.PublicId = uploadResult.PublicId;

            var photo = _mapper.Map <UserPhoto>(userPhotoForCreationDto);

            userFromRepo.UserPhotos.Add(photo);

            if (await _recipeRepo.SaveAll())
            {
                var photoToReturn = _mapper.Map <UserPhotosForReturnDto>(photo);
                return(CreatedAtRoute("GetUserPhoto", new { userId = userId, id = photo.UserPhotoId }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
コード例 #10
0
 public async Task <UserPhotoForReturnDto> Update(UserPhotoForCreationDto creationDto)
 {
     return(await userPhotoService.Update(creationDto));
 }
コード例 #11
0
 public async Task <ActionResult <UserPhotoForReturnDto> > MakeMainPhoto(UserPhotoForCreationDto creationDto, int userId)
 {
     return(await publicService.MakeMainPhotoAsync(creationDto, userId));
 }