Skip to content

Commit 5e72f21

Browse files
committed
global: users - renaming, refactor ui roles
Signed-off-by: pamfilos <pamfilosf@gmail.com>
1 parent bdb6223 commit 5e72f21

File tree

3 files changed

+85
-70
lines changed

3 files changed

+85
-70
lines changed

cap/modules/schemas/imp.py

Lines changed: 15 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
from itertools import groupby
2626

2727
from invenio_access.models import ActionRoles, ActionUsers
28-
from invenio_access.permissions import Permission, superuser_access
28+
from invenio_access.permissions import Permission
2929
from invenio_cache import current_cache
3030
from sqlalchemy.event import listen
3131

@@ -76,6 +76,11 @@ def _filter_by_deposit_create_access(schemas_list):
7676
]
7777

7878

79+
def _filter_by_admin_access(schemas_list):
80+
"""Return only schemas that user has admin access to."""
81+
return [x for x in schemas_list if AdminSchemaPermission(x).can()]
82+
83+
7984
def _filter_by_record_read_access(schemas_list):
8085
"""Return only schemas that user has read access to."""
8186
return [
@@ -102,6 +107,14 @@ def get_cached_indexed_schemas_for_user_create(latest=True, user_id=None):
102107
return schemas
103108

104109

110+
@current_cache.memoize()
111+
def get_cached_indexed_schemas_for_user_admin(latest=True, user_id=None):
112+
"""Return all indexed schemas current user has read access to."""
113+
schemas = get_indexed_schemas(latest=latest)
114+
schemas = _filter_by_admin_access(schemas)
115+
return schemas
116+
117+
105118
@current_cache.memoize()
106119
def get_cached_indexed_schemas_for_user_read(latest=True, user_id=None):
107120
"""Return all indexed schemas current user has read access to."""
@@ -154,41 +167,6 @@ def _filter_by_read_access(schemas_list):
154167
return [x for x in schemas_list if ReadSchemaPermission(x).can()]
155168

156169

157-
def _filter_by_admin_access(schemas_list):
158-
"""Return only schemas that user has admin access to."""
159-
return [x for x in schemas_list if AdminSchemaPermission(x).can()]
160-
161-
162-
def is_super_user():
163-
return Permission(superuser_access).can()
164-
165-
166-
def get_admin_roles_for_user(latest=True):
167-
"""Return list of roles in schemas, current user has admin/superuser access to."""
168-
roles = []
169-
schemas = get_indexed_schemas(latest=latest)
170-
schemas = _filter_by_admin_access(schemas)
171-
if latest:
172-
schemas = _filter_only_latest(schemas)
173-
174-
for schema in schemas:
175-
roles.append(f"{schema.name}")
176-
177-
return roles
178-
179-
180-
def generate_roles(mapping):
181-
roles = []
182-
for method_name, method in mapping.items():
183-
result = method()
184-
if isinstance(result, bool) and result:
185-
roles.append(method_name)
186-
elif isinstance(result, list):
187-
for role in result:
188-
roles.append(f"{method_name}:{role}")
189-
return roles
190-
191-
192170
def get_schemas_for_user(latest=True):
193171
"""Return all schemas current user has read access to."""
194172
schemas = Schema.query.order_by(
@@ -233,6 +211,7 @@ def clear_schema_access_cache(mapper, connection, target):
233211
):
234212
get_cached_indexed_schemas_for_user_create.delete_memoized()
235213
get_cached_indexed_schemas_for_user_read.delete_memoized()
214+
get_cached_indexed_schemas_for_user_admin.delete_memoized()
236215
get_cached_indexed_record_schemas_for_user_create.delete_memoized()
237216
get_cached_indexed_record_schemas_for_user_read.delete_memoized()
238217

cap/modules/user/utils.py

Lines changed: 67 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -26,28 +26,68 @@
2626
import ldap
2727
from cachetools.func import lru_cache
2828
from flask import current_app
29-
from sqlalchemy.orm.exc import NoResultFound
30-
from werkzeug.local import LocalProxy
31-
29+
from flask_login import current_user
30+
from invenio_access.permissions import Permission, superuser_access
3231
from invenio_accounts.models import Role, User
3332
from invenio_oauthclient.models import RemoteAccount
33+
from sqlalchemy.orm.exc import NoResultFound
34+
from werkzeug.local import LocalProxy
3435

3536
from .errors import DoesNotExistInLDAP
3637

3738
_datastore = LocalProxy(lambda: current_app.extensions['security'].datastore)
3839

3940

41+
def is_super_user():
42+
return Permission(superuser_access).can()
43+
44+
45+
def get_admin_roles_for_user(latest=True):
46+
"""Return list of schemas user can admin."""
47+
from cap.modules.schemas.imp import (
48+
get_cached_indexed_schemas_for_user_admin,
49+
)
50+
51+
roles = []
52+
schemas = get_cached_indexed_schemas_for_user_admin(
53+
latest=latest, user_id=current_user.id
54+
)
55+
56+
for schema in schemas:
57+
roles.append(f"{schema.name}")
58+
59+
return roles
60+
61+
62+
USER_UI_ROLES = {
63+
'superuser': is_super_user,
64+
'schema-admin': get_admin_roles_for_user,
65+
}
66+
67+
68+
def get_user_ui_roles():
69+
roles = []
70+
for method_name, method in USER_UI_ROLES.items():
71+
result = method()
72+
if isinstance(result, bool) and result:
73+
roles.append(method_name)
74+
elif isinstance(result, list):
75+
for role in result:
76+
roles.append(f"{method_name}:{role}")
77+
return roles
78+
79+
4080
def _query_ldap(base, query, fields):
4181
lc = ldap.initialize('ldap://xldap.cern.ch')
42-
lc.search_ext(base,
43-
ldap.SCOPE_ONELEVEL,
44-
query,
45-
fields,
46-
serverctrls=[
47-
ldap.controls.SimplePagedResultsControl(True,
48-
size=7,
49-
cookie='')
50-
])
82+
lc.search_ext(
83+
base,
84+
ldap.SCOPE_ONELEVEL,
85+
query,
86+
fields,
87+
serverctrls=[
88+
ldap.controls.SimplePagedResultsControl(True, size=7, cookie='')
89+
],
90+
)
5191

5292
return lc.result()[1]
5393

@@ -60,16 +100,20 @@ def get_user_mail_from_ldap(display_name):
60100
res = _query_ldap(
61101
base='OU=Users,OU=Organic Units,DC=cern,DC=ch',
62102
query='(&(cernAccountType=Primary)(displayName={}))'.format(
63-
display_name),
64-
fields=['mail'])
103+
display_name
104+
),
105+
fields=['mail'],
106+
)
65107

