예제 #1
0
    def delete_forbidden_word(cls, word_data):
        user = Authenticator.authenticate_team(word_data.authentication,
                                               TeamRoles.is_team_moderator)
        forbidden_word = TeamDatabaseClient.get_forbidden_word_by_id(
            user.team_id, word_data.word_id)

        if forbidden_word is None:
            cls.logger().error(
                f"User #{user.id} tried to delete forbidden word {word_data.word_id} from team "
                f"#{user.team_id}, which doesn't exist.")
            return BadRequestTeamMessageResponse(
                "Forbidden word not found!",
                TeamResponseStatus.NOT_FOUND.value)

        try:
            TeamDatabaseClient.delete_forbidden_word(forbidden_word)
            DatabaseClient.commit()
            cls.logger().info(
                f"User #{user.id} deleted forbidden word \"{forbidden_word.word}\" from team "
                f"#{user.team_id}.")
            return SuccessfulTeamMessageResponse(
                "Forbidden word removed!", TeamResponseStatus.REMOVED.value)
        except IntegrityError:
            DatabaseClient.rollback()
            cls.logger().error(
                f"User #{user.id} couldn't remove forbidden word \"{forbidden_word.word}\" from team "
                f"#{user.team_id}.")
            return UnsuccessfulTeamMessageResponse("Couldn't remove team.")
예제 #2
0
    def accept_invite(cls, invitation_data):
        user = Authenticator.authenticate(invitation_data)
        invite = TeamDatabaseClient.get_team_invite_by_token(
            invitation_data.invite_token, user.email)

        if invite is None:
            return BadRequestTeamMessageResponse(
                "You weren't invited to this team.",
                UserResponseStatus.WRONG_CREDENTIALS.value)

        new_user_team = TeamUser(user_id=user.id, team_id=invite.team_id)

        try:
            TeamDatabaseClient.add_team_user(new_user_team)
            TeamDatabaseClient.delete_invite(invite)
            DatabaseClient.commit()
            BotService.tito_welcome(new_user_team.user_id,
                                    new_user_team.team_id)
            cls.logger().info(
                f"User #{user.id} joined team #{invite.team_id}.")
        except IntegrityError:
            DatabaseClient.rollback()
            cls.logger().error(
                f"User #{user.id} failed at joining team #{invite.team_id}.")
            return UnsuccessfulTeamMessageResponse("Couldn't join team.")
        else:
            return SuccessfulTeamMessageResponse(
                "Team joined!", TeamResponseStatus.ADDED.value)
예제 #3
0
    def create_bot(cls, bot_data):
        admin = Authenticator.authenticate_team(bot_data.authentication, UserRoles.is_admin)

        try:
            new_client = UserDatabaseClient.add_client()
            new_bot = Bot(
                bot_id=new_client.id,
                name=bot_data.name,
                callback=bot_data.callback,
                token=Authenticator.generate(new_client.id)
            )
            BotDatabaseClient.add_bot(new_bot)
            team_bot = TeamUser(
                user_id=new_client.id,
                team_id=admin.team_id,
                role=TeamRoles.BOT.value
            )
            TeamDatabaseClient.add_team_user(team_bot)
            DatabaseClient.commit()
            cls.logger().info(f"Bot #{new_bot.id} created in team {admin.team_id} with callback url {new_bot.callback} "
                              f"by admin {admin.id}.")
            return SuccessfulUserMessageResponse("Bot created.", UserResponseStatus.OK.value)

        except IntegrityError as exc:
            DatabaseClient.rollback()
            if BotDatabaseClient.get_bot_by_name(bot_data.name) is not None:
                cls.logger().info(f"Failing to create bot {bot_data.name}. Name already in use.", exc)
                return BadRequestUserMessageResponse("Name already in use for other bot.",
                                                     UserResponseStatus.ALREADY_REGISTERED.value)
            else:
                cls.logger().info(f"Failing to create bot {bot_data.name}.")
                return UnsuccessfulClientResponse("Couldn't create bot.")
