Skip to content

Commit

Permalink
Removes the old auth models and their use.
Browse files Browse the repository at this point in the history
Removes all of the old auth models, and contains a migration to delete
the now unused tables.  There are a few components still depending
(secretly behind the scenes) on PackageRole and as a result for this PR
to be complete it needs to re-implement `number_administered_packages``
  • Loading branch information
rossjones committed Dec 16, 2014
1 parent 40a9e59 commit 822fd18
Show file tree
Hide file tree
Showing 19 changed files with 47 additions and 840 deletions.
1 change: 0 additions & 1 deletion ckan/lib/base.py
Expand Up @@ -119,7 +119,6 @@ def render(template_name, extra_vars=None, cache_key=None, cache_type=None,
def render_template():
globs = extra_vars or {}
globs.update(pylons_globals())
globs['actions'] = model.Action

# Using pylons.url() directly destroys the localisation stuff so
# we remove it so any bad templates crash and burn
Expand Down
27 changes: 0 additions & 27 deletions ckan/lib/create_test_data.py
Expand Up @@ -257,7 +257,6 @@ def create_arbitrary(cls, package_dicts, relationships=[],
else:
raise NotImplementedError(attr)
cls.pkg_names.append(item['name'])
model.setup_default_user_roles(pkg, admins=[])
for admin in admins:
admins_list[item['name']].append(admin)
model.repo.commit_and_remove()
Expand Down Expand Up @@ -287,24 +286,9 @@ def create_arbitrary(cls, package_dicts, relationships=[],
model.repo.commit_and_remove()
needs_commit = False

# setup authz for admins
for pkg_name, admins in admins_list.items():
pkg = model.Package.by_name(unicode(pkg_name))
admins_obj_list = []
for admin in admins:
if isinstance(admin, model.User):
admin_obj = admin
else:
admin_obj = model.User.by_name(unicode(admin))
assert admin_obj, admin
admins_obj_list.append(admin_obj)
model.setup_default_user_roles(pkg, admins_obj_list)
needs_commit = True

# setup authz for groups just created
for group_name in new_group_names:
group = model.Group.by_name(unicode(group_name))
model.setup_default_user_roles(group)
cls.group_names.add(group_name)
needs_commit = True

Expand Down Expand Up @@ -390,7 +374,6 @@ def create_groups(cls, group_dicts, admin_user_name=None, auth_profile=""):
member = model.Member(group=group, table_id=parent.id,
table_name='group', capacity='parent')
model.Session.add(member)
#model.setup_default_user_roles(group, admin_users)
cls.group_names.add(group_dict['name'])
model.repo.commit_and_remove()

Expand Down Expand Up @@ -516,23 +499,13 @@ def create(cls, auth_profile="", package_type=None):
cls.user_refs.extend([u'tester', u'joeadmin', u'annafan', u'russianfan', u'testsysadmin'])
model.repo.commit_and_remove()

visitor = model.User.by_name(model.PSEUDO_USER__VISITOR)
anna = model.Package.by_name(u'annakarenina')
war = model.Package.by_name(u'warandpeace')
annafan = model.User.by_name(u'annafan')
russianfan = model.User.by_name(u'russianfan')
model.setup_default_user_roles(anna, [annafan])
model.setup_default_user_roles(war, [russianfan])
model.add_user_to_role(visitor, model.Role.ADMIN, war)
david = model.Group.by_name(u'david')
roger = model.Group.by_name(u'roger')
model.setup_default_user_roles(david, [russianfan])
model.setup_default_user_roles(roger, [russianfan])

# in new_authz you can't give a visitor permissions to a
# group it seems, so this is a bit meaningless
model.add_user_to_role(visitor, model.Role.ADMIN, roger)
model.repo.commit_and_remove()

# method used in DGU and all good tests elsewhere
@classmethod
Expand Down
2 changes: 0 additions & 2 deletions ckan/lib/helpers.py
Expand Up @@ -765,8 +765,6 @@ def get_action(action_name, data_dict=None):


def linked_user(user, maxlength=0, avatar=20):
if user in [model.PSEUDO_USER__LOGGED_IN, model.PSEUDO_USER__VISITOR]:
return user
if not isinstance(user, model.User):
user_name = unicode(user)
user = model.User.get(user_name)
Expand Down
3 changes: 1 addition & 2 deletions ckan/logic/action/create.py
Expand Up @@ -186,7 +186,6 @@ def package_create(context, data_dict):

pkg = model_save.package_dict_save(data, context)

model.setup_default_user_roles(pkg, admins)
# Needed to let extensions know the package id
model.Session.flush()
data['id'] = pkg.id
Expand Down Expand Up @@ -633,7 +632,7 @@ def _group_or_org_create(context, data_dict, is_org=False):
admins = [model.User.by_name(user.decode('utf8'))]
else:
admins = []
model.setup_default_user_roles(group, admins)

# Needed to let extensions know the group id
session.flush()

Expand Down
75 changes: 11 additions & 64 deletions ckan/logic/action/get.py
Expand Up @@ -797,12 +797,12 @@ def user_list(context, data_dict):
model.Revision.author == model.User.name,
model.Revision.author == model.User.openid
)).label('number_of_edits'),
_select([_func.count(model.UserObjectRole.id)],
_and_(
model.UserObjectRole.user_id == model.User.id,
model.UserObjectRole.context == 'Package',
model.UserObjectRole.role == 'admin'
)).label('number_administered_packages')
#_select([_func.count(model.UserObjectRole.id)],
# _and_(
# model.UserObjectRole.user_id == model.User.id,
# model.UserObjectRole.context == 'Package',
# model.UserObjectRole.role == 'admin'
# )).label('number_administered_packages')
)

if q:
Expand Down Expand Up @@ -1334,10 +1334,11 @@ def user_show(context, data_dict):
user_dict['activity'] = revisions_list

user_dict['datasets'] = []
dataset_q = (model.Session.query(model.Package)
.join(model.PackageRole)
.filter_by(user=user_obj, role=model.Role.ADMIN)
.limit(50))
#dataset_q = (model.Session.query(model.Package)
# .join(model.PackageRole)
# .filter_by(user=user_obj, role=model.Role.ADMIN)
# .limit(50))
dataset_q = []

for dataset in dataset_q:
try:
Expand Down Expand Up @@ -2195,60 +2196,6 @@ def get_site_user(context, data_dict):
'apikey': user.apikey}


def roles_show(context, data_dict):
'''Return the roles of all users and authorization groups for an object.
:param domain_object: a package or group name or id
to filter the results by
:type domain_object: string
:param user: a user name or id
:type user: string
:rtype: list of dictionaries
'''
model = context['model']
session = context['session']
domain_object_ref = _get_or_bust(data_dict, 'domain_object')
user_ref = data_dict.get('user')

domain_object = ckan.logic.action.get_domain_object(
model, domain_object_ref)
if isinstance(domain_object, model.Package):
query = session.query(model.PackageRole).join('package')
elif isinstance(domain_object, model.Group):
query = session.query(model.GroupRole).join('group')
elif domain_object is model.System:
query = session.query(model.SystemRole)
else:
raise NotFound(_('Cannot list entity of this type: %s')
% type(domain_object).__name__)
# Filter by the domain_obj (apart from if it is the system object)
if not isinstance(domain_object, type):
query = query.filter_by(id=domain_object.id)

# Filter by the user
if user_ref:
user = model.User.get(user_ref)
if not user:
raise NotFound(_('unknown user:') + repr(user_ref))
query = query.join('user').filter_by(id=user.id)

uors = query.all()

uors_dictized = [_table_dictize(uor, context) for uor in uors]

result = {
'domain_object_type': type(domain_object).__name__,
'domain_object_id':
domain_object.id if domain_object != model.System else None,
'roles': uors_dictized}
if user_ref:
result['user'] = user.id

return result


def status_show(context, data_dict):
'''Return a dictionary with information about the site's configuration.
Expand Down
4 changes: 2 additions & 2 deletions ckan/logic/auth/create.py
Expand Up @@ -214,15 +214,15 @@ def _check_group_auth(context, data_dict):
def package_create_rest(context, data_dict):
model = context['model']
user = context['user']
if user in (model.PSEUDO_USER__VISITOR, ''):
if not user:
return {'success': False, 'msg': _('Valid API key needed to create a package')}

return package_create(context, data_dict)

def group_create_rest(context, data_dict):
model = context['model']
user = context['user']
if user in (model.PSEUDO_USER__VISITOR, ''):
if not user:
return {'success': False, 'msg': _('Valid API key needed to create a group')}

return group_create(context, data_dict)
Expand Down
4 changes: 2 additions & 2 deletions ckan/logic/auth/update.py
Expand Up @@ -276,7 +276,7 @@ def send_email_notifications(context, data_dict):
def package_update_rest(context, data_dict):
model = context['model']
user = context['user']
if user in (model.PSEUDO_USER__VISITOR, ''):
if not user:
return {'success': False,
'msg': _('Valid API key needed to edit a package')}

Expand All @@ -286,7 +286,7 @@ def package_update_rest(context, data_dict):
def group_update_rest(context, data_dict):
model = context['model']
user = context['user']
if user in (model.PSEUDO_USER__VISITOR, ''):
if not user:
return {'success': False,
'msg': _('Valid API key needed to edit a group')}

Expand Down
14 changes: 14 additions & 0 deletions ckan/migration/versions/075_remove_old_authz_model.py
@@ -0,0 +1,14 @@
import ckan.model


def upgrade(migrate_engine):
migrate_engine.execute(
'''
DROP TABLE "role_action";
DROP TABLE "package_role";
DROP TABLE "group_role";
DROP TABLE "system_role";
DROP TABLE "authorization_group_role";
DROP TABLE "user_object_role";
'''
)
39 changes: 0 additions & 39 deletions ckan/model/__init__.py
Expand Up @@ -44,28 +44,6 @@
User,
user_table,
)
from authz import (
NotRealUserException,
Enum,
Action,
Role,
RoleAction,
UserObjectRole,
PackageRole,
GroupRole,
SystemRole,
PSEUDO_USER__VISITOR,
PSEUDO_USER__LOGGED_IN,
init_authz_const_data,
init_authz_configuration_data,
add_user_to_role,
setup_user_roles,
setup_default_user_roles,
give_all_packages_default_user_roles,
user_has_role,
remove_user_from_role,
clear_user_roles,
)
from group import (
Member,
Group,
Expand Down Expand Up @@ -239,22 +217,9 @@ def clean_db(self):
self.tables_created_and_initialised = False
log.info('Database tables dropped')

def init_const_data(self):
'''Creates 'constant' objects that should always be there in
the database. If they are already there, this method does nothing.'''
for username in (PSEUDO_USER__LOGGED_IN,
PSEUDO_USER__VISITOR):
if not User.by_name(username):
user = User(name=username)
meta.Session.add(user)
meta.Session.flush() # so that these objects can be used
# straight away
init_authz_const_data()

def init_configuration_data(self):
'''Default configuration, for when CKAN is first used out of the box.
This state may be subsequently configured by the user.'''
init_authz_configuration_data()
if meta.Session.query(Revision).count() == 0:
rev = Revision()
rev.author = 'system'
Expand All @@ -268,7 +233,6 @@ def create_db(self):
has shortcuts.
'''
self.metadata.create_all(bind=self.metadata.bind)
self.init_const_data()
self.init_configuration_data()
log.info('Database tables created')

Expand All @@ -283,7 +247,6 @@ def rebuild_db(self):
# just delete data, leaving tables - this is faster
self.delete_all()
# re-add default data
self.init_const_data()
self.init_configuration_data()
self.session.commit()
else:
Expand Down Expand Up @@ -336,8 +299,6 @@ def upgrade_db(self, version=None):
else:
log.info('CKAN database version remains as: %s', version_after)

self.init_const_data()

##this prints the diffs in a readable format
##import pprint
##from migrate.versioning.schemadiff import getDiffOfModelAgainstDatabase
Expand Down

0 comments on commit 822fd18

Please sign in to comment.