Exemplo n.º 1
0
        public async Task <IActionResult> AnswerFriendRequestAsync(
            int id,
            int friendRequestId,
            [FromBody] FriendRequestAnswerRequest request)
        {
            try
            {
                var subClaim = User.FindFirst(JwtRegisteredClaimNames.Sub);
                if (subClaim is null ||
                    !int.TryParse(subClaim.Value, out int idFromToken) ||
                    idFromToken != id)
                {
                    return(Unauthorized());
                }

                var friendRequest = await _userManager.GetFriendRequestAsync(friendRequestId);

                if (friendRequest is null)
                {
                    return(NotFound());
                }
                else if (friendRequest.User2Id != id)
                {
                    // User1 sends the friend request, User2 answers to it
                    return(Unauthorized());
                }

                if (request.Accept)
                {
                    await _userManager.AcceptFriendRequestAsync(friendRequestId);
                }
                else
                {
                    await _userManager.RejectFriendRequestAsync(friendRequestId);
                }

                _notificationsService.EnqueueNotification(new FriendRequestNotification(
                                                              friendRequestId: friendRequest.Id,
                                                              accepted: request.Accept,
                                                              sender: await _userManager.GetUserAsync(friendRequest.User1Id),
                                                              receiver: await _userManager.GetUserAsync(friendRequest.User2Id)));

                return(Ok());
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"Could not answer friend request with id ({friendRequestId})");
                return(BadRequest());
            }
        }