예제 #4
0
    def add_forbidden_word(cls, word_data):
        user = Authenticator.authenticate_team(word_data.authentication,
                                               TeamRoles.is_team_moderator)

        if TeamDatabaseClient.get_forbidden_word_by_word(
                user.team_id, word_data.word) is not None:
            cls.logger().debug(
                f"User #{user.id} attempted to add a forbidden word that already exists ({word_data.word})."
            )
            return BadRequestTeamMessageResponse(
                "Word already forbidden!",
                TeamResponseStatus.ALREADY_REGISTERED.value)

        forbidden_word = ForbiddenWord(word=word_data.word,
                                       team_id=user.team_id)

        try:
            TeamDatabaseClient.add_forbidden_word(forbidden_word)
            DatabaseClient.commit()
            cls.logger().info(
                f"Word \"{word_data.word}\" forbidden in team #{user.team_id} by user #{user.id}."
            )
            return SuccessfulTeamMessageResponse(
                "Forbidden word added!", TeamResponseStatus.ADDED.value)
        except IntegrityError:
            DatabaseClient.rollback()
            cls.logger().error(
                f"User #{user.id} couldn't add forbidden word \"{word_data.word}\"."
            )
            return UnsuccessfulTeamMessageResponse(
                "Couldn't add forbidden word.")
예제 #5
0
 def register_tito_in_team(cls, team_id):
     try:
         team_tito = TeamUser(
             user_id=cls.TITO_ID,
             team_id=team_id,
             role=TeamRoles.BOT.value
         )
         TeamDatabaseClient.add_team_user(team_tito)
         DatabaseClient.commit()
         cls.logger().info(f"Tito added to team #{team_id}.")
     except SQLAlchemyError as exc:
         DatabaseClient.rollback()
         cls.logger().error(f"Failing to register Tito into team #{team_id}.", exc)
         raise
예제 #6
0
    def delete_team(cls, user_data):
        user = Authenticator.authenticate_team(user_data,
                                               TeamRoles.is_team_moderator)
        team = TeamDatabaseClient.get_team_by_id(user.team_id)

        try:
            TeamDatabaseClient.delete_team(team)
            DatabaseClient.commit()
            cls.logger().info(f"Team #{user.team_id} deleted.")
            return SuccessfulTeamMessageResponse(
                "Team removed!", TeamResponseStatus.REMOVED.value)
        except IntegrityError:
            DatabaseClient.rollback()
            cls.logger().error(
                f"User #{user.id} couldn't remove team #{user.team_id}.")
            return UnsuccessfulTeamMessageResponse("Couldn't remove team.")
예제 #7
0
    def notify_change_role(cls, user_team, old_role, admin_id):
        admin = UserDatabaseClient.get_user_by_id(admin_id)
        team = TeamDatabaseClient.get_team_by_id(user_team.team_id)
        new_role = user_team.role

        condition = "upgraded" if TeamRoles.is_higher_role(
            new_role, old_role) else "downgraded"
        message_body = f"You have been {condition} in team {team.name}!"
        data = {
            "notification_type": NotificationType.TEAM_ROLE_CHANGE.value,
            "team_name": team.name,
            "admin_id": admin.id
        }

        try:
            cls.logger().debug(
                f"Sending notification to topic {user_team.user_id}, with title \"{cls.APP_NAME}\" "
                f"and body \"{message_body}\"")
            response = cls.push_service.notify_topic_subscribers(
                topic_name=user_team.user_id,
                message_title=cls.APP_NAME,
                message_body=message_body,
                data_message=data)

            failures = response.get("failure")
            if failures > 0:
                cls.logger().error(
                    f"There's been detected {failures} failures sending user #{user_team.user_id} new "
                    f"role notifications to Firebase.")
            else:
                cls.logger().info(
                    f"New role notified to user #{user_team.user_id}.")

        except ConnectionError:
            cls.logger().error("Couldn't connect to Firebase server.")
