Esempio n. 1
0
        public async Task <IActionResult> GetUserDetails(int id)
        {
            var user = await _repo.GetUserDetails(id);

            var userToReturn = _mapper.Map <User, UserDetailsDto>(user);

            return(Ok(userToReturn));
        }
Esempio n. 2
0
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUserDetails(userId);

            var file = photoForCreationDto.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);
                }
            }

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

            var photo = _mapper.Map <Avatar>(photoForCreationDto);


            if (userFromRepo.Avatar != null)
            {
                var avatarFromRepo = await _repo.GetAvatar(userFromRepo.Avatar.Id);

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

                    var result = _cloudinary.Destroy(deleteParams);

                    if (result.Result == "ok")
                    {
                        _repo.Delete(avatarFromRepo);
                    }
                }
                else if (avatarFromRepo.PublicId == null)
                {
                    _repo.Delete(avatarFromRepo);
                }
            }

            userFromRepo.Avatar = photo;

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

            return(BadRequest("Could not save the avatar photo"));
        }