Skip to content

Commit

Permalink
Merge pull request #34777 from dimagi/ad/load-cookie-only-if-can-logi…
Browse files Browse the repository at this point in the history
…n-as

Check loaded login-as cookie when when getting web apps for a user
  • Loading branch information
AddisonDunn authored Jun 27, 2024
2 parents 1773566 + fd26f90 commit 1946602
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions corehq/apps/cloudcare/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,31 +126,38 @@ def get_restore_as_user(request, domain):
if not hasattr(request, 'couch_user'):
raise Http404()

def set_cookie(response): # set_coookie is a noop by default
def set_cookie(response): # set_cookie is a noop by default
return response

def _get_login_as_user_query():
return login_as_user_query(
domain,
request.couch_user,
search_string='',
limit=1,
offset=0
).run()

cookie_name = urllib.parse.quote(
'restoreAs:{}:{}'.format(domain, request.couch_user.username))
username = request.COOKIES.get(cookie_name)
if username:
username = urllib.parse.unquote(username)
username = get_complete_username(username, domain)
user = CouchUser.get_by_username(username)
if user:
if user and request.couch_user.has_permission(domain, "login_as_all_users"):
return user, set_cookie
elif user and request.couch_user.has_permission(domain, "limited_login_as"):
login_as_users = _get_login_as_user_query()
if user._id == login_as_users.hits[0]['_id']:
return user, set_cookie
else:
def set_cookie(response): # overwrite the default noop set_cookie
response.delete_cookie(cookie_name)
return response

elif request.couch_user.has_permission(domain, 'limited_login_as'):
login_as_users = login_as_user_query(
domain,
request.couch_user,
search_string='',
limit=1,
offset=0
).run()
login_as_users = _get_login_as_user_query()
if login_as_users.total == 1:
def set_cookie(response):
response.set_cookie(cookie_name, urllib.parse.quote(user.raw_username))
Expand Down

0 comments on commit 1946602

Please sign in to comment.