예제 #8
0
    def leave_team(cls, user_data):
        user = Authenticator.authenticate_team(user_data)
        delete_user = TeamDatabaseClient.get_user_in_team_by_ids(
            user.id, user.team_id)

        try:
            TeamDatabaseClient.delete_team_user(delete_user)
            DatabaseClient.commit()
            cls.logger().info(f"User #{user.id} leaved team #{user.team_id}.")
            return SuccessfulTeamMessageResponse(
                "Team leaved!", TeamResponseStatus.REMOVED.value)
        except IntegrityError:
            DatabaseClient.rollback()
            cls.logger().error(
                f"User #{user.id} failing to leave team #{user.team_id}.")
            return UnsuccessfulTeamMessageResponse("Couldn't leave team.")
예제 #9
0
 def search_users(cls, user_data):
     user = Authenticator.authenticate_team(user_data.authentication)
     found_users = TeamDatabaseClient.get_all_team_users_by_likely_name(
         user.team_id, user_data.searched_username)
     cls.logger().info(
         f"Found {len(found_users)} users for user #{user.id} with keyword {user.username} ."
     )
     return SuccessfulUsersListResponse(cls._team_users_list(found_users))
예제 #10
0
 def team_users(cls, user_data):
     user = Authenticator.authenticate_team(user_data)
     team_users = TeamDatabaseClient.get_all_team_users_by_team_id(
         user.team_id)
     cls.logger().info(
         f"User #{user.id} got {len(team_users)} users from team #{user.team_id}."
     )
     return SuccessfulUsersListResponse(cls._team_users_list(team_users))
예제 #11
0
    def change_role(cls, change_role_data):
        team_admin = Authenticator.authenticate_team(
            change_role_data.authentication, TeamRoles.is_team_creator)

        if change_role_data.new_role == TeamRoles.CREATOR.value:
            cls.logger().warning(
                f"Trying to set user as team #{team_admin.team_id} {TeamRoles.CREATOR.value}"
            )
            return BadRequestTeamMessageResponse(
                "You cannot set someone as team CREATOR.",
                TeamResponseStatus.ROLE_UNAVAILABLE.value)

        user_team = TeamDatabaseClient.get_user_in_team_by_ids(
            change_role_data.user_id, team_admin.team_id)
        if user_team is None:
            cls.logger().info(
                f"Trying to modify role from user #{change_role_data.user_id}, who's not part of team #{team_admin.team_id}"
            )
            return BadRequestTeamMessageResponse(
                "The given user is not part this team.",
                TeamResponseStatus.USER_NOT_MEMBER.value)

        old_role = user_team.role
        user_team.role = change_role_data.new_role

        try:
            TeamDatabaseClient.update_team_user(user_team)
            DatabaseClient.commit()
            NotificationService.notify_change_role(user_team, old_role,
                                                   team_admin.id)
            cls.logger().info(
                f"User #{user_team.user_id} set as team #{team_admin.team_id} {user_team.role} by user "
                f"#{team_admin.id}.")
        except IntegrityError:
            DatabaseClient.rollback()
            cls.logger().error(
                f"Failing to modifying role of #{user_team.user_id} in team #{user_team.team_id}."
            )
            return UnsuccessfulTeamMessageResponse(
                "Couldn't modify user role.")
        else:
            return SuccessfulTeamMessageResponse(
                "Role modified", TeamResponseStatus.ROLE_MODIFIED.value)
예제 #12
0
 def forbidden_words(cls, user_data):
     user = Authenticator.authenticate_team(user_data,
                                            TeamRoles.is_team_moderator)
     forbidden_words = TeamDatabaseClient.get_forbidden_words_from_team(
         user.team_id)
     cls.logger().info(
         f"User #{user.id} got {len(forbidden_words)} forbidden words in team #{user.team_id}."
     )
     return SuccessfulForbiddenWordsList(
         cls._generate_forbidden_words_list(forbidden_words))
