public async Task <ActionResult <FollowingResponse> > Follow(string username)
        {
            _logger.LogInformation("Received profile follow request.");
            _logger.LogInformation("Profile username: {0}", username);

            User currentUser = _currentUserService.GetCurrentUser(HttpContext);

            _logger.LogInformation("Requesting user email: {0}", currentUser.Email);

            try
            {
                Follow newFollow = await _followService.FollowUser(username, currentUser.Email);

                newFollow.Follower = currentUser;

                // Publish event.
                _logger.LogInformation("Publishing follow notification.");
                await _notificationService.Publish(new FollowNotification(_mapper.Map <FollowResponse>(newFollow)));

                _logger.LogInformation("Successfully followed '{0}' for '{1}'.", username, currentUser.Email);

                return(Ok(_mapper.Map <FollowingResponse>(newFollow)));
            }
            catch (EntityNotFoundException <string> )
            {
                _logger.LogError("Profile with username '{0}' does not exist.", username);
                return(NotFound());
            }
            catch (OwnProfileFollowException)
            {
                _logger.LogError("User '{0}' cannot follow their own profile '{1}'.", currentUser.Email, username);
                return(BadRequest());
            }
        }
Example #2
0
        public async Task CreateAsync(CreateItemGroupDto dto)
        {
            var userId = _currentUserService.GetCurrentUser().Id;

            var group = _itemGroupAggregate.Create(userId, dto.Name, dto.Description, dto.Image);

            await _itemGroupRepository.CreateAsync(group);
        }
        public async Task <ActionResult <ImagePostResponse> > Create([FromForm] CreateImagePostRequest imagePostRequest)
        {
            _logger.LogInformation("Received image post create request.");

            // Get the user making the request.
            User user = _currentUserService.GetCurrentUser(HttpContext);

            _logger.LogInformation("Requesting user email: {0}", user.Email);

            IFormFile image = imagePostRequest.Image;

            // Optimize image.
            _logger.LogInformation("Optimizing image.");
            Stream imageStream = _imageOptimizationService.Optimize(image);

            // Store image file.
            _logger.LogInformation("Saving image file with filename '{0}'.", image.FileName);
            string imageUri = await _imageStorage.SaveImage(imageStream, Path.GetExtension(image.FileName));

            _logger.LogInformation("Successfully saved image file at location '{0}'.", imageUri);

            // Save image database record.
            ImagePost newImagePost = new ImagePost()
            {
                UserEmail   = user.Email,
                Description = imagePostRequest.Description,
                ImageUri    = imageUri,
                DateCreated = DateTime.Now,
                Tags        = imagePostRequest.Tags
                              .Select(content => new ImagePostTag()
                {
                    Tag = new Tag()
                    {
                        Content = content
                    }
                }).ToList()
            };

            _logger.LogInformation("Creating image post.");
            newImagePost = await _imagePostService.Create(newImagePost);

            newImagePost.User = user;

            // Map to response object.
            ImagePostResponse imagePostResponse = _mapper.Map <ImagePostResponse>(newImagePost);

            // Publish event.
            _logger.LogInformation("Publishing image post create notification.");
            await _notificationService.Publish(new ImagePostCreatedNotification(imagePostResponse));

            _logger.LogInformation("Successfully created image post with id {0}.", newImagePost.Id);

            return(Created($"/imageposts/{newImagePost.Id}", imagePostResponse));
        }
        public ListingDTO createListing(ListingCreateOrUpdate listingDTO)
        {
            Listing listing = new Listing()
            {
                name        = listingDTO.name,
                description = listingDTO.description,
                created     = DateTime.UtcNow,
                modified    = DateTime.UtcNow,
                price       = listingDTO.price
            };

            User currentUser = _currentUserService.GetCurrentUser();

            listing.userId = currentUser.id;
            Guid key = _ctx.Listings.Add(listing).Entity.id.Value;

            foreach (string tag in listingDTO.tags)
            {
                _ctx.ListingTags.Add(new ListingTag()
                {
                    name      = tag,
                    listingId = key
                });
            }

            if (null != listingDTO.image && FileHelper.IsImage(listingDTO.image))
            {
                byte[] fileContents = null;
                using (var fs1 = listingDTO.image.OpenReadStream())
                    using (var ms1 = new MemoryStream())
                    {
                        fs1.CopyTo(ms1);
                        fileContents = ms1.ToArray();
                    }

                _ctx.ListingImages.Add(new ListingImage()
                {
                    listingId   = key,
                    contentType = listingDTO.image.ContentType,
                    image       = fileContents,
                    fileName    = Path.GetFileName(listingDTO.image.FileName)
                });
            }

            _ctx.SaveChanges();

            Listing result = _ctx.Listings
                             .Include(l => l.user)
                             .Include(l => l.tags)
                             .Where(l => l.id == key)
                             .FirstOrDefault();

            return(_mapper.Map <ListingDTO>(result));
        }
