Esempio n. 1
0
 def get_state_instance(self, request):
     if request.method == 'POST':
         if 'ban-jrs' in request.data:
             return TemporaryBanSanction(request.data)
         else:
             return BanSanction(request.POST)
     elif request.method == 'DELETE':
         return DeleteBanSanction(request.data)
     raise ValueError('Method {0} is not supported in this API route.'.format(request.method))
Esempio n. 2
0
 def get_state_instance(self, request):
     if request.method == "POST":
         if "ban-jrs" in request.data:
             return TemporaryBanSanction(request.data)
         else:
             return BanSanction(request.POST)
     elif request.method == "DELETE":
         return DeleteBanSanction(request.data)
     raise ValueError(f"Method {request.method} is not supported in this API route.")
Esempio n. 3
0
def modify_profile(request, user_pk):
    """Modifies sanction of a user if there is a POST request."""

    if not request.user.has_perm('member.change_profile'):
        raise PermissionDenied

    profile = get_object_or_404(Profile, user__pk=user_pk)
    if profile.is_private():
        raise PermissionDenied
    if request.user.profile == profile:
        messages.error(request,
                       _(u'Vous ne pouvez pas vous sanctionner vous-même !'))
        raise PermissionDenied

    if 'ls' in request.POST:
        state = ReadingOnlySanction(request.POST)
    elif 'ls-temp' in request.POST:
        state = TemporaryReadingOnlySanction(request.POST)
    elif 'ban' in request.POST:
        state = BanSanction(request.POST)
    elif 'ban-temp' in request.POST:
        state = TemporaryBanSanction(request.POST)
    elif 'un-ls' in request.POST:
        state = DeleteReadingOnlySanction(request.POST)
    else:
        # un-ban
        state = DeleteBanSanction(request.POST)

    try:
        ban = state.get_sanction(request.user, profile.user)
    except ValueError:
        raise HttpResponseBadRequest

    state.apply_sanction(profile, ban)

    if 'un-ls' in request.POST or 'un-ban' in request.POST:
        msg = state.get_message_unsanction()
    else:
        msg = state.get_message_sanction()

    msg = msg.format(ban.user, ban.moderator, ban.type, state.get_detail(),
                     ban.note, settings.ZDS_APP['site']['litteral_name'])

    state.notify_member(ban, msg)
    return redirect(profile.get_absolute_url())
    def import_users(self):
        print("\nImporting users...")

        with self.connection.cursor(MySQLdb.cursors.DictCursor) as cursor:
            cursor.execute("SELECT COUNT(*) AS users_count FROM fluxbb_users")
            users_count = cursor.fetchone()['users_count']

            print("{} users to be imported".format(users_count))

            # TODO add location support into the new site
            cursor.execute('SELECT '
                           'fluxbb_users.id AS user_id, '
                           'fluxbb_users.username AS username, '
                           'fluxbb_users.email AS email, '
                           'fluxbb_users.url AS website, '
                           'fluxbb_users.signature AS signature, '
                           'fluxbb_users.show_sig AS show_signature, '
                           'fluxbb_users.registered AS registration_date, '
                           'fluxbb_users.last_visit AS last_visit, '
                           'fluxbb_users.admin_note AS admin_note, '
                           'fluxbb_users.title AS title, '
                           'fluxbb_groups.g_title AS group_name, '
                           '('
                           '  SELECT fluxbb_users.username'
                           '  FROM fluxbb_users'
                           '  WHERE fluxbb_users.id = fluxbb_bans.ban_creator'
                           ') AS ban_creator_username, '
                           'fluxbb_bans.expire AS ban_expiration, '
                           'fluxbb_bans.message AS ban_message '
                           'FROM fluxbb_users '
                           'INNER JOIN fluxbb_groups ON fluxbb_groups.g_id = fluxbb_users.group_id '
                           'LEFT OUTER JOIN fluxbb_bans ON fluxbb_bans.username = fluxbb_users.username '
                           'ORDER BY fluxbb_users.id')

            imported = 0
            for row in cursor.fetchall():
                if self.decode(row['username']) is 'Guest':
                    continue

                user = self.create_user(self.decode(row['username']))
                profile = user.profile

                # User data
                user.email = self.decode(row['email'])
                user.date_joined = datetime.datetime.fromtimestamp(row['registration_date'])
                user.last_login = datetime.datetime.fromtimestamp(row['last_visit'])

                profile.last_visit = user.last_login

                # Groups
                user.groups.add(self.member_group)

                group_name = unicode(row['group_name'], self.encoding)
                if group_name == 'Administrateurs':
                    user.groups.add(self.admin_group)
                    user.is_superuser = True
                elif group_name == 'Gardiens' or group_name == 'Modérateur':
                    user.groups.add(self.staff_group)
                elif group_name == 'Animateur':
                    user.groups.add(self.animator_group)

                # Profile
                profile.title = self.decode(row['title']) if row['title'] is not None else ''
                profile.site = self.decode(row['website']) if row['website'] is not None else ''

                # TODO Markdown conversion
                profile.sign = self.decode(row['signature']) if row['signature'] is not None else ''
                profile.show_sign = bool(row['show_signature'])

                # Avatar
                # FluxBB doesn't store the avatar URL, but retries each time to find the file type,
                # checking if the file exists for the three allowed extensions. Yes.
                avatar_url_pattern = 'https://forum.zcraft.fr/img/avatars/{}.{}'
                extensions = ['jpg', 'png', 'gif']
                for extension in extensions:
                    avatar_url = avatar_url_pattern.format(row['user_id'], extension)
                    r = requests.get(avatar_url)
                    if r.status_code == 200:
                        profile.set_avatar_from_file(StringIO(r.content), filename='avatar.{}'.format(extension))

                user.save()
                profile.save()

                # Administrative note imported as a karma note with score = 0
                if row['admin_note']:
                    KarmaNote(user=user, staff=user, comment=self.decode(row['admin_note']), value=0).save()

                # Bans
                if row['ban_creator_username']:
                    if row['ban_message']:
                        ban_message = self.decode(row['ban_message'])
                    else:
                        ban_message = 'Bannissement : aucun motif donné'

                    # A ban with an expiration date
                    if row['ban_expiration']:
                        days = (datetime.datetime.fromtimestamp(row['ban_expiration']) - datetime.datetime.now()).days
                        if days > 0:
                            state = TemporaryBanSanction({
                                'ban-text': ban_message,
                                'ban-jrs': days
                            })
                            karma_score = -10
                        else:
                            state = None
                            karma_score = 0
                    else:
                        state = BanSanction({
                            'ban-text': ban_message
                        })
                        karma_score = -20

                    if state:
                        try:
                            moderator = User.objects.filter(username=self.decode(row['ban_creator_username'])).first()
                            if not moderator:
                                moderator = User.objects.filter(username=ZDS_APP['member']['bot_account']).first()

                            ban = state.get_sanction(moderator, user)
                            state.apply_sanction(profile, ban)

                            KarmaNote(user=user, staff=moderator, comment=ban_message,
                                      value=karma_score).save()

                            profile.karma += karma_score
                            profile.save()

                        except ValueError as e:
                            self.stderr.write(' Unable to import ban for {}: error: {}'.format(user.username, e))

                imported += 1
                percentage = int((float(imported) / float(users_count)) * 100)
                self.print_progress("[{}% - {}/{}] Importing user {}...".format(percentage, imported, users_count,
                                                                                user.username))

        print("\nDone.")