예제 #13
0
    def update_information(cls, update_data):
        user = Authenticator.authenticate_team(update_data.authentication,
                                               TeamRoles.is_team_moderator)
        team = TeamDatabaseClient.get_team_by_id(
            update_data.authentication.team_id)

        team.name = \
            update_data.updated_team["team_name"] if "team_name" in update_data.updated_team else team.name
        team.picture = \
            update_data.updated_team["picture"] if "picture" in update_data.updated_team else team.picture
        team.location = \
            update_data.updated_team["location"] if "location" in update_data.updated_team else team.location
        team.description = \
            update_data.updated_team["description"] if "description" in update_data.updated_team else team.description
        team.welcome_message = \
            update_data.updated_team[
                "welcome_message"] if "welcome_message" in update_data.updated_team else team.welcome_message

        try:
            team = TeamDatabaseClient.update_team(team)
            DatabaseClient.commit()
            cls.logger().info(
                f"Team {team.id} information updated by user #{user.id}, who's team {user.team_role}."
            )
            return SuccessfulTeamResponse(team,
                                          TeamResponseStatus.UPDATED.value)
        except IntegrityError:
            DatabaseClient.rollback()
            team_name = update_data.updated_team.get("team_name")
            if TeamDatabaseClient.get_team_by_name(team_name) is not None:
                cls.logger().info(
                    f"Trying to update team {user.team_id}'s name with {team_name}, that currently exists."
                )
                return BadRequestTeamMessageResponse(
                    f"Name {team_name} is already in use!",
                    TeamResponseStatus.ALREADY_REGISTERED.value)
            else:
                cls.logger().error(
                    f"Couldn't update team {user.team_id} information.")
                return UnsuccessfulTeamMessageResponse(
                    "Couldn't update team information!")
예제 #14
0
    def delete_user(cls, delete_data):
        user = Authenticator.authenticate_team(delete_data.authentication,
                                               TeamRoles.is_team_moderator)
        delete_user = TeamDatabaseClient.get_user_in_team_by_ids(
            delete_data.delete_id, user.team_id)

        if delete_user is not None:

            if TeamRoles.is_higher_role(user.team_role, delete_user.role):
                try:
                    TeamDatabaseClient.delete_team_user(delete_user)
                    DatabaseClient.commit()
                    cls.logger().info(
                        f"User #{delete_user.user_id} deleted from team #{user.team_id} by user #{user.id}."
                    )
                    return SuccessfulTeamMessageResponse(
                        "User removed!", TeamResponseStatus.REMOVED.value)
                except IntegrityError:
                    DatabaseClient.rollback()
                    cls.logger().error(
                        f"User #{user.id} failed to delete user {delete_user.user_id} from team #{user.team_id}."
                    )
                    return UnsuccessfulTeamMessageResponse(
                        "Couldn't delete user.")
            else:
                cls.logger().info(
                    f"Cannot delete user #{delete_user.user_id} because he's role ({delete_user.role}) "
                    f"is higher than yours.")
                return ForbiddenTeamMessageResponse(
                    "You don't have enough permissions to delete this user.",
                    TeamResponseStatus.NOT_ENOUGH_PERMISSIONS.value)

        else:
            cls.logger().info(
                f"Trying to delete user #{delete_data.delete_id}, who's not part of the team {user.team_id}."
            )
            return NotFoundTeamMessageResponse(
                "Couldn't find user to delete",
                UserResponseStatus.USER_NOT_FOUND.value)