66108
if not res:
67109
parts = display_name.split(' ')
68110
res = _query_ldap(
69111
base='OU=Users,OU=Organic Units,DC=cern,DC=ch',
70112
query='(&(cernAccountType=Primary)(givenName={}*)(sn=*{}))'.format(
71-
parts[0], parts[-1]),
72-
fields=['mail'])
113+
parts[0], parts[-1]
114+
),
115+
fields=['mail'],
116+
)
73117

74118
if len(res) != 1:
75119
raise DoesNotExistInLDAP
@@ -85,16 +129,19 @@ def does_user_exist_in_ldap(mail):
85129
res = _query_ldap(
86130
base='OU=Users,OU=Organic Units,DC=cern,DC=ch',
87131
query='(&(cernAccountType=Primary)(mail={}))'.format(mail),
88-
fields=['mail'])
132+
fields=['mail'],
133+
)
89134

90135
return True if res else False
91136

92137

93138
def does_egroup_exist_in_ldap(mail):
94139
"""Query ldap to check if user exists."""
95-
res = _query_ldap(base='OU=e-groups,OU=Workgroups,DC=cern,DC=ch',
96-
query='mail={}'.format(mail),
97-
fields=['mail'])
140+
res = _query_ldap(
141+
base='OU=e-groups,OU=Workgroups,DC=cern,DC=ch',
142+
query='mail={}'.format(mail),
143+
fields=['mail'],
144+
)
98145

99146
return True if res else False
100147

cap/modules/user/views.py

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -36,25 +36,14 @@
3636

3737
from cap.config import DEBUG
3838
from cap.modules.access.utils import login_required
39-
from cap.modules.schemas.imp import (
40-
get_admin_roles_for_user,
41-
get_cached_indexed_schemas_for_user_create,
42-
generate_roles,
43-
is_super_user,
44-
)
45-
from cap.modules.user.utils import get_remote_account_by_id
39+
from cap.modules.schemas.imp import get_cached_indexed_schemas_for_user_create
40+
from cap.modules.user.utils import get_remote_account_by_id, get_user_ui_roles
4641

4742
_datastore = LocalProxy(lambda: current_app.extensions['security'].datastore)
4843

4944
user_blueprint = Blueprint('cap_user', __name__, template_folder='templates')
5045

5146

52-
USER_UI_ROLES = {
53-
'superuser': is_super_user,
54-
'schema-admin': get_admin_roles_for_user,
55-
}
56-
57-
5847
@user_blueprint.route('/me')
5948
@login_required
6049
def get_user():
@@ -73,7 +62,7 @@ def get_user():
7362
"email": current_user.email,
7463
"deposit_groups": deposit_groups,
7564
"profile": extra_data,
76-
"roles": generate_roles(USER_UI_ROLES),
65+
"roles": get_user_ui_roles(),
7766
}
7867

7968
response = jsonify(_user)

0 commit comments

Comments
 (0)