Example #5
0
        public async Task <TaskDto> CreateAsync(CreateTaskDto dto)
        {
            if (dto.GroupId is not null && !await _entityValidator.IsGroupIdValidAsync(dto.GroupId.Value))
            {
                throw new GroupIdInvalidException();
            }

            var userId = _currentUserService.GetCurrentUser().Id;

            var task = _taskAggregate.Create(dto.Name, userId, dto.GroupId, dto.Deadline);

            await _taskRepository.CreateAsync(task);

            return(new(task.Id, task.Name, task.Created, task.IsComplete, task.GroupId, task.Deadline));
        }
        public ActionResult Index()
        {
            User users = currentUser.GetCurrentUser(Request);

            ViewBag.CurrentUser = users != null ? users.Email : null;
            return(View());
        }
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     if (!(context.Role.Find(currentUserService.GetCurrentUser(filterContext.HttpContext.Request).RoleId).RoleType == Role))
     {
         filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "User" }));
     }
 }
        public Task Process(TRequest request, CancellationToken cancellationToken)
        {
            var currentUser = _currentUserService.GetCurrentUser();
            var name        = typeof(TRequest).Name;

            _logger.LogInformation(
                "ProjectManagement Request: {Name} {@Request} user: {User}", name, request, currentUser.Login);

            return(Task.CompletedTask);
        }
        public async Task <Unit> Handle(RequestJoinCommand request, CancellationToken cancellationToken)
        {
            var currentUser = await _currentUserService.GetCurrentUser();

            await _context.UserRequests.AddAsync(new UserRequest { AllianceId = request.AllianceId, UserId = currentUser.Id }, cancellationToken);

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IAuthorizationRequirement requirement)
        {
            User currentUser = _userService.GetCurrentUser(context.User);

            if (currentUser != null && _adminUsernames.Any(u => u == currentUser.Username))
            {
                context.Succeed(requirement);
            }

            return(Task.CompletedTask);
        }
        public ActionResult AllRecords()
        {
            List <UserViewModels> allUsersRecords = new List <UserViewModels>();
            int id     = currentUserService.GetCurrentUser(Request).RoleId;
            var result = context.User.Where(u => u.RoleId != id);

            foreach (var user in result)
            {
                allUsersRecords.Add(this.userService.GetUserDetails(user));
            }
            ViewBag.AllUsers = allUsersRecords;
            return(View());
        }
Example #12
0
        public async Task <IActionResult> GetAllJournals([FromServices] ICurrentUserService service)
        {
            if (ModelState.IsValid)
            {
                var user = await service.GetCurrentUser(HttpContext);

                var result = await _service.GetJournals(user.Id);

                return(Ok(result));
            }

            return(BadRequest(ModelState));
        }
Example #13
0
        public async Task <ActionResult <IEnumerable <ImagePostResponse> > > GetFeed()
        {
            _logger.LogInformation("Received feed request.");

            User currentUser = _currentUserService.GetCurrentUser(HttpContext);

            _logger.LogInformation("Requesting user email: {0}", currentUser.Email);

            IEnumerable <ImagePost> feed = await _feedService.GetFeed(currentUser.Email);

            _logger.LogInformation("Successfully retrieved feed of {0} image posts.", feed.Count());

            return(Ok(_mapper.Map <IEnumerable <ImagePostResponse> >(feed)));
        }
        public async Task <ActionResult <CommentResponse> > CreateComment(int imagePostId, [FromBody] CreateCommentRequest commentRequest)
        {
            _logger.LogInformation("Received image post comment create request.");
            _logger.LogInformation("Image post id: {0}", imagePostId);

            if (!ModelState.IsValid)
            {
                _logger.LogError("Invalid create comment request model state.");
                return(BadRequest());
            }

            User currentUser = _currentUserService.GetCurrentUser(HttpContext);

            _logger.LogInformation("Requesting user email: {0}", currentUser.Email);

            Comment createdComment = new Comment()
            {
                ImagePostId = imagePostId,
                UserEmail   = currentUser.Email,
                DateCreated = DateTime.Now,
                Content     = commentRequest.Content
            };

            createdComment = await _commentService.Create(createdComment);

            createdComment.User = currentUser;

            CommentResponse commentResponse = _mapper.Map <CommentResponse>(createdComment);

            // Publish event.
            _logger.LogInformation("Publishing comment create notification.");
            await _notificationService.Publish(new CommentCreatedNotification(commentResponse));

            _logger.LogInformation("Successfully created comment with id {0} on image post with id {1}.", createdComment.Id, createdComment.ImagePostId);

            return(Ok(commentResponse));
        }