예제 #15
0
    def create_team(cls, new_team_data):
        user = Authenticator.authenticate(new_team_data)
        new_team = Team(name=new_team_data.team_name,
                        picture=new_team_data.picture,
                        location=new_team_data.location,
                        description=new_team_data.description,
                        welcome_message=new_team_data.welcome_message)

        try:
            team = TeamDatabaseClient.add_team(new_team)
            new_team.id = team.id
            new_user_by_team = TeamUser(user_id=user.id,
                                        team_id=team.id,
                                        role=TeamRoles.CREATOR.value)
            TeamDatabaseClient.add_team_user(new_user_by_team)
            BotService.register_tito_in_team(team.id)
            DatabaseClient.commit()
            cls.logger().info(f"Team #{team.id} created.")
            cls.logger().info(
                f"User #{user.id} assigned as team #{team.id} {new_user_by_team.role}."
            )
        except IntegrityError:
            DatabaseClient.rollback()
            if TeamDatabaseClient.get_team_by_name(
                    new_team_data.team_name) is not None:
                cls.logger().info(
                    f"Failing to create team {new_team_data.team_name}. Name already in use."
                )
                return BadRequestTeamMessageResponse(
                    f"Name {new_team_data.team_name} already in use for other team.",
                    TeamResponseStatus.ALREADY_REGISTERED.value)
            else:
                cls.logger().error(
                    f"Failing to create team {new_team_data.team_name}.")
                return UnsuccessfulTeamMessageResponse("Couldn't create team.")
        else:
            return SuccessfulTeamResponse(new_team,
                                          TeamResponseStatus.CREATED.value)
예제 #16
0
    def add_user(cls, add_data):
        admin = Authenticator.authenticate(add_data.authentication,
                                           UserRoles.is_admin)
        user = UserDatabaseClient.get_user_by_id(add_data.add_user_id)

        if user is None:
            cls.logger().info(f"User {add_data.add_user_id} not found.")
            raise UserNotFoundError("User not found.",
                                    UserResponseStatus.USER_NOT_FOUND.value)

        if user.role == UserRoles.ADMIN.value:
            cls.logger().warning(
                f"Admin #{admin.id} trying to add other admin to a team.")
            return BadRequestTeamMessageResponse(
                "You cannot add an admin to a team!",
                TeamResponseStatus.ROLE_UNAVAILABLE.value)

        if TeamDatabaseClient.get_user_in_team_by_ids(
                user.id, add_data.authentication.team_id) is not None:
            cls.logger().info(
                f"User {add_data.add_user_id} already part of team #{add_data.authentication.team_id}."
            )
            return BadRequestTeamMessageResponse(
                "This user already belongs to the team.",
                TeamResponseStatus.ALREADY_REGISTERED.value)

        previous_invitation = TeamDatabaseClient.get_team_invite(
            add_data.authentication.team_id, user.email)

        if previous_invitation is not None:
            cls.logger().info(
                f"Deleting old invitation for user {add_data.add_user_id} to team "
                f"#{add_data.authentication.team_id}.")
            TeamDatabaseClient.delete_invite(previous_invitation)
            DatabaseClient.commit()

        added_user = TeamUser(user_id=add_data.add_user_id,
                              team_id=add_data.authentication.team_id)

        try:
            TeamDatabaseClient.add_team_user(added_user)
            DatabaseClient.commit()
            BotService.tito_welcome(added_user.user_id, added_user.team_id)
            cls.logger().info(
                f"Added user #{added_user.user_id} to team #{added_user.team_id} by admin #{admin.id}."
            )
            return SuccessfulTeamMessageResponse(
                "User added.", TeamResponseStatus.ADDED.value)

        except IntegrityError:
            DatabaseClient.rollback()
            cls.logger().error(
                f"Couldn't add user #{added_user.user_id} to team #{added_user.team_id}."
            )
            return UnsuccessfulTeamMessageResponse(
                "Couldn't invite user to team.")
예제 #17
0
    def tito_welcome(cls, user_id, team_id):
        bot = BotDatabaseClient.get_bot_by_id(cls.TITO_ID)
        team = TeamDatabaseClient.get_team_by_id(team_id)

        if bot is not None and team.welcome_message is not None:
            body = {
                "params": cls.TITO_WELCOME_PARAMS,
                "message": team.welcome_message,
                "user_id": user_id,
                "team_id": team_id
            }
            headers = {"X-Auth-Token": bot.token}
            requests.post(url=bot.callback, json=body, headers=headers)
            cls.logger().info(f"Tito notified to welcome user #{user_id} to team #{team_id}")
        elif team.welcome_message is not None:
            cls.logger().info(f"There's no message for Tito to welcome user #{user_id}.")
