public async Task <IActionResult> ApproveFriend(FriendAcceptDTO model) { try { await _friendService.ApproveInviteAsync(model); return(Ok()); } catch (UnauthorizedAccessException) { return(Unauthorized()); } catch (NoPermissionException e) { return(BadRequest(new { e.Message })); } catch (SqlNullValueException e) { return(NotFound(new { e.Message })); } catch (Exception e) { return(BadRequest(new { e.Message })); } }
public async Task ApproveInviteAsync(FriendAcceptDTO model) { var idClaim = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; if (!long.TryParse(idClaim, out var ownerId)) { throw new UnauthorizedAccessException(); } var isOwnerFriend = await _inviteRepository.ExistsAsync(invite => invite.Id == model.InviteId && invite.UserId == ownerId); if (!isOwnerFriend) { throw new NoPermissionException("User is not owner of this invite"); } if (model.Accepted) { var oldInvite = await _inviteRepository.GetByIdAsync(model.InviteId); var oldFriend = await _friendRepository.GetFirstAsync(friend => friend.Owner.Id == oldInvite.OwnerId && friend.InviteId == model.InviteId); if (oldFriend == null) { throw new SqlNullValueException("Friend not found"); } if (model.FriendId != null) { var friendToSync = await _friendRepository.GetFirstAsync(friend => friend.Owner.Id == ownerId && friend.Id == model.FriendId); if (friendToSync == null) { throw new NoPermissionException("Friend not Founded"); } friendToSync.IsSynchronized = true; friendToSync.FriendUser = await _userRepository.GetByIdAsync(oldInvite.OwnerId); oldFriend.IsSynchronized = true; oldFriend.FriendUser = await _userRepository.GetByIdAsync(ownerId); await _friendRepository.UpdateAsync(friendToSync); await _friendRepository.UpdateAsync(oldFriend); } else { var addFriendDTO = new FriendAddDTO { Name = model.UsersName }; var addedFriend = await AddFriendAsync(addFriendDTO); var newFriend = await _friendRepository.GetByIdAsync(addedFriend.Id); newFriend.IsSynchronized = true; newFriend.FriendUser = await _userRepository.GetByIdAsync(oldInvite.OwnerId); oldFriend.IsSynchronized = true; oldFriend.FriendUser = await _userRepository.GetByIdAsync(ownerId); await _friendRepository.UpdateAsync(newFriend); await _friendRepository.UpdateAsync(oldFriend); } } await _inviteRepository.RemoveByIdAsync(model.InviteId); }