示例#1
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.")
示例#2
0
    def save_mentions(cls, message, mentions):
        cls.logger().debug(
            f"Saving mentions from message #{message.message_id}.")

        try:
            for mention in mentions:
                if message.send_type == SendMessageType.CHANNEL.value:
                    BotService.process_mention(mention, message)
                    new_mention = Mention(message_id=message.message_id,
                                          client_id=mention)
                    MessageDatabaseClient.add_mention(new_mention)
                    cls.logger().debug(f"Mention saved for client {mention}.")
                    NotificationService.notify_mention(message, mention)

                elif BotDatabaseClient.get_bot_by_id(mention) is None:
                    new_mention = Mention(message_id=message.message_id,
                                          client_id=mention)
                    MessageDatabaseClient.add_mention(new_mention)
                    cls.logger().debug(f"Mention saved for user {mention}.")
                    NotificationService.notify_mention(message, mention)

            DatabaseClient.commit()
            cls.logger().info(
                f"{len(mentions)} mentions saved for message #{message.message_id}."
            )
        except IntegrityError:
            DatabaseClient.rollback()
            cls.logger().error(
                f"Couldn't save mentions for message #{message.message_id}.")
示例#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 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.")
示例#5
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)
示例#6
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.")
示例#7
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
示例#8
0
    def send_message(cls, inbox_data):
        user = Authenticator.authenticate_team(inbox_data.authentication)

        if user.id == inbox_data.chat_id:
            raise WrongActionError("You cannot send a message to yourself!", MessageResponseStatus.ERROR.value)

        receiver = cls._determinate_message_receiver(inbox_data.chat_id, user.team_id)
        if receiver is None or receiver.team_id != user.team_id:
            cls.logger().info(f"Trying to send a message to client #{inbox_data.chat_id} who's not part of team "
                              f"{user.team_id}.")
            return BadRequestMessageSentResponse("The receiver it's not part of this team!",
                                                 TeamResponseStatus.USER_NOT_MEMBER.value)

        new_message = Message(
            sender_id=user.id,
            receiver_id=inbox_data.chat_id,
            team_id=user.team_id,
            content=inbox_data.content,
            send_type=SendMessageType.DIRECT.value if receiver.is_user else SendMessageType.CHANNEL.value,
            message_type=inbox_data.message_type
        )

        chat_sender, chat_receivers = cls._increase_chats_offset(user.id, inbox_data.chat_id, user.team_id, receiver.is_user)

        try:
            new_message = MessageDatabaseClient.add_message(new_message)
            if inbox_data.mentions is not None:
                MentionService.save_mentions(new_message, inbox_data.mentions)
            MessageDatabaseClient.add_or_update_chat(chat_sender)
            for chat_receiver in chat_receivers:
                MessageDatabaseClient.add_or_update_chat(chat_receiver)
            DatabaseClient.commit()
            NotificationService.notify_message(new_message, receiver.is_user)
            cls.logger().info(f"Message sent from user #{new_message.sender_id} to client #{new_message.receiver_id}.")
        except IntegrityError:
            DatabaseClient.rollback()
            if UserDatabaseClient.get_client_by_id(inbox_data.chat_id) is None:
                cls.logger().error(f"User #{new_message.sender_id} trying to sent a message to an nonexistent user.")
                raise UserNotFoundError("User not found.", UserResponseStatus.USER_NOT_FOUND.value)
            else:
                cls.logger().error(f"Failing to send message from user #{new_message.sender_id} to client"
                                   f" #{inbox_data.chat_id}.")
                return UnsuccessfulMessageSentResponse("Couldn't sent message.")
        except FlushError:
            cls.logger().error(
                f"Failing to send message from user #{new_message.sender_id} to client #{inbox_data.chat_id} "
                f"due to DB problems.")
            return UnsuccessfulMessageSentResponse("Couldn't sent message.")
        else:
            return SuccessfulMessageSentResponse("Message sent")
示例#9
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.")
示例#10
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.")
示例#11
0
    def update_user(cls, update_data):
        user = Authenticator.authenticate(update_data)

        user.username = \
            update_data.updated_user["username"] if "username" in update_data.updated_user else user.username
        user.email = \
            update_data.updated_user["email"] if "email" in update_data.updated_user else user.email
        user.password = \
            hashing.hash(
                update_data.updated_user["password"]) if "password" in update_data.updated_user else user.password
        user.first_name = \
            update_data.updated_user["first_name"] if "first_name" in update_data.updated_user else user.first_name
        user.last_name = \
            update_data.updated_user["last_name"] if "last_name" in update_data.updated_user else user.last_name
        user.profile_pic = \
            update_data.updated_user["profile_pic"] if "profile_pic" in update_data.updated_user else user.profile_pic

        try:
            UserDatabaseClient.update_user(user)
            DatabaseClient.commit()
            cls.logger().info(f"User {user.id} information updated.")
            return SuccessfulUserResponse(user)
        except IntegrityError:
            DatabaseClient.rollback()
            new_username = update_data.updated_user.get("username")
            new_email = update_data.updated_user.get("email")

            if UserDatabaseClient.get_user_by_username(
                    new_username) is not None:
                cls.logger().info(
                    f"Name {new_email} is taken for another user.")
                return BadRequestUserMessageResponse(
                    f"Name {new_username} is already in use!",
                    UserResponseStatus.ALREADY_REGISTERED.value)
            elif UserDatabaseClient.get_user_by_email(new_email) is not None:
                cls.logger().info(
                    f"Email {new_email} is taken for another user.")
                return BadRequestUserMessageResponse(
                    f"Email {new_email} is already in use!",
                    UserResponseStatus.ALREADY_REGISTERED.value)
            else:
                cls.logger().error(
                    f"Couldn't update user {user.id} information.")
                return UnsuccessfulClientResponse(
                    "Couldn't update user information!")