예제 #18
0
    def notify_mention(cls, message, mentioned_id):
        is_not_bot = BotDatabaseClient.get_bot_by_id(mentioned_id) is None

        if is_not_bot:
            team = TeamDatabaseClient.get_team_by_id(message.team_id)
            sender = UserDatabaseClient.get_user_by_id(message.sender_id)

            if sender is None:
                sender = BotDatabaseClient.get_bot_by_id(message.sender_id)

            message_body = "You have been mentioned!"
            data = {
                "notification_type": NotificationType.MENTION.value,
                "team_name": team.name,
                "sender_id": sender.id
            }

            channel = ChannelDatabaseClient.get_channel_by_id(mentioned_id)
            if channel is not None:
                data["channel_name"] = channel.name

            try:
                cls.logger().debug(
                    f"Sending notification to topic {mentioned_id}, with title \"{cls.APP_NAME}\" "
                    f"and body \"{message_body}\"")
                response = cls.push_service.notify_topic_subscribers(
                    topic_name=mentioned_id,
                    message_title=cls.APP_NAME,
                    message_body=message_body,
                    data_message=data)

                failures = response.get("failure")
                if failures > 0:
                    cls.logger().error(
                        f"There's been detected {failures} failures sending the mentions notification for "
                        f"receiver #{message.receiver_id} to Firebase.")
                else:
                    cls.logger().info(
                        f"New mention notified to receiver #{message.receiver_id}."
                    )
            except ConnectionError:
                cls.logger().error("Couldn't connect to Firebase server.")
예제 #19
0
    def authenticate_team(cls, authentication, role_verifying=lambda _: True):
        logger = logging.getLogger(cls.__name__)

        user = cls.authenticate(authentication)

        if user.role == UserRoles.ADMIN.value:
            user.user_role = user.role
            user.team_id = authentication.team_id
            user.team_role = user.role
            return user

        team_user = UserDatabaseClient.get_team_user_by_ids(
            user.id, authentication.team_id)

        if team_user is not None:
            if role_verifying(team_user.team_role):
                logger.info(
                    f"Client #{team_user.id} authenticated as team #{team_user.team_id} {team_user.team_role}."
                )
                return team_user
            else:
                logger.info(
                    f"User #{user.id} does not have permissions to perform this action."
                )
                raise NoPermissionsError(
                    "You don't have enough permissions to perform this action.",
                    TeamResponseStatus.NOT_ENOUGH_PERMISSIONS.value)
        else:
            team = TeamDatabaseClient.get_team_by_id(authentication.team_id)

            if team is None:
                logger.info(f"Team #{authentication.team_id} not found.")
                raise TeamNotFoundError("Team not found.",
                                        TeamResponseStatus.NOT_FOUND.value)
            else:
                logger.info(
                    f"Client #{user.id} trying to access team #{team.id}, when it's not part of it."
                )
                raise NoPermissionsError(
                    "You're not part of this team!",
                    TeamResponseStatus.NOT_ENOUGH_PERMISSIONS.value)
