Skip to content

Commit

Permalink
Fix #6205 & Fix #6119
Browse files Browse the repository at this point in the history
  • Loading branch information
robnagler committed Aug 7, 2023
1 parent 3eb443d commit e6c4cdb
Show file tree
Hide file tree
Showing 10 changed files with 72 additions and 40 deletions.
46 changes: 34 additions & 12 deletions sirepo/auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from pykern import pkconfig
from pykern import pkinspect
from pykern.pkcollections import PKDict
from pykern.pkdebug import pkdc, pkdlog, pkdp
from pykern.pkdebug import pkdc, pkdlog, pkdp, pkdexc
import contextlib
import datetime
import importlib
Expand Down Expand Up @@ -438,7 +438,26 @@ def need_complete_registration(self, model_or_uid):
return not self.user_display_name(uid=u)

def only_for_api_auth_state(self):
return self._auth_state()
try:
try:
return self._auth_state()
except sirepo.util.UserDirNotFound as e:
# Clear login and return new auth_state
self._handle_user_dir_not_found(**e.sr_args)
return self._auth_state()
except Exception as e:
pkdlog("exception={}", e, " stack={}", pkdexc())
# POSIT: minimal authState record, see _auth_state
return PKDict(
displayName=None,
guestIsOnlyMethod=not non_guest_methods,
isGuestUser=False,
isLoggedIn=False,
roles=[],
userName=None,
uiWebSocket=sirepo.feature_config.cfg().ui_websocket,
visibleMethods=visible_methods,
)