Example #15
0
        public async Task <IActionResult> Create(
            [FromBody] string title,
            [FromServices] ICurrentUserService service)
        {
            if (ModelState.IsValid)
            {
                var user = await service.GetCurrentUser(HttpContext);

                var result = await _service.Create(title, user.Id);

                return(Ok(result));
            }

            return(BadRequest(ModelState));
        }
        public async Task <AllianceDto> Handle(CreateAllianceCommand request, CancellationToken cancellationToken)
        {
            var user = await _currentUserService.GetCurrentUser();

            var entity = new Alliance
            {
                Title        = request.Title,
                Description  = request.Description,
                LeaderId     = _currentUserService.UserId,
                CreationDate = DateTime.Now,
                Members      = { user }
            };

            await _context.Alliances.AddAsync(entity, cancellationToken);

            await _context.SaveChangesAsync(cancellationToken);

            return(_mapper.Map <AllianceDto>(entity));
        }
Example #17
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var currentUser = _currentUserService.GetCurrentUser();

            _timer.Start();

            var response = await next();

            _timer.Stop();

            if (_timer.ElapsedMilliseconds > 500)
            {
                var name = typeof(TRequest).Name;

                _logger.LogWarning(
                    "Northwind Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@Request}", name, _timer.ElapsedMilliseconds, request);
            }

            return(response);
        }
Example #18
0
        public void Resolve(EntityEntry entry)
        {
            if (entry.Entity is IAuditInfo audit)
            {
                var email = _currentUserService.GetCurrentUser().Email;
                var now   = DateTime.UtcNow;
                var user  = !string.IsNullOrEmpty(email) ? email : "SYSTEM";

                switch (entry.State)
                {
                case EntityState.Added:
                    audit.CreatedDate = now;
                    audit.CreatedBy   = user;
                    break;

                case EntityState.Modified:
                    audit.ModifiedDate = now;
                    audit.ModifiedBy   = user;
                    break;
                }
            }
        }
Example #19
0
        public async Task <ActionResult <LoggedInUserResponse> > GoogleLogin()
        {
            _logger.LogInformation("Received Google login request.");

            User currentUser = _currentUserService.GetCurrentUser(HttpContext);

            _logger.LogInformation("Requesting user email: {0}", currentUser.Email);

            User existingUser = await _userService.GetByEmail(currentUser.Email);

            // User does not exist.
            if (existingUser == null)
            {
                _logger.LogWarning("User '{0}' does not exist.", currentUser.Email);
                _logger.LogInformation("Creating account for '{0}'.", currentUser.Email);
                currentUser.DateJoined = DateTime.Now;
                existingUser           = await _userService.Create(currentUser);
            }

            _logger.LogInformation("Successfully logged in user '{0}'.", existingUser.Email);

            return(Ok(_mapper.Map <LoggedInUserResponse>(existingUser)));
        }
Example #20
0
 public async Task <IActionResult> GetUserStats() => Ok(await _mediator.Send(new UserStatsGetRequest((await _currentUserService.GetCurrentUser()).Id)));
Example #21
0
 public async Task <IActionResult> CompleteWish(Guid id) => Ok(await _mediator.Send(new WishCompleteItemRequest(await _userService.GetCurrentUser(), id)));
Example #22
0
 public ActionResult Index()
 {
     return(View(userService.GetUserDetails(currentUser.GetCurrentUser(Request))));
 }
        public bool isValidUpdate(Guid key)
        {
            User currentUser = _currentUserService.GetCurrentUser();

            return(currentUser.isAdmin || currentUser.id == key);
        }
Example #24
0
        public async Task Service_Calls_UserManager()
        {
            await _service.GetCurrentUser();

            _userManager.Verify(x => x.GetUserAsync(It.IsNotNull <ClaimsPrincipal>()), Times.Once);
        }
Example #25
0
 public async Task <IActionResult> AddToShowcase(Guid id) => Ok(await _mediator.Send(new MovieAddToShowcaseRequest(id, await _userService.GetCurrentUser())));