diff --git a/mediagoblin.ini b/mediagoblin.ini
index 30dacadf..874ebcbd 100644
--- a/mediagoblin.ini
+++ b/mediagoblin.ini
@@ -20,6 +20,9 @@ email_debug_mode = true
# Set to false to disable registrations
allow_registration = true
+# Set to false to disable the ability for users to report offensive content
+allow_reporting = true
+
## Uncomment this to put some user-overriding templates here
# local_templates = %(here)s/user_dev/templates/
diff --git a/mediagoblin/admin/views.py b/mediagoblin/admin/views.py
deleted file mode 100644
index 22ca74a3..00000000
--- a/mediagoblin/admin/views.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# GNU MediaGoblin -- federated, autonomous media hosting
-# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see .
-
-from werkzeug.exceptions import Forbidden
-
-from mediagoblin.db.models import MediaEntry
-from mediagoblin.decorators import require_active_login
-from mediagoblin.tools.response import render_to_response
-
-@require_active_login
-def admin_processing_panel(request):
- '''
- Show the global processing panel for this instance
- '''
- # TODO: Why not a "require_admin_login" decorator throwing a 403 exception?
- if not request.user.is_admin:
- raise Forbidden()
-
- processing_entries = MediaEntry.query.filter_by(state = u'processing').\
- order_by(MediaEntry.created.desc())
-
- # Get media entries which have failed to process
- failed_entries = MediaEntry.query.filter_by(state = u'failed').\
- order_by(MediaEntry.created.desc())
-
- processed_entries = MediaEntry.query.filter_by(state = u'processed').\
- order_by(MediaEntry.created.desc()).limit(10)
-
- # Render to response
- return render_to_response(
- request,
- 'mediagoblin/admin/panel.html',
- {'processing_entries': processing_entries,
- 'failed_entries': failed_entries,
- 'processed_entries': processed_entries})
diff --git a/mediagoblin/auth/tools.py b/mediagoblin/auth/tools.py
index 20c1f5c2..88716e1c 100644
--- a/mediagoblin/auth/tools.py
+++ b/mediagoblin/auth/tools.py
@@ -14,12 +14,14 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
+
import logging
import wtforms
+from sqlalchemy import or_
from mediagoblin import mg_globals
from mediagoblin.tools.crypto import get_timed_signer_url
-from mediagoblin.db.models import User
+from mediagoblin.db.models import User, Privilege
from mediagoblin.tools.mail import (normalize_email, send_email,
email_debug_message)
from mediagoblin.tools.template import render_template
@@ -129,6 +131,14 @@ def register_user(request, register_form):
# Create the user
user = auth.create_user(register_form)
+ # give the user the default privileges
+ default_privileges = [
+ Privilege.query.filter(Privilege.privilege_name==u'commenter').first(),
+ Privilege.query.filter(Privilege.privilege_name==u'uploader').first(),
+ Privilege.query.filter(Privilege.privilege_name==u'reporter').first()]
+ user.all_privileges += default_privileges
+ user.save()
+
# log the user in
request.session['user_id'] = unicode(user.id)
request.session.save()
diff --git a/mediagoblin/auth/views.py b/mediagoblin/auth/views.py
index 8563195f..dc03515b 100644
--- a/mediagoblin/auth/views.py
+++ b/mediagoblin/auth/views.py
@@ -17,7 +17,7 @@
from itsdangerous import BadSignature
from mediagoblin import messages, mg_globals
-from mediagoblin.db.models import User
+from mediagoblin.db.models import User, Privilege
from mediagoblin.tools.crypto import get_timed_signer_url
from mediagoblin.decorators import auth_enabled, allow_registration
from mediagoblin.tools.response import render_to_response, redirect, render_404
@@ -147,9 +147,12 @@ def verify_email(request):
user = User.query.filter_by(id=int(token)).first()
- if user and user.email_verified is False:
- user.status = u'active'
- user.email_verified = True
+ if user and user.has_privilege(u'active') is False:
+ user.verification_key = None
+ user.all_privileges.append(
+ Privilege.query.filter(
+ Privilege.privilege_name==u'active').first())
+
user.save()
messages.add_message(
@@ -183,7 +186,7 @@ def resend_activation(request):
return redirect(request, 'mediagoblin.auth.login')
- if request.user.email_verified:
+ if request.user.has_privilege(u'active'):
messages.add_message(
request,
messages.ERROR,
@@ -248,7 +251,7 @@ def forgot_password(request):
success_message=_("An email has been sent with instructions "
"on how to change your password.")
- if user and not(user.email_verified and user.status == 'active'):
+ if user and not(user.has_privilege(u'active')):
# Don't send reminder because user is inactive or has no verified email
messages.add_message(request,
messages.WARNING,
@@ -304,8 +307,8 @@ def verify_forgot_password(request):
return redirect(
request, 'index')
- # check if user active and has email verified
- if user.email_verified and user.status == 'active':
+ # check if user active
+ if user.has_privilege(u'active'):
cp_form = auth_forms.ChangePassForm(formdata_vars)
@@ -325,13 +328,13 @@ def verify_forgot_password(request):
'mediagoblin/auth/change_fp.html',
{'cp_form': cp_form,})
- if not user.email_verified:
+ if not user.has_privilege(u'active'):
messages.add_message(
request, messages.ERROR,
_('You need to verify your email before you can reset your'
' password.'))
- if not user.status == 'active':
+ if not user.has_privilege(u'active'):
messages.add_message(
request, messages.ERROR,
_('You are no longer an active user. Please contact the system'
diff --git a/mediagoblin/config_spec.ini b/mediagoblin/config_spec.ini
index 6f318d64..d738074d 100644
--- a/mediagoblin/config_spec.ini
+++ b/mediagoblin/config_spec.ini
@@ -42,6 +42,9 @@ allow_comments = boolean(default=True)
# Whether comments are ascending or descending
comments_ascending = boolean(default=True)
+# Enable/disable reporting
+allow_reporting = boolean(default=True)
+
# By default not set, but you might want something like:
# "%(here)s/user_dev/templates/"
local_templates = string()
diff --git a/mediagoblin/db/migrations.py b/mediagoblin/db/migrations.py
index 423508f6..5c2a23aa 100644
--- a/mediagoblin/db/migrations.py
+++ b/mediagoblin/db/migrations.py
@@ -19,7 +19,7 @@ import uuid
from sqlalchemy import (MetaData, Table, Column, Boolean, SmallInteger,
Integer, Unicode, UnicodeText, DateTime,
- ForeignKey)
+ ForeignKey, Date)
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import and_
@@ -28,7 +28,8 @@ from migrate.changeset.constraint import UniqueConstraint
from mediagoblin.db.extratypes import JSONEncoded, MutationDict
from mediagoblin.db.migration_tools import RegisterMigration, inspect_table
-from mediagoblin.db.models import MediaEntry, Collection, User, MediaComment
+from mediagoblin.db.models import (MediaEntry, Collection, MediaComment, User,
+ Privilege)
MIGRATIONS = {}
@@ -469,9 +470,204 @@ def wants_notifications(db):
"""Add a wants_notifications field to User model"""
metadata = MetaData(bind=db.bind)
user_table = inspect_table(metadata, "core__users")
-
col = Column('wants_notifications', Boolean, default=True)
col.create(user_table)
+ db.commit()
+
+class ReportBase_v0(declarative_base()):
+ __tablename__ = 'core__reports'
+ id = Column(Integer, primary_key=True)
+ reporter_id = Column(Integer, ForeignKey(User.id), nullable=False)
+ report_content = Column(UnicodeText)
+ reported_user_id = Column(Integer, ForeignKey(User.id), nullable=False)
+ created = Column(DateTime, nullable=False, default=datetime.datetime.now)
+ discriminator = Column('type', Unicode(50))
+ resolver_id = Column(Integer, ForeignKey(User.id))
+ resolved = Column(DateTime)
+ result = Column(UnicodeText)
+ __mapper_args__ = {'polymorphic_on': discriminator}
+
+class CommentReport_v0(ReportBase_v0):
+ __tablename__ = 'core__reports_on_comments'
+ __mapper_args__ = {'polymorphic_identity': 'comment_report'}
+
+ id = Column('id',Integer, ForeignKey('core__reports.id'),
+ primary_key=True)
+ comment_id = Column(Integer, ForeignKey(MediaComment.id), nullable=True)
+
+
+
+class MediaReport_v0(ReportBase_v0):
+ __tablename__ = 'core__reports_on_media'
+ __mapper_args__ = {'polymorphic_identity': 'media_report'}
+
+ id = Column('id',Integer, ForeignKey('core__reports.id'), primary_key=True)
+ media_entry_id = Column(Integer, ForeignKey(MediaEntry.id), nullable=True)
+
+class UserBan_v0(declarative_base()):
+ __tablename__ = 'core__user_bans'
+ user_id = Column(Integer, ForeignKey(User.id), nullable=False,
+ primary_key=True)
+ expiration_date = Column(Date)
+ reason = Column(UnicodeText, nullable=False)
+
+class Privilege_v0(declarative_base()):
+ __tablename__ = 'core__privileges'
+ id = Column(Integer, nullable=False, primary_key=True, unique=True)
+ privilege_name = Column(Unicode, nullable=False, unique=True)
+
+class PrivilegeUserAssociation_v0(declarative_base()):
+ __tablename__ = 'core__privileges_users'
+ privilege_id = Column(
+ 'core__privilege_id',
+ Integer,
+ ForeignKey(User.id),
+ primary_key=True)
+ user_id = Column(
+ 'core__user_id',
+ Integer,
+ ForeignKey(Privilege.id),
+ primary_key=True)
+
+PRIVILEGE_FOUNDATIONS_v0 = [{'privilege_name':u'admin'},
+ {'privilege_name':u'moderator'},
+ {'privilege_name':u'uploader'},
+ {'privilege_name':u'reporter'},
+ {'privilege_name':u'commenter'},
+ {'privilege_name':u'active'}]
+
+
+class User_vR1(declarative_base()):
+ __tablename__ = 'rename__users'
+ id = Column(Integer, primary_key=True)
+ username = Column(Unicode, nullable=False, unique=True)
+ email = Column(Unicode, nullable=False)
+ pw_hash = Column(Unicode)
+ created = Column(DateTime, nullable=False, default=datetime.datetime.now)
+ wants_comment_notification = Column(Boolean, default=True)
+ wants_notifications = Column(Boolean, default=True)
+ license_preference = Column(Unicode)
+ url = Column(Unicode)
+ bio = Column(UnicodeText) # ??
+
+@RegisterMigration(18, MIGRATIONS)
+def create_moderation_tables(db):
+
+ # First, we will create the new tables in the database.
+ #--------------------------------------------------------------------------
+ ReportBase_v0.__table__.create(db.bind)
+ CommentReport_v0.__table__.create(db.bind)
+ MediaReport_v0.__table__.create(db.bind)
+ UserBan_v0.__table__.create(db.bind)
+ Privilege_v0.__table__.create(db.bind)
+ PrivilegeUserAssociation_v0.__table__.create(db.bind)
+
+ db.commit()
+
+ # Then initialize the tables that we will later use
+ #--------------------------------------------------------------------------
+ metadata = MetaData(bind=db.bind)
+ privileges_table= inspect_table(metadata, "core__privileges")
+ user_table = inspect_table(metadata, 'core__users')
+ user_privilege_assoc = inspect_table(
+ metadata, 'core__privileges_users')
+
+ # This section initializes the default Privilege foundations, that
+ # would be created through the FOUNDATIONS system in a new instance
+ #--------------------------------------------------------------------------
+ for parameters in PRIVILEGE_FOUNDATIONS_v0:
+ db.execute(privileges_table.insert().values(**parameters))
+
+ db.commit()
+
+ # This next section takes the information from the old is_admin and status
+ # columns and converts those to the new privilege system
+ #--------------------------------------------------------------------------
+ admin_users_ids, active_users_ids, inactive_users_ids = (
+ db.execute(
+ user_table.select().where(
+ user_table.c.is_admin==1)).fetchall(),
+ db.execute(
+ user_table.select().where(
+ user_table.c.is_admin==0).where(
+ user_table.c.status==u"active")).fetchall(),
+ db.execute(
+ user_table.select().where(
+ user_table.c.is_admin==0).where(
+ user_table.c.status!=u"active")).fetchall())
+
+ # Get the ids for each of the privileges so we can reference them ~~~~~~~~~
+ (admin_privilege_id, uploader_privilege_id,
+ reporter_privilege_id, commenter_privilege_id,
+ active_privilege_id) = [
+ db.execute(privileges_table.select().where(
+ privileges_table.c.privilege_name==privilege_name)).first()['id']
+ for privilege_name in
+ [u"admin",u"uploader",u"reporter",u"commenter",u"active"]
+ ]
+
+ # Give each user the appopriate privileges depending whether they are an
+ # admin, an active user or an inactivated user ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ for admin_user in admin_users_ids:
+ admin_user_id = admin_user['id']
+ for privilege_id in [admin_privilege_id, uploader_privilege_id, reporter_privilege_id, commenter_privilege_id, active_privilege_id]:
+ db.execute(user_privilege_assoc.insert().values(
+ core__privilege_id=admin_user_id,
+ core__user_id=privilege_id))
+
+ for active_user in active_users_ids:
+ active_user_id = active_user['id']
+ for privilege_id in [uploader_privilege_id, reporter_privilege_id, commenter_privilege_id, active_privilege_id]:
+ db.execute(user_privilege_assoc.insert().values(
+ core__privilege_id=active_user_id,
+ core__user_id=privilege_id))
+
+ for inactive_user in inactive_users_ids:
+ inactive_user_id = inactive_user['id']
+ for privilege_id in [uploader_privilege_id, reporter_privilege_id, commenter_privilege_id]:
+ db.execute(user_privilege_assoc.insert().values(
+ core__privilege_id=inactive_user_id,
+ core__user_id=privilege_id))
+
+ db.commit()
+
+ # And then, once the information is taken from the is_admin & status columns
+ # we drop all of the vestigial columns from the User table.
+ #--------------------------------------------------------------------------
+ if db.bind.url.drivername == 'sqlite':
+ # SQLite has some issues that make it *impossible* to drop boolean
+ # columns. So, the following code is a very hacky workaround which
+ # makes it possible. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ User_vR1.__table__.create(db.bind)
+ db.commit()
+ new_user_table = inspect_table(metadata, 'rename__users')
+ for row in db.execute(user_table.select()):
+ db.execute(new_user_table.insert().values(
+ username=row.username,
+ email=row.email,
+ pw_hash=row.pw_hash,
+ created=row.created,
+ wants_comment_notification=row.wants_comment_notification,
+ wants_notifications=row.wants_notifications,
+ license_preference=row.license_preference,
+ url=row.url,
+ bio=row.bio))
+
+ db.commit()
+ user_table.drop()
+
+ db.commit()
+ new_user_table.rename("core__users")
+ else:
+ # If the db is not SQLite, this process is much simpler ~~~~~~~~~~~~~~~
+
+ status = user_table.columns['status']
+ email_verified = user_table.columns['email_verified']
+ is_admin = user_table.columns['is_admin']
+ status.drop()
+ email_verified.drop()
+ is_admin.drop()
db.commit()
diff --git a/mediagoblin/db/mixin.py b/mediagoblin/db/mixin.py
index 57b27d83..25ce6642 100644
--- a/mediagoblin/db/mixin.py
+++ b/mediagoblin/db/mixin.py
@@ -46,7 +46,6 @@ class UserMixin(object):
def bio_html(self):
return cleaned_markdown_conversion(self.bio)
-
class GenerateSlugMixin(object):
"""
Mixin to add a generate_slug method to objects.
diff --git a/mediagoblin/db/models.py b/mediagoblin/db/models.py
index 68a2faa0..1514a3aa 100644
--- a/mediagoblin/db/models.py
+++ b/mediagoblin/db/models.py
@@ -23,7 +23,7 @@ import datetime
from sqlalchemy import Column, Integer, Unicode, UnicodeText, DateTime, \
Boolean, ForeignKey, UniqueConstraint, PrimaryKeyConstraint, \
- SmallInteger
+ SmallInteger, Date
from sqlalchemy.orm import relationship, backref, with_polymorphic
from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.sql.expression import desc
@@ -64,15 +64,12 @@ class User(Base, UserMixin):
# point.
email = Column(Unicode, nullable=False)
pw_hash = Column(Unicode)
- email_verified = Column(Boolean, default=False)
created = Column(DateTime, nullable=False, default=datetime.datetime.now)
- status = Column(Unicode, default=u"needs_email_verification", nullable=False)
# Intented to be nullable=False, but migrations would not work for it
# set to nullable=True implicitly.
wants_comment_notification = Column(Boolean, default=True)
wants_notifications = Column(Boolean, default=True)
license_preference = Column(Unicode)
- is_admin = Column(Boolean, default=False, nullable=False)
url = Column(Unicode)
bio = Column(UnicodeText) # ??
uploaded = Column(Integer, default=0)
@@ -85,8 +82,8 @@ class User(Base, UserMixin):
return '<{0} #{1} {2} {3} "{4}">'.format(
self.__class__.__name__,
self.id,
- 'verified' if self.email_verified else 'non-verified',
- 'admin' if self.is_admin else 'user',
+ 'verified' if self.has_privilege(u'active') else 'non-verified',
+ 'admin' if self.has_privilege(u'admin') else 'user',
self.username)
def delete(self, **kwargs):
@@ -108,6 +105,36 @@ class User(Base, UserMixin):
super(User, self).delete(**kwargs)
_log.info('Deleted user "{0}" account'.format(self.username))
+ def has_privilege(self,*priv_names):
+ """
+ This method checks to make sure a user has all the correct privileges
+ to access a piece of content.
+
+ :param priv_names A variable number of unicode objects which rep-
+ -resent the different privileges which may give
+ the user access to this content. If you pass
+ multiple arguments, the user will be granted
+ access if they have ANY of the privileges
+ passed.
+ """
+ if len(priv_names) == 1:
+ priv = Privilege.query.filter(
+ Privilege.privilege_name==priv_names[0]).one()
+ return (priv in self.all_privileges)
+ elif len(priv_names) > 1:
+ return self.has_privilege(priv_names[0]) or \
+ self.has_privilege(*priv_names[1:])
+ return False
+
+ def is_banned(self):
+ """
+ Checks if this user is banned.
+
+ :returns True if self is banned
+ :returns False if self is not
+ """
+ return UserBan.query.get(self.id) is not None
+
class Client(Base):
"""
@@ -675,16 +702,198 @@ class ProcessingNotification(Notification):
'polymorphic_identity': 'processing_notification'
}
-
with_polymorphic(
Notification,
[ProcessingNotification, CommentNotification])
+class ReportBase(Base):
+ """
+ This is the basic report object which the other reports are based off of.
+
+ :keyword reporter_id Holds the id of the user who created
+ the report, as an Integer column.
+ :keyword report_content Hold the explanation left by the repor-
+ -ter to indicate why they filed the
+ report in the first place, as a
+ Unicode column.
+ :keyword reported_user_id Holds the id of the user who created
+ the content which was reported, as
+ an Integer column.
+ :keyword created Holds a datetime column of when the re-
+ -port was filed.
+ :keyword discriminator This column distinguishes between the
+ different types of reports.
+ :keyword resolver_id Holds the id of the moderator/admin who
+ resolved the report.
+ :keyword resolved Holds the DateTime object which descri-
+ -bes when this report was resolved
+ :keyword result Holds the UnicodeText column of the
+ resolver's reasons for resolving
+ the report this way. Some of this
+ is auto-generated
+ """
+ __tablename__ = 'core__reports'
+ id = Column(Integer, primary_key=True)
+ reporter_id = Column(Integer, ForeignKey(User.id), nullable=False)
+ reporter = relationship(
+ User,
+ backref=backref("reports_filed_by",
+ lazy="dynamic",
+ cascade="all, delete-orphan"),
+ primaryjoin="User.id==ReportBase.reporter_id")
+ report_content = Column(UnicodeText)
+ reported_user_id = Column(Integer, ForeignKey(User.id), nullable=False)
+ reported_user = relationship(
+ User,
+ backref=backref("reports_filed_on",
+ lazy="dynamic",
+ cascade="all, delete-orphan"),
+ primaryjoin="User.id==ReportBase.reported_user_id")
+ created = Column(DateTime, nullable=False, default=datetime.datetime.now())
+ discriminator = Column('type', Unicode(50))
+ resolver_id = Column(Integer, ForeignKey(User.id))
+ resolver = relationship(
+ User,
+ backref=backref("reports_resolved_by",
+ lazy="dynamic",
+ cascade="all, delete-orphan"),
+ primaryjoin="User.id==ReportBase.resolver_id")
+
+ resolved = Column(DateTime)
+ result = Column(UnicodeText)
+ __mapper_args__ = {'polymorphic_on': discriminator}
+
+ def is_comment_report(self):
+ return self.discriminator=='comment_report'
+
+ def is_media_entry_report(self):
+ return self.discriminator=='media_report'
+
+ def is_archived_report(self):
+ return self.resolved is not None
+
+ def archive(self,resolver_id, resolved, result):
+ self.resolver_id = resolver_id
+ self.resolved = resolved
+ self.result = result
+
+
+class CommentReport(ReportBase):
+ """
+ Reports that have been filed on comments.
+ :keyword comment_id Holds the integer value of the reported
+ comment's ID
+ """
+ __tablename__ = 'core__reports_on_comments'
+ __mapper_args__ = {'polymorphic_identity': 'comment_report'}
+
+ id = Column('id',Integer, ForeignKey('core__reports.id'),
+ primary_key=True)
+ comment_id = Column(Integer, ForeignKey(MediaComment.id), nullable=True)
+ comment = relationship(
+ MediaComment, backref=backref("reports_filed_on",
+ lazy="dynamic"))
+
+
+class MediaReport(ReportBase):
+ """
+ Reports that have been filed on media entries
+ :keyword media_entry_id Holds the integer value of the reported
+ media entry's ID
+ """
+ __tablename__ = 'core__reports_on_media'
+ __mapper_args__ = {'polymorphic_identity': 'media_report'}
+
+ id = Column('id',Integer, ForeignKey('core__reports.id'),
+ primary_key=True)
+ media_entry_id = Column(Integer, ForeignKey(MediaEntry.id), nullable=True)
+ media_entry = relationship(
+ MediaEntry,
+ backref=backref("reports_filed_on",
+ lazy="dynamic"))
+
+class UserBan(Base):
+ """
+ Holds the information on a specific user's ban-state. As long as one of
+ these is attached to a user, they are banned from accessing mediagoblin.
+ When they try to log in, they are greeted with a page that tells them
+ the reason why they are banned and when (if ever) the ban will be
+ lifted
+
+ :keyword user_id Holds the id of the user this object is
+ attached to. This is a one-to-one
+ relationship.
+ :keyword expiration_date Holds the date that the ban will be lifted.
+ If this is null, the ban is permanent
+ unless a moderator manually lifts it.
+ :keyword reason Holds the reason why the user was banned.
+ """
+ __tablename__ = 'core__user_bans'
+
+ user_id = Column(Integer, ForeignKey(User.id), nullable=False,
+ primary_key=True)
+ expiration_date = Column(Date)
+ reason = Column(UnicodeText, nullable=False)
+
+
+class Privilege(Base):
+ """
+ The Privilege table holds all of the different privileges a user can hold.
+ If a user 'has' a privilege, the User object is in a relationship with the
+ privilege object.
+
+ :keyword privilege_name Holds a unicode object that is the recognizable
+ name of this privilege. This is the column
+ used for identifying whether or not a user
+ has a necessary privilege or not.
+
+ """
+ __tablename__ = 'core__privileges'
+
+ id = Column(Integer, nullable=False, primary_key=True)
+ privilege_name = Column(Unicode, nullable=False, unique=True)
+ all_users = relationship(
+ User,
+ backref='all_privileges',
+ secondary="core__privileges_users")
+
+ def __init__(self, privilege_name):
+ '''
+ Currently consructors are required for tables that are initialized thru
+ the FOUNDATIONS system. This is because they need to be able to be con-
+ -structed by a list object holding their arg*s
+ '''
+ self.privilege_name = privilege_name
+
+ def __repr__(self):
+ return "" % (self.privilege_name)
+
+
+class PrivilegeUserAssociation(Base):
+ '''
+ This table holds the many-to-many relationship between User and Privilege
+ '''
+
+ __tablename__ = 'core__privileges_users'
+
+ privilege_id = Column(
+ 'core__privilege_id',
+ Integer,
+ ForeignKey(User.id),
+ primary_key=True)
+ user_id = Column(
+ 'core__user_id',
+ Integer,
+ ForeignKey(Privilege.id),
+ primary_key=True)
+
MODELS = [
- User, Client, RequestToken, AccessToken, NonceTimestamp, MediaEntry, Tag,
- MediaTag, MediaComment, Collection, CollectionItem, MediaFile, FileKeynames,
- MediaAttachmentFile, ProcessingMetaData, Notification, CommentNotification,
- ProcessingNotification, CommentSubscription]
+ User, MediaEntry, Tag, MediaTag, MediaComment, Collection, CollectionItem,
+ MediaFile, FileKeynames, MediaAttachmentFile, ProcessingMetaData,
+ Notification, CommentNotification, ProcessingNotification, Client,
+ CommentSubscription, ReportBase, CommentReport, MediaReport, UserBan,
+ Privilege, PrivilegeUserAssociation,
+ RequestToken, AccessToken, NonceTimestamp]
"""
Foundations are the default rows that are created immediately after the tables
@@ -700,7 +909,13 @@ MODELS = [
FOUNDATIONS = {User:user_foundations}
"""
-FOUNDATIONS = {}
+privilege_foundations = [{'privilege_name':u'admin'},
+ {'privilege_name':u'moderator'},
+ {'privilege_name':u'uploader'},
+ {'privilege_name':u'reporter'},
+ {'privilege_name':u'commenter'},
+ {'privilege_name':u'active'}]
+FOUNDATIONS = {Privilege:privilege_foundations}
######################################################
# Special, migrations-tracking table
diff --git a/mediagoblin/db/util.py b/mediagoblin/db/util.py
index 8431361a..7a0a3a73 100644
--- a/mediagoblin/db/util.py
+++ b/mediagoblin/db/util.py
@@ -67,7 +67,6 @@ def check_collection_slug_used(creator_id, slug, ignore_c_id):
does_exist = Session.query(Collection.id).filter(filt).first() is not None
return does_exist
-
if __name__ == '__main__':
from mediagoblin.db.open import setup_connection_and_db_from_config
diff --git a/mediagoblin/decorators.py b/mediagoblin/decorators.py
index 685d0d98..872dc1f4 100644
--- a/mediagoblin/decorators.py
+++ b/mediagoblin/decorators.py
@@ -22,25 +22,44 @@ from oauthlib.oauth1 import ResourceEndpoint
from mediagoblin import mg_globals as mgg
from mediagoblin import messages
-from mediagoblin.db.models import MediaEntry, User
-from mediagoblin.tools.response import json_response, redirect, render_404
+from mediagoblin.db.models import MediaEntry, User, MediaComment
+from mediagoblin.tools.response import (redirect, render_404,
+ render_user_banned, json_response)
from mediagoblin.tools.translate import pass_to_ugettext as _
from mediagoblin.oauth.tools.request import decode_authorization_header
from mediagoblin.oauth.oauth import GMGRequestValidator
-def require_active_login(controller):
+
+def user_not_banned(controller):
"""
- Require an active login from the user.
+ Requires that the user has not been banned. Otherwise redirects to the page
+ explaining why they have been banned
"""
@wraps(controller)
+ def wrapper(request, *args, **kwargs):
+ if request.user:
+ if request.user.is_banned():
+ return render_user_banned(request)
+ return controller(request, *args, **kwargs)
+
+ return wrapper
+
+
+def require_active_login(controller):
+ """
+ Require an active login from the user. If the user is banned, redirects to
+ the "You are Banned" page.
+ """
+ @wraps(controller)
+ @user_not_banned
def new_controller_func(request, *args, **kwargs):
if request.user and \
- request.user.status == u'needs_email_verification':
+ not request.user.has_privilege(u'active'):
return redirect(
request, 'mediagoblin.user_pages.user_home',
user=request.user.username)
- elif not request.user or request.user.status != u'active':
+ elif not request.user or not request.user.has_privilege(u'active'):
next_url = urljoin(
request.urlgen('mediagoblin.auth.login',
qualified=True),
@@ -53,6 +72,34 @@ def require_active_login(controller):
return new_controller_func
+
+def user_has_privilege(privilege_name):
+ """
+ Requires that a user have a particular privilege in order to access a page.
+ In order to require that a user have multiple privileges, use this
+ decorator twice on the same view. This decorator also makes sure that the
+ user is not banned, or else it redirects them to the "You are Banned" page.
+
+ :param privilege_name A unicode object that is that represents
+ the privilege object. This object is
+ the name of the privilege, as assigned
+ in the Privilege.privilege_name column
+ """
+
+ def user_has_privilege_decorator(controller):
+ @wraps(controller)
+ @require_active_login
+ def wrapper(request, *args, **kwargs):
+ user_id = request.user.id
+ if not request.user.has_privilege(privilege_name):
+ raise Forbidden()
+
+ return controller(request, *args, **kwargs)
+
+ return wrapper
+ return user_has_privilege_decorator
+
+
def active_user_from_url(controller):
"""Retrieve User() from URL pattern and pass in as url_user=...
@@ -75,7 +122,7 @@ def user_may_delete_media(controller):
@wraps(controller)
def wrapper(request, *args, **kwargs):
uploader_id = kwargs['media'].uploader
- if not (request.user.is_admin or
+ if not (request.user.has_privilege(u'admin') or
request.user.id == uploader_id):
raise Forbidden()
@@ -92,7 +139,7 @@ def user_may_alter_collection(controller):
def wrapper(request, *args, **kwargs):
creator_id = request.db.User.query.filter_by(
username=request.matchdict['user']).first().id
- if not (request.user.is_admin or
+ if not (request.user.has_privilege(u'admin') or
request.user.id == creator_id):
raise Forbidden()
@@ -256,6 +303,48 @@ def allow_registration(controller):
return wrapper
+def allow_reporting(controller):
+ """ Decorator for if reporting is enabled"""
+ @wraps(controller)
+ def wrapper(request, *args, **kwargs):
+ if not mgg.app_config["allow_reporting"]:
+ messages.add_message(
+ request,
+ messages.WARNING,
+ _('Sorry, reporting is disabled on this instance.'))
+ return redirect(request, 'index')
+
+ return controller(request, *args, **kwargs)
+
+ return wrapper
+
+def get_optional_media_comment_by_id(controller):
+ """
+ Pass in a MediaComment based off of a url component. Because of this decor-
+ -ator's use in filing Media or Comment Reports, it has two valid outcomes.
+
+ :returns The view function being wrapped with kwarg `comment` set to
+ the MediaComment who's id is in the URL. If there is a
+ comment id in the URL and if it is valid.
+ :returns The view function being wrapped with kwarg `comment` set to
+ None. If there is no comment id in the URL.
+ :returns A 404 Error page, if there is a comment if in the URL and it
+ is invalid.
+ """
+ @wraps(controller)
+ def wrapper(request, *args, **kwargs):
+ if 'comment' in request.matchdict:
+ comment = MediaComment.query.filter_by(
+ id=request.matchdict['comment']).first()
+
+ if comment is None:
+ return render_404(request)
+
+ return controller(request, comment=comment, *args, **kwargs)
+ else:
+ return controller(request, comment=None, *args, **kwargs)
+ return wrapper
+
def auth_enabled(controller):
"""Decorator for if an auth plugin is enabled"""
@@ -272,6 +361,31 @@ def auth_enabled(controller):
return wrapper
+def require_admin_or_moderator_login(controller):
+ """
+ Require a login from an administrator or a moderator.
+ """
+ @wraps(controller)
+ def new_controller_func(request, *args, **kwargs):
+ if request.user and \
+ not request.user.has_privilege(u'admin',u'moderator'):
+
+ raise Forbidden()
+ elif not request.user:
+ next_url = urljoin(
+ request.urlgen('mediagoblin.auth.login',
+ qualified=True),
+ request.url)
+
+ return redirect(request, 'mediagoblin.auth.login',
+ next=next_url)
+
+ return controller(request, *args, **kwargs)
+
+ return new_controller_func
+
+
+
def oauth_required(controller):
""" Used to wrap API endpoints where oauth is required """
@wraps(controller)
@@ -283,7 +397,7 @@ def oauth_required(controller):
error = "Missing required parameter."
return json_response({"error": error}, status=400)
-
+
request_validator = GMGRequestValidator()
resource_endpoint = ResourceEndpoint(request_validator)
valid, request = resource_endpoint.validate_protected_resource_request(
diff --git a/mediagoblin/edit/lib.py b/mediagoblin/edit/lib.py
index aab537a0..6acebc96 100644
--- a/mediagoblin/edit/lib.py
+++ b/mediagoblin/edit/lib.py
@@ -19,6 +19,6 @@ def may_edit_media(request, media):
"""Check, if the request's user may edit the media details"""
if media.uploader == request.user.id:
return True
- if request.user.is_admin:
+ if request.user.has_privilege(u'admin'):
return True
return False
diff --git a/mediagoblin/edit/views.py b/mediagoblin/edit/views.py
index 140f9eec..80590875 100644
--- a/mediagoblin/edit/views.py
+++ b/mediagoblin/edit/views.py
@@ -83,7 +83,7 @@ def edit_media(request, media):
return redirect_obj(request, media)
- if request.user.is_admin \
+ if request.user.has_privilege(u'admin') \
and media.uploader != request.user.id \
and request.method != 'POST':
messages.add_message(
@@ -184,7 +184,7 @@ def legacy_edit_profile(request):
def edit_profile(request, url_user=None):
# admins may edit any user profile
if request.user.username != url_user.username:
- if not request.user.is_admin:
+ if not request.user.has_privilege(u'admin'):
raise Forbidden(_("You can only edit your own profile."))
# No need to warn again if admin just submitted an edited profile
@@ -324,7 +324,7 @@ def edit_collection(request, collection):
return redirect_obj(request, collection)
- if request.user.is_admin \
+ if request.user.has_privilege(u'admin') \
and collection.creator != request.user.id \
and request.method != 'POST':
messages.add_message(
diff --git a/mediagoblin/gmg_commands/users.py b/mediagoblin/gmg_commands/users.py
index e44b0aa9..4a730d9e 100644
--- a/mediagoblin/gmg_commands/users.py
+++ b/mediagoblin/gmg_commands/users.py
@@ -53,8 +53,17 @@ def adduser(args):
entry.username = unicode(args.username.lower())
entry.email = unicode(args.email)
entry.pw_hash = auth.gen_password_hash(args.password)
- entry.status = u'active'
- entry.email_verified = True
+ default_privileges = [
+ db.Privilege.query.filter(
+ db.Privilege.privilege_name==u'commenter').one(),
+ db.Privilege.query.filter(
+ db.Privilege.privilege_name==u'uploader').one(),
+ db.Privilege.query.filter(
+ db.Privilege.privilege_name==u'reporter').one(),
+ db.Privilege.query.filter(
+ db.Privilege.privilege_name==u'active').one()
+ ]
+ entry.all_privileges = default_privileges
entry.save()
print "User created (and email marked as verified)"
@@ -74,7 +83,10 @@ def makeadmin(args):
user = db.User.query.filter_by(
username=unicode(args.username.lower())).one()
if user:
- user.is_admin = True
+ user.all_privileges.append(
+ db.Privilege.query.filter(
+ db.Privilege.privilege_name==u'admin').one()
+ )
user.save()
print 'The user is now Admin'
else:
diff --git a/mediagoblin/admin/__init__.py b/mediagoblin/moderation/__init__.py
similarity index 100%
rename from mediagoblin/admin/__init__.py
rename to mediagoblin/moderation/__init__.py
diff --git a/mediagoblin/moderation/forms.py b/mediagoblin/moderation/forms.py
new file mode 100644
index 00000000..5582abdd
--- /dev/null
+++ b/mediagoblin/moderation/forms.py
@@ -0,0 +1,148 @@
+# GNU MediaGoblin -- federated, autonomous media hosting
+# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+
+import wtforms
+from mediagoblin.tools.translate import lazy_pass_to_ugettext as _
+
+ACTION_CHOICES = [(_(u'takeaway'),_(u'Take away privilege')),
+ (_(u'userban'),_(u'Ban the user')),
+ (_(u'sendmessage'),(u'Send the user a message')),
+ (_(u'delete'),_(u'Delete the content'))]
+
+class MultiCheckboxField(wtforms.SelectMultipleField):
+ """
+ A multiple-select, except displays a list of checkboxes.
+
+ Iterating the field will produce subfields, allowing custom rendering of
+ the enclosed checkbox fields.
+
+ code from http://wtforms.simplecodes.com/docs/1.0.4/specific_problems.html
+ """
+ widget = wtforms.widgets.ListWidget(prefix_label=False)
+ option_widget = wtforms.widgets.CheckboxInput()
+
+
+# ============ Forms for mediagoblin.moderation.user page ================== #
+
+class PrivilegeAddRemoveForm(wtforms.Form):
+ """
+ This form is used by an admin to give/take away a privilege directly from
+ their user page.
+ """
+ privilege_name = wtforms.HiddenField('',[wtforms.validators.required()])
+
+class BanForm(wtforms.Form):
+ """
+ This form is used by an admin to ban a user directly from their user page.
+ """
+ user_banned_until = wtforms.DateField(
+ _(u'User will be banned until:'),
+ format='%Y-%m-%d',
+ validators=[wtforms.validators.optional()])
+ why_user_was_banned = wtforms.TextAreaField(
+ _(u'Why are you banning this User?'),
+ validators=[wtforms.validators.optional()])
+
+# =========== Forms for mediagoblin.moderation.report page ================= #
+
+class ReportResolutionForm(wtforms.Form):
+ """
+ This form carries all the information necessary to take punitive actions
+ against a user who created content that has been reported.
+
+ :param action_to_resolve A list of Unicode objects representing
+ a choice from the ACTION_CHOICES const-
+ -ant. Every choice passed affects what
+ punitive actions will be taken against
+ the user.
+
+ :param targeted_user A HiddenField object that holds the id
+ of the user that was reported.
+
+ :param take_away_privileges A list of Unicode objects which repres-
+ -ent the privileges that are being tak-
+ -en away. This field is optional and
+ only relevant if u'takeaway' is in the
+ `action_to_resolve` list.
+
+ :param user_banned_until A DateField object that holds the date
+ that the user will be unbanned. This
+ field is optional and only relevant if
+ u'userban' is in the action_to_resolve
+ list. If the user is being banned and
+ this field is blank, the user is banned
+ indefinitely.
+
+ :param why_user_was_banned A TextArea object that holds the
+ reason that a user was banned, to disp-
+ -lay to them when they try to log in.
+ This field is optional and only relevant
+ if u'userban' is in the
+ `action_to_resolve` list.
+
+ :param message_to_user A TextArea object that holds a message
+ which will be emailed to the user. This
+ is only relevant if the u'sendmessage'
+ option is in the `action_to_resolve`
+ list.
+
+ :param resolution_content A TextArea object that is required for
+ every report filed. It represents the
+ reasons that the moderator/admin resol-
+ -ved the report in such a way.
+ """
+ action_to_resolve = MultiCheckboxField(
+ _(u'What action will you take to resolve the report?'),
+ validators=[wtforms.validators.optional()],
+ choices=ACTION_CHOICES)
+ targeted_user = wtforms.HiddenField('',
+ validators=[wtforms.validators.required()])
+ take_away_privileges = wtforms.SelectMultipleField(
+ _(u'What privileges will you take away?'),
+ validators=[wtforms.validators.optional()])
+ user_banned_until = wtforms.DateField(
+ _(u'User will be banned until:'),
+ format='%Y-%m-%d',
+ validators=[wtforms.validators.optional()])
+ why_user_was_banned = wtforms.TextAreaField(
+ validators=[wtforms.validators.optional()])
+ message_to_user = wtforms.TextAreaField(
+ validators=[wtforms.validators.optional()])
+ resolution_content = wtforms.TextAreaField()
+
+# ======== Forms for mediagoblin.moderation.report_panel page ============== #
+
+class ReportPanelSortingForm(wtforms.Form):
+ """
+ This form is used for sorting and filtering through different reports in
+ the mediagoblin.moderation.reports_panel view.
+
+ """
+ active_p = wtforms.IntegerField(
+ validators=[wtforms.validators.optional()])
+ closed_p = wtforms.IntegerField(
+ validators=[wtforms.validators.optional()])
+ reported_user = wtforms.IntegerField(
+ validators=[wtforms.validators.optional()])
+ reporter = wtforms.IntegerField(
+ validators=[wtforms.validators.optional()])
+
+class UserPanelSortingForm(wtforms.Form):
+ """
+ This form is used for sorting different reports.
+ """
+ p = wtforms.IntegerField(
+ validators=[wtforms.validators.optional()])
diff --git a/mediagoblin/moderation/routing.py b/mediagoblin/moderation/routing.py
new file mode 100644
index 00000000..ba10bc6d
--- /dev/null
+++ b/mediagoblin/moderation/routing.py
@@ -0,0 +1,38 @@
+# GNU MediaGoblin -- federated, autonomous media hosting
+# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+
+moderation_routes = [
+ ('mediagoblin.moderation.media_panel',
+ '/media/',
+ 'mediagoblin.moderation.views:moderation_media_processing_panel'),
+ ('mediagoblin.moderation.users',
+ '/users/',
+ 'mediagoblin.moderation.views:moderation_users_panel'),
+ ('mediagoblin.moderation.reports',
+ '/reports/',
+ 'mediagoblin.moderation.views:moderation_reports_panel'),
+ ('mediagoblin.moderation.users_detail',
+ '/users//',
+ 'mediagoblin.moderation.views:moderation_users_detail'),
+ ('mediagoblin.moderation.give_or_take_away_privilege',
+ '/users//privilege/',
+ 'mediagoblin.moderation.views:give_or_take_away_privilege'),
+ ('mediagoblin.moderation.ban_or_unban',
+ '/users//ban/',
+ 'mediagoblin.moderation.views:ban_or_unban'),
+ ('mediagoblin.moderation.reports_detail',
+ '/reports//',
+ 'mediagoblin.moderation.views:moderation_reports_detail')]
diff --git a/mediagoblin/moderation/tools.py b/mediagoblin/moderation/tools.py
new file mode 100644
index 00000000..e0337536
--- /dev/null
+++ b/mediagoblin/moderation/tools.py
@@ -0,0 +1,217 @@
+# GNU MediaGoblin -- federated, autonomous media hosting
+# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+
+from mediagoblin import mg_globals
+from mediagoblin.db.models import User, Privilege, UserBan
+from mediagoblin.db.base import Session
+from mediagoblin.tools.mail import send_email
+from mediagoblin.tools.response import redirect
+from datetime import datetime
+from mediagoblin.tools.translate import lazy_pass_to_ugettext as _
+
+def take_punitive_actions(request, form, report, user):
+ message_body =''
+
+ # The bulk of this action is running through all of the different
+ # punitive actions that a moderator could take.
+ if u'takeaway' in form.action_to_resolve.data:
+ for privilege_name in form.take_away_privileges.data:
+ take_away_privileges(user.username, privilege_name)
+ form.resolution_content.data += \
+ u"\n{mod} took away {user}\'s {privilege} privileges.".format(
+ mod=request.user.username,
+ user=user.username,
+ privilege=privilege_name)
+
+ # If the moderator elects to ban the user, a new instance of user_ban
+ # will be created.
+ if u'userban' in form.action_to_resolve.data:
+ user_ban = ban_user(form.targeted_user.data,
+ expiration_date=form.user_banned_until.data,
+ reason=form.why_user_was_banned.data)
+ Session.add(user_ban)
+ form.resolution_content.data += \
+ u"\n{mod} banned user {user} {expiration_date}.".format(
+ mod=request.user.username,
+ user=user.username,
+ expiration_date = (
+ "until {date}".format(date=form.user_banned_until.data)
+ if form.user_banned_until.data
+ else "indefinitely"
+ )
+ )
+
+ # If the moderator elects to send a warning message. An email will be
+ # sent to the email address given at sign up
+ if u'sendmessage' in form.action_to_resolve.data:
+ message_body = form.message_to_user.data
+ form.resolution_content.data += \
+ u"\n{mod} sent a warning email to the {user}.".format(
+ mod=request.user.username,
+ user=user.username)
+
+ if u'delete' in form.action_to_resolve.data and \
+ report.is_comment_report():
+ deleted_comment = report.comment
+ Session.delete(deleted_comment)
+ form.resolution_content.data += \
+ u"\n{mod} deleted the comment.".format(
+ mod=request.user.username)
+ elif u'delete' in form.action_to_resolve.data and \
+ report.is_media_entry_report():
+ deleted_media = report.media_entry
+ deleted_media.delete()
+ form.resolution_content.data += \
+ u"\n{mod} deleted the media entry.".format(
+ mod=request.user.username)
+ report.archive(
+ resolver_id=request.user.id,
+ resolved=datetime.now(),
+ result=form.resolution_content.data)
+
+ Session.add(report)
+ Session.commit()
+ if message_body:
+ send_email(
+ mg_globals.app_config['email_sender_address'],
+ [user.email],
+ _('Warning from')+ '- {moderator} '.format(
+ moderator=request.user.username),
+ message_body)
+
+ return redirect(
+ request,
+ 'mediagoblin.moderation.users_detail',
+ user=user.username)
+
+
+def take_away_privileges(user,*privileges):
+ """
+ Take away all of the privileges passed as arguments.
+
+ :param user A Unicode object representing the target user's
+ User.username value.
+
+ :param privileges A variable number of Unicode objects describing
+ the privileges being taken away.
+
+
+ :returns True If ALL of the privileges were taken away
+ successfully.
+
+ :returns False If ANY of the privileges were not taken away
+ successfully. This means the user did not have
+ (one of) the privilege(s) to begin with.
+ """
+ if len(privileges) == 1:
+ privilege = Privilege.query.filter(
+ Privilege.privilege_name==privileges[0]).first()
+ user = User.query.filter(
+ User.username==user).first()
+ if privilege in user.all_privileges:
+ user.all_privileges.remove(privilege)
+ return True
+ return False
+
+ elif len(privileges) > 1:
+ return (take_away_privileges(user, privileges[0]) and \
+ take_away_privileges(user, *privileges[1:]))
+
+def give_privileges(user,*privileges):
+ """
+ Take away all of the privileges passed as arguments.
+
+ :param user A Unicode object representing the target user's
+ User.username value.
+
+ :param privileges A variable number of Unicode objects describing
+ the privileges being granted.
+
+
+ :returns True If ALL of the privileges were granted successf-
+ -ully.
+
+ :returns False If ANY of the privileges were not granted succ-
+ essfully. This means the user already had (one
+ of) the privilege(s) to begin with.
+ """
+ if len(privileges) == 1:
+ privilege = Privilege.query.filter(
+ Privilege.privilege_name==privileges[0]).first()
+ user = User.query.filter(
+ User.username==user).first()
+ if privilege not in user.all_privileges:
+ user.all_privileges.append(privilege)
+ return True
+ return False
+
+ elif len(privileges) > 1:
+ return (give_privileges(user, privileges[0]) and \
+ give_privileges(user, *privileges[1:]))
+
+def ban_user(user_id, expiration_date=None, reason=None):
+ """
+ This function is used to ban a user. If the user is already banned, the
+ function returns False. If the user is not already banned, this function
+ bans the user using the arguments to build a new UserBan object.
+
+ :returns False if the user is already banned and the ban is not updated
+ :returns UserBan object if there is a new ban that was created.
+ """
+ user_ban =UserBan.query.filter(
+ UserBan.user_id==user_id)
+ if user_ban.count():
+ return False
+ new_user_ban = UserBan(
+ user_id=user_id,
+ expiration_date=expiration_date,
+ reason=reason)
+ return new_user_ban
+
+def unban_user(user_id):
+ """
+ This function is used to unban a user. If the user is not currently banned,
+ nothing happens.
+
+ :returns True if the operation was completed successfully and the user
+ has been unbanned
+ :returns False if the user was never banned.
+ """
+ user_ban = UserBan.query.filter(
+ UserBan.user_id==user_id)
+ if user_ban.count() == 0:
+ return False
+ user_ban.first().delete()
+ return True
+
+def parse_report_panel_settings(form):
+ """
+ This function parses the url arguments to which are used to filter reports
+ in the reports panel view. More filters can be added to make a usuable
+ search function.
+
+ :returns A dictionary of sqlalchemy-usable filters.
+ """
+ filters = {}
+
+ if form.validate():
+ filters['reported_user_id'] = form.reported_user.data
+ filters['reporter_id'] = form.reporter.data
+
+ filters = dict((k, v)
+ for k, v in filters.iteritems() if v)
+
+ return filters
diff --git a/mediagoblin/moderation/views.py b/mediagoblin/moderation/views.py
new file mode 100644
index 00000000..f4de11ad
--- /dev/null
+++ b/mediagoblin/moderation/views.py
@@ -0,0 +1,219 @@
+# GNU MediaGoblin -- federated, autonomous media hosting
+# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+
+
+from mediagoblin.db.models import (MediaEntry, User,ReportBase, Privilege,
+ UserBan)
+from mediagoblin.decorators import (require_admin_or_moderator_login,
+ active_user_from_url, user_has_privilege,
+ allow_reporting)
+from mediagoblin.tools.response import render_to_response, redirect
+from mediagoblin.moderation import forms as moderation_forms
+from mediagoblin.moderation.tools import (take_punitive_actions, \
+ take_away_privileges, give_privileges, ban_user, unban_user, \
+ parse_report_panel_settings)
+from math import ceil
+
+@require_admin_or_moderator_login
+def moderation_media_processing_panel(request):
+ '''
+ Show the global media processing panel for this instance
+ '''
+ processing_entries = MediaEntry.query.filter_by(state = u'processing').\
+ order_by(MediaEntry.created.desc())
+
+ # Get media entries which have failed to process
+ failed_entries = MediaEntry.query.filter_by(state = u'failed').\
+ order_by(MediaEntry.created.desc())
+
+ processed_entries = MediaEntry.query.filter_by(state = u'processed').\
+ order_by(MediaEntry.created.desc()).limit(10)
+
+ # Render to response
+ return render_to_response(
+ request,
+ 'mediagoblin/moderation/media_panel.html',
+ {'processing_entries': processing_entries,
+ 'failed_entries': failed_entries,
+ 'processed_entries': processed_entries})
+
+@require_admin_or_moderator_login
+def moderation_users_panel(request):
+ '''
+ Show the global panel for monitoring users in this instance
+ '''
+ current_page = 1
+ if len(request.args) > 0:
+ form = moderation_forms.UserPanelSortingForm(request.args)
+ if form.validate():
+ current_page = form.p.data or 1
+
+ all_user_list = User.query
+ user_list = all_user_list.order_by(
+ User.created.desc()).offset(
+ (current_page-1)*10).limit(10)
+ last_page = int(ceil(all_user_list.count()/10.))
+
+ return render_to_response(
+ request,
+ 'mediagoblin/moderation/user_panel.html',
+ {'user_list': user_list,
+ 'current_page':current_page,
+ 'last_page':last_page})
+
+@require_admin_or_moderator_login
+def moderation_users_detail(request):
+ '''
+ Shows details about a particular user.
+ '''
+ user = User.query.filter_by(username=request.matchdict['user']).first()
+ active_reports = user.reports_filed_on.filter(
+ ReportBase.resolved==None).limit(5)
+ closed_reports = user.reports_filed_on.filter(
+ ReportBase.resolved!=None).all()
+ privileges = Privilege.query
+ user_banned = UserBan.query.get(user.id)
+ ban_form = moderation_forms.BanForm()
+
+ return render_to_response(
+ request,
+ 'mediagoblin/moderation/user.html',
+ {'user':user,
+ 'privileges': privileges,
+ 'reports':active_reports,
+ 'user_banned':user_banned,
+ 'ban_form':ban_form})
+
+@require_admin_or_moderator_login
+@allow_reporting
+def moderation_reports_panel(request):
+ '''
+ Show the global panel for monitoring reports filed against comments or
+ media entries for this instance.
+ '''
+ filters = []
+ active_settings, closed_settings = {'current_page':1}, {'current_page':1}
+
+ if len(request.args) > 0:
+ form = moderation_forms.ReportPanelSortingForm(request.args)
+ if form.validate():
+ filters = parse_report_panel_settings(form)
+ active_settings['current_page'] = form.active_p.data or 1
+ closed_settings['current_page'] = form.closed_p.data or 1
+ filters = [
+ getattr(ReportBase,key)==val
+ for key,val in filters.viewitems()]
+
+ all_active = ReportBase.query.filter(
+ ReportBase.resolved==None).filter(
+ *filters)
+ all_closed = ReportBase.query.filter(
+ ReportBase.resolved!=None).filter(
+ *filters)
+
+ # report_list and closed_report_list are the two lists of up to 10
+ # items which are actually passed to the user in this request
+ report_list = all_active.order_by(
+ ReportBase.created.desc()).offset(
+ (active_settings['current_page']-1)*10).limit(10)
+ closed_report_list = all_closed.order_by(
+ ReportBase.created.desc()).offset(
+ (closed_settings['current_page']-1)*10).limit(10)
+
+ active_settings['last_page'] = int(ceil(all_active.count()/10.))
+ closed_settings['last_page'] = int(ceil(all_closed.count()/10.))
+ # Render to response
+ return render_to_response(
+ request,
+ 'mediagoblin/moderation/report_panel.html',
+ {'report_list':report_list,
+ 'closed_report_list':closed_report_list,
+ 'active_settings':active_settings,
+ 'closed_settings':closed_settings})
+
+@require_admin_or_moderator_login
+@allow_reporting
+def moderation_reports_detail(request):
+ """
+ This is the page an admin or moderator goes to see the details of a report.
+ The report can be resolved or unresolved. This is also the page that a mod-
+ erator would go to to take an action to resolve a report.
+ """
+ form = moderation_forms.ReportResolutionForm(request.form)
+ report = ReportBase.query.get(request.matchdict['report_id'])
+
+ form.take_away_privileges.choices = [
+ (s.privilege_name,s.privilege_name.title()) \
+ for s in report.reported_user.all_privileges
+ ]
+
+ if request.method == "POST" and form.validate() and not (
+ not request.user.has_privilege(u'admin') and
+ report.reported_user.has_privilege(u'admin')):
+
+ user = User.query.get(form.targeted_user.data)
+ return take_punitive_actions(request, form, report, user)
+
+
+ form.targeted_user.data = report.reported_user_id
+
+ return render_to_response(
+ request,
+ 'mediagoblin/moderation/report.html',
+ {'report':report,
+ 'form':form})
+
+@user_has_privilege(u'admin')
+@active_user_from_url
+def give_or_take_away_privilege(request, url_user):
+ '''
+ A form action to give or take away a particular privilege from a user.
+ Can only be used by an admin.
+ '''
+ form = moderation_forms.PrivilegeAddRemoveForm(request.form)
+ if request.method == "POST" and form.validate():
+ privilege = Privilege.query.filter(
+ Privilege.privilege_name==form.privilege_name.data).one()
+ if not take_away_privileges(
+ url_user.username, form.privilege_name.data):
+
+ give_privileges(url_user.username, form.privilege_name.data)
+ url_user.save()
+
+ return redirect(
+ request,
+ 'mediagoblin.moderation.users_detail',
+ user=url_user.username)
+
+@user_has_privilege(u'admin')
+@active_user_from_url
+def ban_or_unban(request, url_user):
+ """
+ A page to ban or unban a user. Only can be used by an admin.
+ """
+ form = moderation_forms.BanForm(request.form)
+ if request.method == "POST" and form.validate():
+ already_banned = unban_user(url_user.id)
+ same_as_requesting_user = (request.user.id == url_user.id)
+ if not already_banned and not same_as_requesting_user:
+ user_ban = ban_user(url_user.id,
+ expiration_date = form.user_banned_until.data,
+ reason = form.why_user_was_banned.data)
+ user_ban.save()
+ return redirect(
+ request,
+ 'mediagoblin.moderation.users_detail',
+ user=url_user.username)
diff --git a/mediagoblin/routing.py b/mediagoblin/routing.py
index 5961f33b..c2c6d284 100644
--- a/mediagoblin/routing.py
+++ b/mediagoblin/routing.py
@@ -18,7 +18,7 @@ import logging
from mediagoblin.tools.routing import add_route, mount, url_map
from mediagoblin.tools.pluginapi import PluginManager
-from mediagoblin.admin.routing import admin_routes
+from mediagoblin.moderation.routing import moderation_routes
from mediagoblin.auth.routing import auth_routes
@@ -27,8 +27,10 @@ _log = logging.getLogger(__name__)
def get_url_map():
add_route('index', '/', 'mediagoblin.views:root_view')
+ add_route('terms_of_service','/terms_of_service',
+ 'mediagoblin.views:terms_of_service')
mount('/auth', auth_routes)
- mount('/a', admin_routes)
+ mount('/mod', moderation_routes)
import mediagoblin.submit.routing
import mediagoblin.user_pages.routing
diff --git a/mediagoblin/static/css/base.css b/mediagoblin/static/css/base.css
index d96b9200..b9b806f9 100644
--- a/mediagoblin/static/css/base.css
+++ b/mediagoblin/static/css/base.css
@@ -156,6 +156,10 @@ a.logo {
margin: 6px 8px 6px 0;
}
+.fine_print {
+ font-size: 0.8em;
+}
+
.mediagoblin_content {
width: 100%;
padding-bottom: 74px;
@@ -220,6 +224,7 @@ footer {
color: #283F35;
}
+
.button_form {
min-width: 99px;
margin: 10px 0px 10px 15px;
@@ -351,40 +356,40 @@ textarea#description, textarea#bio {
/* comments */
-.comment_wrapper {
+.comment_wrapper, .report_wrapper {
margin-top: 20px;
margin-bottom: 20px;
}
-.comment_wrapper p {
+.comment_wrapper p, .report_wrapper p {
margin-bottom: 2px;
}
-.comment_author {
+.comment_author, .report_author {
padding-top: 4px;
font-size: 0.9em;
}
-a.comment_authorlink {
+a.comment_authorlink, a.report_authorlink {
text-decoration: none;
padding-right: 5px;
font-weight: bold;
padding-left: 2px;
}
-a.comment_authorlink:hover {
+a.comment_authorlink:hover, a.report_authorlink:hover {
text-decoration: underline;
}
-a.comment_whenlink {
+a.comment_whenlink, a.report_whenlink {
text-decoration: none;
}
-a.comment_whenlink:hover {
+a.comment_whenlink:hover, a.report_whenlink:hover {
text-decoration: underline;
}
-.comment_content {
+.comment_content, .report_content {
margin-left: 8px;
margin-top: 8px;
}
@@ -408,6 +413,13 @@ textarea#comment_content {
padding-right: 6px;
}
+
+a.report_authorlink, a.report_whenlink {
+ color: #D486B1;
+}
+
+ul#action_to_resolve {list-style:none; margin-left:10px;}
+
/* media galleries */
.media_thumbnail {
@@ -608,6 +620,38 @@ table.media_panel th {
text-align: left;
}
+/* moderator panels */
+
+table.admin_panel {
+ width: 100%
+}
+
+table.admin_side_panel {
+ width: 60%
+}
+
+table.admin_panel th, table.admin_side_panel th {
+ font-weight: bold;
+ padding-bottom: 4px;
+ text-align: left;
+ color: #fff;
+}
+
+table td.user_with_privilege {
+ font-weight: bold;
+ color: #86D4B1;
+}
+
+table td.user_without_privilege {
+ font-weight: bold;
+ color: #D486B1;
+}
+
+.return_to_panel {
+ text-align:right;
+ float: right;
+ font-size:1.2em
+}
/* Delete panel */
@@ -616,6 +660,27 @@ table.media_panel th {
margin-left: 10px;
}
+/* code of conduct */
+
+#code_of_conduct_list {
+ margin-left:25px;
+ margin-bottom: 10px;
+}
+#code_of_conduct_list li {
+ margin:5px 0 15px 25px;
+}
+#code_of_conduct_list strong{
+ color:#fff;
+}
+
+.nested_sublist {
+ margin: 5px 0 10px 25px;
+ font-size:80%;
+}
+.nested_sublist li {
+ margin-bottom: 10px;
+}
+
/* ASCII art and code */
@font-face {
diff --git a/mediagoblin/static/images/icon_clipboard.png b/mediagoblin/static/images/icon_clipboard.png
new file mode 100644
index 00000000..6f94498b
Binary files /dev/null and b/mediagoblin/static/images/icon_clipboard.png differ
diff --git a/mediagoblin/static/images/icon_clipboard_alert.png b/mediagoblin/static/images/icon_clipboard_alert.png
new file mode 100644
index 00000000..952c588d
Binary files /dev/null and b/mediagoblin/static/images/icon_clipboard_alert.png differ
diff --git a/mediagoblin/static/js/setup_report_forms.js b/mediagoblin/static/js/setup_report_forms.js
new file mode 100644
index 00000000..a75a92dd
--- /dev/null
+++ b/mediagoblin/static/js/setup_report_forms.js
@@ -0,0 +1,67 @@
+/**
+ * GNU MediaGoblin -- federated, autonomous media hosting
+ * Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+function init_report_resolution_form() {
+ hidden_input_names = {
+ 'takeaway':['take_away_privileges'],
+ 'userban':['user_banned_until','why_user_was_banned'],
+ 'sendmessage':['message_to_user']
+}
+ init_user_banned_form();
+ $('form#resolution_form').hide()
+ $('#open_resolution_form').click(function() {
+ $('form#resolution_form').toggle();
+ $.each(hidden_input_names, function(key, list){
+ $.each(list, function(index, name){
+ $('label[for='+name+']').hide();
+ $('#'+name).hide();
+ });
+ });
+ });
+ $('#action_to_resolve').change(function() {
+ $('ul#action_to_resolve li input:checked').each(function() {
+ $.each(hidden_input_names[$(this).val()], function(index, name){
+ $('label[for='+name+']').show();
+ $('#'+name).show();
+ });
+ });
+ $('ul#action_to_resolve li input:not(:checked)').each(function() {
+ $.each(hidden_input_names[$(this).val()], function(index, name){
+ $('label[for='+name+']').hide();
+ $('#'+name).hide();
+ });
+ });
+ });
+ $("#submit_this_report").click(function(){
+ submit_user_banned_form()
+ });
+}
+
+function submit_user_banned_form() {
+ if ($("#user_banned_until").val() == 'YYYY-MM-DD'){
+ $("#user_banned_until").val("");
+ }
+}
+
+function init_user_banned_form() {
+ $('#user_banned_until').val("YYYY-MM-DD")
+ $("#user_banned_until").focus(function() {
+ $(this).val("");
+ $(this).unbind('focus');
+ });
+}
diff --git a/mediagoblin/submit/views.py b/mediagoblin/submit/views.py
index 7f7dee33..e0e2f1a5 100644
--- a/mediagoblin/submit/views.py
+++ b/mediagoblin/submit/views.py
@@ -27,7 +27,7 @@ _log = logging.getLogger(__name__)
from mediagoblin.tools.text import convert_to_tag_list_of_dicts
from mediagoblin.tools.translate import pass_to_ugettext as _
from mediagoblin.tools.response import render_to_response, redirect
-from mediagoblin.decorators import require_active_login
+from mediagoblin.decorators import require_active_login, user_has_privilege
from mediagoblin.submit import forms as submit_forms
from mediagoblin.messages import add_message, SUCCESS
from mediagoblin.media_types import sniff_media, \
@@ -39,6 +39,7 @@ from mediagoblin.notifications import add_comment_subscription
@require_active_login
+@user_has_privilege(u'uploader')
def submit_start(request):
"""
First view for submitting a file.
diff --git a/mediagoblin/templates/mediagoblin/banned.html b/mediagoblin/templates/mediagoblin/banned.html
new file mode 100644
index 00000000..cd54158a
--- /dev/null
+++ b/mediagoblin/templates/mediagoblin/banned.html
@@ -0,0 +1,35 @@
+{#
+# GNU MediaGoblin -- federated, autonomous media hosting
+# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+#}
+{% extends "mediagoblin/base.html" %}
+
+{% block title %}{% trans %}You are Banned.{% endtrans %}{% endblock %}
+
+{% block mediagoblin_content %}
+
+
+ {% trans %}You have been banned{% endtrans %}
+ {% if expiration_date %}
+ {% trans %}until{% endtrans %} {{ expiration_date }}
+ {% else %}
+ {% trans %}indefinitely{% endtrans %}
+ {% endif %}
+
+
{{ reason|safe }}
+
+{% endblock %}
diff --git a/mediagoblin/templates/mediagoblin/base.html b/mediagoblin/templates/mediagoblin/base.html
index f9deb2ad..94ca7aa5 100644
--- a/mediagoblin/templates/mediagoblin/base.html
+++ b/mediagoblin/templates/mediagoblin/base.html
@@ -62,7 +62,7 @@
{% block mediagoblin_header_title %}{% endblock %}