예제 #20
0
    def notify_team_invitation(cls, invitation, inviter_id):
        inviter_user = UserDatabaseClient.get_user_by_id(inviter_id)
        invited_user = UserDatabaseClient.get_user_by_email(invitation.email)
        team = TeamDatabaseClient.get_team_by_id(invitation.team_id)

        if invited_user is not None:
            message_body = "You have been invited to join a team!"
            data = {
                "notification_type": NotificationType.TEAM_INVITATION.value,
                "team_name": team.name,
                "inviter_id": inviter_user.id,
                "invitation_token": invitation.token
            }

            try:
                cls.logger().debug(
                    f"Sending notification to topic {invited_user.id}, with title \"{cls.APP_NAME}\" "
                    f"and body \"{message_body}\"")
                response = cls.push_service.notify_topic_subscribers(
                    topic_name=invited_user.id,
                    message_title=cls.APP_NAME,
                    message_body=message_body,
                    data_message=data)

                failures = response.get("failure")
                if failures > 0:
                    cls.logger().error(
                        f"There's been detected {failures} failures sending user #{invited_user.id}'s "
                        f"team invite notification to Firebase.")
                else:
                    cls.logger().info(
                        f"Team invite notified to user #{invited_user.id}.")

            except ConnectionError:
                cls.logger().error("Couldn't connect to Firebase server.")

        else:
            cls.logger().info(
                f"The invited user is not already registered so it cannot receive a notification."
            )
예제 #21
0
    def add_member(cls, invitation_data):
        user = Authenticator.authenticate_channel(invitation_data.authentication, TeamRoles.is_channel_creator)

        invited_user = UserDatabaseClient.get_user_by_id(invitation_data.user_invited_id)
        if invited_user is None:
            cls.logger().info(f"Trying to add user an nonexistent user to channel #{user.channel_id}.")
            return BadRequestChannelMessageResponse("Invited user not found!", UserResponseStatus.USER_NOT_FOUND.value)

        invited_user_in_team = TeamDatabaseClient.get_user_in_team_by_ids(invited_user.id, user.team_id)
        if invited_user_in_team is None:
            cls.logger().info(f"Trying to add user {invited_user.id} to channel #{user.channel_id}, but it's not part "
                              f"of the team #{user.team_id}.")
            return BadRequestChannelMessageResponse("User not part of the team!",
                                                    TeamResponseStatus.USER_NOT_MEMBER.value)

        try:
            new_channel_user = ChannelUser(user_id=invited_user.id, channel_id=user.channel_id)
            ChannelDatabaseClient.add_channel_user(new_channel_user)
            new_chat = Chat(user_id=invited_user.id, chat_id=user.channel_id, team_id=user.team_id)
            MessageDatabaseClient.add_chat(new_chat)
            DatabaseClient.commit()
            NotificationService.notify_channel_invitation(new_channel_user, user.id)
            cls.logger().info(f"User #{invited_user.id} added to channel #{user.channel_id} by {user.username}.")

        except IntegrityError:
            DatabaseClient.rollback()
            already_member = ChannelDatabaseClient.get_user_in_channel_by_ids(invited_user.id, user.channel_id)

            if already_member is not None:
                cls.logger().info(f"Failing to add user #{invited_user.id} to channel #{user.channel_id}. "
                                  f"The user is already part of it.")
                return BadRequestChannelMessageResponse(f"User already registered in channel.",
                                                        TeamResponseStatus.ALREADY_REGISTERED.value)
            else:
                cls.logger().error(f"Failing to add user #{invitation_data.user_invited_id} to channel"
                                   f"{invitation_data.authentication.channel_id}.")
                return UnsuccessfulChannelMessageResponse("Couldn't add user to channel.")
        else:
            return SuccessfulChannelMessageResponse("User added!", ChannelResponseStatus.ADDED.value)
예제 #22
0
    def notify_channel_invitation(cls, user_channel, inviter_id):
        inviter_user = UserDatabaseClient.get_user_by_id(inviter_id)
        channel = ChannelDatabaseClient.get_channel_by_id(
            user_channel.channel_id)
        team = TeamDatabaseClient.get_team_by_id(channel.team_id)

        message_body = f"You have been added to channel {channel.name} in team {team.name}!"
        data = {
            "notification_type": NotificationType.CHANNEL_INVITATION.value,
            "channel_name": channel.name,
            "team_name": team.name,
            "inviter_id": inviter_user.id
        }

        try:
            cls.logger().debug(
                f"Sending notification to topic {user_channel.user_id}, with title \"{cls.APP_NAME}\" "
                f"and body \"{message_body}\"")
            response = cls.push_service.notify_topic_subscribers(
                topic_name=user_channel.user_id,
                message_title=cls.APP_NAME,
                message_body=message_body,
                data_message=data)

            failures = response.get("failure")
            if failures > 0:
                cls.logger().error(
                    f"There's been detected {failures} failures sending user #{user_channel.user_id}'s "
                    f"channel invite notification to Firebase.")
            else:
                cls.logger().info(
                    f"Channel invitation notified to user #{user_channel.user_id}."
                )

        except ConnectionError:
            cls.logger().error("Couldn't connect to Firebase server.")