def only_for_api_logout(self):
sirepo.events.emit(
Expand Down Expand Up @@ -551,16 +570,7 @@ def user_dir_not_found(self, user_dir, uid):
user_dir (str): directory not found
uid (str): user
"""
for m in _METHOD_MODULES.values():
u = self._method_user_model(m, uid)
if u:
u.delete()
u = self.qcall.auth_db.model("UserRegistration").unchecked_search_by(uid=uid)
if u:
u.delete()
self.reset_state()
self.qcall.auth_db.commit()
pkdlog("user_dir={} uid={}", user_dir, uid)
self._handle_user_dir_not_found(user_dir, uid)
return self.qcall.reply_redirect_for_app_root()

def user_display_name(self, uid):
Expand Down Expand Up @@ -680,6 +690,18 @@ def _create_user(self, module, want_login):
self._create_roles_for_new_user(module.AUTH_METHOD)
return u

def _handle_user_dir_not_found(self, user_dir, uid):
for m in _METHOD_MODULES.values():
u = self._method_user_model(m, uid)
if u:
u.delete()
u = self.qcall.auth_db.model("UserRegistration").unchecked_search_by(uid=uid)
if u:
u.delete()
self.reset_state()
self.qcall.auth_db.commit()
pkdlog("user_dir={} uid={}", user_dir, uid)

def _login_user(self, module, uid):
"""Set up the cookie for logged in state
Expand Down
5 changes: 5 additions & 0 deletions sirepo/package_data/static/js/sirepo.js
Original file line number Diff line number Diff line change
Expand Up @@ -2167,6 +2167,11 @@ SIREPO.app.factory('msgRouter', ($http, $interval, $q, $window, errorService) =>

self.send = (url, data, httpConfig) => {
if (! SIREPO.authState.uiWebSocket || ! _isAuthenticated() || _isAuthUrl(url)) {
// Might be auto logged out so close socket so can re-authenticate
if (socket) {
socket.close();
socket = null;
}
return data == null ? $http.get(url, httpConfig)
: $http.post(url, data, httpConfig);
}
Expand Down
25 changes: 19 additions & 6 deletions sirepo/srunit.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,12 +193,12 @@ def sr_auth_state(self, **kwargs):
Returns:
dict: parsed auth_state
"""
from pykern import pkunit
from pykern import pkcollections
from pykern import pkunit, pkcollections
from pykern.pkdebug import pkdp

m = re.search(
r"(\{.*\})",
pkcompat.from_bytes(self.sr_get("authState").data),
pkdp(pkcompat.from_bytes(self.sr_get("authState").data)),
)
s = pkcollections.json_load_any(m.group(1))
for k, v in kwargs.items():
Expand Down Expand Up @@ -694,6 +694,9 @@ def change_to_redirect(self, uri):


class _WebSocket:

_AUTH_RE = re.compile(r"/auth-|https?:")

def __init__(self, test_client):
self._enabled = False
self._connection = None
Expand Down Expand Up @@ -724,11 +727,21 @@ def _marshall_req():
return m

def _must_be_http():
# POSIT: /auth- match like sirepo.js msgRouter
return headers or uri.startswith("/auth-") or not self._enabled
# POSIT: /auth- match like sirepo.js msgRouter and https?:
# for browser click on email msg. If there are headers,
# it's a change in auth.
if headers or self._AUTH_RE.search(uri):
# Stop the socket
self.stop()
return True
if self._enabled:
return False
if self._test_client.sr_uid:
self.start()
return False
return True

if _must_be_http():
# Headers means something special (usually auth testing)
pkdlog("uri={} enabled={}", uri, self._enabled)
return None
assert uri[0] == "/", f"uri={uri} must begin with '/'"
Expand Down
4 changes: 1 addition & 3 deletions tests/adm_and_own_jobs_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ def _op(fc, sim_type):
with srunit.quest_start() as qcall:
qcall.auth_db.model("UserRole").delete_all_for_column_by_values(
"uid",
[
fc.sr_auth_state().uid,
],
[fc.sr_uid],
)
r = fc.sr_post(
"admJobs",
Expand Down
12 changes: 6 additions & 6 deletions tests/auth/email1_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def test_different_email(auth_fc):
},
)
t = fc.sr_auth_state(userName="[email protected]", displayName="abc")
fc.sr_get("authLogout", {"simulation_type": fc.sr_sim_type})
fc.sr_logout()
uid = fc.sr_auth_state(userName=None, isLoggedIn=False).uid
r = fc.sr_post(
"authEmailLogin", {"email": "[email protected]", "simulationType": fc.sr_sim_type}
Expand Down Expand Up @@ -60,7 +60,7 @@ def test_follow_email_auth_link_twice(auth_fc):
d = fc.sr_get(r.uri)
assert not re.search(r"login-fail", pkcompat.from_bytes(d.data))
fc.sr_email_confirm(r)
fc.sr_get("authLogout", {"simulation_type": fc.sr_sim_type})
fc.sr_logout()
# now logged out, should see login fail for bad link
pkre("login-fail", pkcompat.from_bytes(fc.get(r.uri).data))

Expand All @@ -79,7 +79,7 @@ def test_force_login(auth_fc):
"authEmailLogin", {"email": "[email protected]", "simulationType": fc.sr_sim_type}
)
fc.get(r.uri)
fc.sr_get("authLogout", {"simulation_type": fc.sr_sim_type})
fc.sr_logout()
with pkexcept("SRException.*routeName.*login"):
fc.sr_post("listSimulations", {"simulationType": fc.sr_sim_type})
r = fc.sr_post(
Expand Down Expand Up @@ -121,7 +121,7 @@ def test_guest_merge(auth_fc):
folder="/",
),
)
guest_uid = fc.sr_auth_state().uid
guest_uid = fc.sr_uid

# Convert to email user
r = fc.sr_post(
Expand Down Expand Up @@ -149,7 +149,7 @@ def test_guest_merge(auth_fc):
folder="/",
),
)
fc.sr_get("authLogout", {"simulation_type": fc.sr_sim_type})
fc.sr_logout()

# Login as email user
r = fc.sr_post(
Expand Down Expand Up @@ -191,7 +191,7 @@ def test_happy_path(auth_fc):
isLoggedIn=True,
userName="[email protected]",
).uid
r = fc.sr_get("authLogout", {"simulation_type": fc.sr_sim_type})
r = fc.sr_logout()
fc.sr_auth_state(
displayName=None,
isLoggedIn=False,
Expand Down
2 changes: 1 addition & 1 deletion tests/auth/email4_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def test_token_reuse(auth_fc):
)
fc.sr_email_confirm(r)
s = fc.sr_auth_state(userName="[email protected]")
fc.sr_get("authLogout", {"simulation_type": fc.sr_sim_type})
fc.sr_logout()
r = fc.sr_get(r.uri, redirect=False)
pkre("/login-fail/email", r.header_get("Location"))
fc.sr_auth_state(isLoggedIn=False)
6 changes: 1 addition & 5 deletions tests/auth2_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
:copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import pytest


Expand All @@ -15,10 +14,7 @@ def test_myapp_user_dir_deleted(fc):
from pykern.pkdebug import pkdp
import sirepo.srdb

sirepo.srdb.root().join(
"user",
fc.sr_auth_state().uid,
).remove(rec=1)
sirepo.srdb.root().join("user", fc.sr_uid).remove(rec=1)
r = pkjson.load_any(
fc.sr_post(
"listSimulations",
Expand Down
7 changes: 2 additions & 5 deletions tests/pkcli/roles_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,7 @@ def test_flash_change_role_change_lib_files(auth_fc):

def _change_role(add=True):
f = getattr(roles, "add" if add else "delete")
f(
fc.sr_auth_state().uid,
auth_role.for_sim_type(fc.sr_sim_type),
)
f(fc.sr_uid, auth_role.for_sim_type(fc.sr_sim_type))

def _check_file(exists=True):
pkunit.pkeq(
Expand Down Expand Up @@ -60,4 +57,4 @@ def test_flash_list_role_by_email(auth_fc):
auth_fc.sr_email_login(e, sim_type="flash")
roles.add(e, *r)
pkunit.pkeq(r, roles.list(e))
pkunit.pkeq(r, roles.list(auth_fc.sr_auth_state().uid))
pkunit.pkeq(r, roles.list(auth_fc.sr_uid))
3 changes: 2 additions & 1 deletion tests/proprietary_sim_types_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,10 @@ def test_myapp(auth_fc):
)
pkunit.pkeq(403, r.status_code)
sirepo.pkcli.roles.add_roles(
fc.sr_auth_state().uid,
fc.sr_uid,
sirepo.auth_role.for_sim_type(fc.sr_sim_type),
)
r = fc.sr_run_sim(fc.sr_sim_data(), "heightWeightReport")
pkdp(type(r))
p = r.get("plots")
pkunit.pkok(p, "expecting truthy r.plots={}", p)
2 changes: 1 addition & 1 deletion tests/supervisor_purge_free_sims_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def _status_eq(next_req, status):
user_premium = "[email protected]"
fc.sr_email_login(user_free)
fc.sr_email_login(user_premium)
_make_user_premium(fc.sr_auth_state().uid)
_make_user_premium(fc.sr_uid)
_make_invalid_job()
next_req_premium = _run_sim(fc.sr_sim_data())
fc.sr_email_login(user_free)
Expand Down

0 comments on commit e6c4cdb

Please sign in to comment.