public async Task <IActionResult> InviteFriend(FriendInviteDTO model) { try { await _friendService.InviteFriendAsync(model); return(Ok("Friend invite was sended")); } catch (NoPermissionException e) { return(BadRequest(new { e.Message })); } catch (UnauthorizedAccessException) { return(Unauthorized()); } catch (SqlNullValueException e) { return(NotFound(new { e.Message })); } catch (AlreadyExistsException e) { return(BadRequest(new { e.Message })); } catch (Exception e) { return(BadRequest(new { e.Message })); } }
public static Invite FriendInviteDTOToInvite(this FriendInviteDTO model, User friendToInvite, long ownerId, User ownerUser) { return(new Invite { Approved = false, FriendId = model.FriendId, CreatedBy = ownerId, UserId = friendToInvite.Id, OwnerId = ownerId, OwnerUser = ownerUser }); }
public async Task InviteFriendAsync(FriendInviteDTO model) { var idClaim = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; if (!long.TryParse(idClaim, out var ownerId)) { throw new UnauthorizedAccessException(); } var ownerUser = await _userRepository.GetByIdAsync(ownerId); var isThisUser = await _userRepository.ExistsAsync(user => user.Id == ownerId && (user.Email == model.FriendEmail || user.Username == model.FriendEmail)); if (isThisUser) { throw new ArgumentException("You can't invite yourself"); } var isOwnerFriend = await _friendRepository.ExistsAsync(friend => friend.Id == model.FriendId && friend.Owner.Id == ownerId); if (!isOwnerFriend) { throw new NoPermissionException("User is not owner of this friend"); } var isAlreadySentFriend = await _inviteRepository.ExistsAsync(invite => invite.FriendId == model.FriendId && invite.OwnerId == ownerId); if (isAlreadySentFriend) { throw new AlreadyExistsException("Invite of this friend already sent"); } var friendToInvite = await _userRepository.GetFirstAsync(user => user.Email.ToUpper().Equals(model.FriendEmail.ToUpper())); if (friendToInvite == null) { throw new SqlNullValueException("User with this email does not exist"); } var isAlreadySentUser = await _inviteRepository.ExistsAsync(invite => invite.UserId == friendToInvite.Id && invite.OwnerId == ownerId); if (isAlreadySentUser) { throw new AlreadyExistsException("Invite to this user already sent"); } var isAlreadyFriends = await _friendRepository.ExistsAsync(friend => friend.Owner.Id == ownerId && friend.FriendUser.Id == friendToInvite.Id || friend.Owner.Id == friendToInvite.Id && friend.FriendUser.Id == ownerId); if (isAlreadyFriends) { throw new AlreadyExistsException("You already friends"); } var newInvite = model.FriendInviteDTOToInvite(friendToInvite, ownerId, ownerUser); var inviteRet = await _inviteRepository.InsertAsync(newInvite); var oldFriend = await _friendRepository.GetByIdAsync(model.FriendId); oldFriend.InviteId = inviteRet.Id; oldFriend.ModifiedBy = ownerId; await _friendRepository.UpdateAsync(oldFriend); }