예제 #23
0
    def teams_for_user(cls, user_data):
        user = Authenticator.authenticate(user_data)
        teams = TeamDatabaseClient.get_user_teams_by_user_id(
            user.id, user.role == UserRoles.ADMIN.value)

        return SuccessfulTeamsListResponse(cls._generate_teams_list(teams))
예제 #24
0
 def __init__(self, team_id):
     self.forbidden_words = TeamDatabaseClient.get_forbidden_words_from_team(team_id)
예제 #25
0
    def invite_user(cls, invite_data):
        team_mod = Authenticator.authenticate_team(invite_data.authentication,
                                                   TeamRoles.is_team_moderator)

        invited_user = UserDatabaseClient.get_user_by_email(invite_data.email)
        if invited_user is not None and invited_user.role == UserRoles.ADMIN.value:
            cls.logger().info(
                f"Mod #{team_mod.id} tried to invite admin #{invited_user.id} to team #{team_mod.team_id}."
            )
            return BadRequestTeamMessageResponse(
                "You cannot invite an admin to a team!",
                TeamResponseStatus.ROLE_UNAVAILABLE.value)

        already_member = TeamDatabaseClient.get_user_in_team_by_email(
            invite_data.email, team_mod.team_id)
        if already_member is not None:
            cls.logger().info(
                f"Mod #{team_mod.id} tried to invite user #{already_member.user_id} to team "
                f"#{team_mod.team_id}, but it already belongs to that team.")
            return BadRequestTeamMessageResponse(
                "This user already belongs to the team.",
                TeamResponseStatus.ALREADY_REGISTERED.value)

        if TeamDatabaseClient.get_team_invite(team_mod.team_id,
                                              invite_data.email) is not None:
            cls.logger().info(
                f"Mod #{team_mod.id} tried to invite an user already invited to team #{team_mod.team_id}"
            )
            return BadRequestTeamMessageResponse(
                "This user was already invited to join the team.",
                TeamResponseStatus.ALREADY_INVITED.value)

        invite_token = Authenticator.generate_team_invitation()
        new_invite = TeamInvite(team_id=team_mod.team_id,
                                email=invite_data.email,
                                token=invite_token)

        try:
            TeamDatabaseClient.add_invite(new_invite)
            team = TeamDatabaseClient.get_team_by_id(team_mod.team_id)
            DatabaseClient.commit()
            cls.logger().info(
                f"New invitation for {new_invite.email} to join team #{team_mod.team_id}, by user #"
                f"{team_mod.id}.")

            email_data = TeamInvitationEmailDTO(
                email=invite_data.email,
                team_name=team.name,
                inviter_name=team_mod.username,
                token=invite_token,
                message_template=EmailService.team_invitation_message)
            EmailService.send_email(email_data)
            NotificationService.notify_team_invitation(new_invite, team_mod.id)
            cls.logger().info(
                f"Team #{team_mod.team_id} invitation email sent to {new_invite.email}."
            )

        except IntegrityError:
            DatabaseClient.rollback()
            cls.logger().error(
                f"Couldn't invite user {new_invite.email} to team #{team_mod.team_id}."
            )
            return UnsuccessfulTeamMessageResponse(
                "Couldn't invite user to team.")
        else:
            return SuccessfulTeamMessageResponse(
                "User invited.", TeamResponseStatus.INVITED.value)