示例#12
0
    def create_user(cls, user_data):
        if UserDatabaseClient.get_user_by_username(
                user_data.username) is not None:
            cls.logger().info(
                f"Failing to create user #{user_data.username}. Username already in use."
            )
            return BadRequestUserMessageResponse(
                "Username already in use for other user.",
                UserResponseStatus.ALREADY_REGISTERED.value)
        try:
            new_client = UserDatabaseClient.add_client()
            new_user = User(user_id=new_client.id,
                            username=user_data.username,
                            email=user_data.email,
                            password=hashing.hash(user_data.password),
                            first_name=user_data.first_name,
                            last_name=user_data.last_name,
                            profile_pic=user_data.profile_pic,
                            role=user_data.role or UserRoles.USER.value,
                            token=Authenticator.generate(
                                new_client.id, user_data.password))
            UserDatabaseClient.add_user(new_user)
            DatabaseClient.commit()
            cls.logger().info(f"User #{new_client.id} created.")
            headers = {"auth_token": new_user.token}
            return SuccessfulUserResponse(new_user, headers)

        except IntegrityError as exc:
            DatabaseClient.rollback()
            if UserDatabaseClient.get_user_by_email(
                    user_data.email) is not None:
                cls.logger().info(
                    f"Failing to create user {user_data.username}. Email already in use.",
                    exc)
                return BadRequestUserMessageResponse(
                    "Email already in use for other user.",
                    UserResponseStatus.ALREADY_REGISTERED.value)
            else:
                cls.logger().info(
                    f"Failing to create user #{user_data.username}.")
                return UnsuccessfulClientResponse("Couldn't create user.")
        except:
            DatabaseClient.rollback()
            cls.logger().info(f"Failing to create user #{user_data.username}.")
            return UnsuccessfulClientResponse("Couldn't create user.")
示例#13
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)
示例#14
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!")
示例#15
0
    def regenerate_token(cls, regenerate_data):
        user = UserDatabaseClient.get_user_by_email(regenerate_data.email)

        if user:
            password_recovery = UserDatabaseClient.get_password_recovery_by_id(
                user.id)

            if password_recovery:
                try:
                    UserDatabaseClient.delete_password_recovery(
                        password_recovery)
                    cls.logger().debug(
                        f"Deleting token recover entry for user {user.id}")
                    user.token = Authenticator.generate(user.id)
                    cls.logger().debug(
                        f"Regenerating token for user {user.id}")
                    user.online = True
                    UserDatabaseClient.update_user(user)
                    DatabaseClient.commit()
                    cls.logger().info(f"Logging in user {user.id}")
                    headers = {"auth_token": user.token}
                    return SuccessfulUserResponse(user, headers)
                except IntegrityError:
                    DatabaseClient.rollback()
                    cls.logger().error(
                        f"Couldn't regenerate token for user #{user.id}.")
                    return UnsuccessfulClientResponse(
                        "Couldn't regenerate token.")
            else:
                cls.logger().info(
                    f"Attempting to recover password for user #{user.id} with no password recovery token."
                )
                return BadRequestUserMessageResponse(
                    "You haven't ask for password recovery!",
                    UserResponseStatus.WRONG_CREDENTIALS.value)
        else:
            cls.logger().info(f"User {regenerate_data.email} not found.")
            raise UserNotFoundError("User not found.",
                                    UserResponseStatus.USER_NOT_FOUND.value)
示例#16
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)
示例#17
0
    def get_messages_from_chat(cls, chat_data):
        user = Authenticator.authenticate_team(chat_data.authentication)
        chat = MessageDatabaseClient.get_chat_by_ids(user.id, chat_data.chat_id, user.team_id)

        if chat is None:
            cls.logger().error(f"User #{user.id} trying to retrieve messages from chat {chat_data.chat_id}, "
                               f"that doesn't exist.")
            raise ChatNotFoundError("Chat not found.", MessageResponseStatus.CHAT_NOT_FOUND.value)
        else:
            is_channel, messages = cls._determinate_messages(user.id, chat_data.chat_id, user.team_id, chat_data.offset)
            unseen_messages = chat.offset
            try:
                chat.offset = 0
                MessageDatabaseClient.add_or_update_chat(chat)
                DatabaseClient.commit()
                cls.logger().error(f"{unseen_messages} messages set as seen for user {user.id} in chat {chat.chat_id}.")
            except IntegrityError:
                DatabaseClient.rollback()
                cls.logger().error(f"Couldn't set seen messages for user {user.id} in chat {chat.chat_id}.")

            cls.logger().info(f"Retrieved {len(messages)} messages from chat {chat_data.chat_id} from user #{user.id}.")
            return MessageListResponse(cls._generate_messages_list(messages, unseen_messages, user.id, user.team_id), is_channel)
示例#18
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)
示例#19
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)