def test_1(): import shutil from pykern import pkconfig, pkunit, pkio from pykern.pkunit import pkeq from pykern.pkdebug import pkdp from sirepo import srunit srunit.flask_client() from sirepo import cookie cookie.init_mock() cookie.init('x') with pkunit.pkexcept('Unauthorized'): cookie.get_user() with pkunit.pkexcept('Unauthorized'): cookie.get_user(checked=False) cookie.set_sentinel() cookie.set_user('abc') cookie.set_value('hi', 'hello') r = _Response(status_code=200) cookie.save_to_cookie(r) pkeq('sirepo_dev', r.args[0]) pkeq(False, r.kwargs['secure']) pkeq('abc', cookie.get_user()) cookie.clear_user() cookie.unchecked_remove('hi') pkeq(None, cookie.get_user(checked=False)) cookie.init('sirepo_dev={}'.format(r.args[1])) pkeq('hello', cookie.get_value('hi')) pkeq('abc', cookie.get_user())
def test_set_get(): from pykern import pkunit from pykern.pkunit import pkeq from pykern.pkdebug import pkdp from pykern import pkcollections from sirepo import cookie class _Response(pkcollections.Dict): def set_cookie(self, *args, **kwargs): self.args = args self.kwargs = kwargs cookie.process_header('x') with pkunit.pkexcept('KeyError'): cookie.get_value('hi') with pkunit.pkexcept('AssertionError'): cookie.set_value('hi', 'hello') pkeq(None, cookie.unchecked_get_value('hi')) cookie.init_mock() cookie.set_value('hi', 'hello') r = _Response(status_code=200) cookie.save_to_cookie(r) pkeq('sirepo_dev', r.args[0]) pkeq(False, r.kwargs['secure']) pkeq('hello', cookie.get_value('hi')) cookie.unchecked_remove('hi') pkeq(None, cookie.unchecked_get_value('hi')) cookie.process_header('sirepo_dev={}'.format(r.args[1])) pkeq('hello', cookie.get_value('hi'))
def authorize(simulation_type, oauth_type): """Redirects to an OAUTH request for the specified oauth_type ('github'). If oauth_type is 'anonymous', the current session is cleared. """ oauth_next = '/{}#{}'.format(simulation_type, flask.request.args.get('next', '')) if oauth_type == _ANONYMOUS_OAUTH_TYPE: _update_session(_ANONYMOUS) cookie.clear_user() return server.javascript_redirect(oauth_next) state = util.random_base62() cookie.set_value(_COOKIE_NONCE, state) cookie.set_value(_COOKIE_NEXT, oauth_next) callback = cfg.github_callback_uri if not callback: from sirepo import uri_router callback = uri_router.uri_for_api( 'oauthAuthorized', dict(oauth_type=oauth_type), ) return _oauth_client(oauth_type).authorize( callback=callback, state=state, )
def is_login_expired(res=None): """If expiry is configured, check timestamp Args: res (hash): If a hash and return is True, will contain (uid, expiry, and now). Returns: bool: true if login is expired """ if not cfg.expiry_days: return False n = int(srtime.utc_now_as_float()) t = int(cookie.unchecked_get_value(_COOKIE_EXPIRY_TIMESTAMP, 0)) if n <= t: # cached timestamp less than expiry return False # db expiry at most one day from now so we can change expiry_days # and (in any event) ensure expiry is checked once a day. This # would also allow us to extend the expired period in the db. u = auth.logged_in_user() r = auth.user_registration(u) t = r.created + cfg.expiry_days n = srtime.utc_now() if n > t: if res is not None: res.update(uid=u, expiry=t, now=n) return True # set expiry in cookie t2 = n + _ONE_DAY if t2 < t: t = t2 t -= datetime.datetime.utcfromtimestamp(0) cookie.set_value(_COOKIE_EXPIRY_TIMESTAMP, int(t.total_seconds())) return False
def api_authGithubLogin(simulation_type): """Redirects to Github""" t = sirepo.template.assert_sim_type(simulation_type) s = util.random_base62() cookie.set_value(_COOKIE_NONCE, s) cookie.set_value(_COOKIE_SIM_TYPE, t) if not cfg.callback_uri: # must be executed in an app and request context so can't # initialize earlier. cfg.callback_uri = uri_router.uri_for_api('authGithubAuthorized') return _oauth_client().authorize(callback=cfg.callback_uri, state=s)
def api_authGithubLogin(simulation_type): """Redirects to Github""" req = http_request.parse_params(type=simulation_type) s = util.random_base62() cookie.set_value(_COOKIE_NONCE, s) cookie.set_value(_COOKIE_SIM_TYPE, req.type) if not cfg.callback_uri: # must be executed in an app and request context so can't # initialize earlier. cfg.callback_uri = uri_router.uri_for_api('authGithubAuthorized') return _client(s).authorize_redirect(redirect_uri=cfg.callback_uri, state=s)
def test_set_get(): from pykern import pkunit, pkcompat from pykern.pkunit import pkeq from pykern.pkdebug import pkdp from sirepo import cookie with cookie.process_header('x'): with pkunit.pkexcept('KeyError'): cookie.get_value('hi1') with pkunit.pkexcept('AssertionError'): cookie.set_value('hi2', 'hello') pkeq(None, cookie.unchecked_get_value('hi3'))
def complete_registration(name=None): """Update the database with the user's display_name and sets state to logged-in. Guests will have no name. """ u = _get_user() with auth_db.thread_lock: r = user_registration(u) if cookie.unchecked_get_value(_COOKIE_METHOD) is METHOD_GUEST: assert name is None, \ 'Cookie method is {} and name is {}. Expected name to be None'.format(METHOD_GUEST, name) r.display_name = name r.save() cookie.set_value(_COOKIE_STATE, _STATE_LOGGED_IN)
def api_authLogout(simulation_type): """Set the current user as logged out. Redirects to root simulation page. """ t = None try: t = sirepo.template.assert_sim_type(simulation_type) except AssertionError: pass if _is_logged_in(): cookie.set_value(_COOKIE_STATE, _STATE_LOGGED_OUT) _set_log_user() return http_reply.gen_redirect_for_root(t)
def api_authCompleteRegistration(): # Needs to be explicit, because we would need a special permission # for just this API. if not _is_logged_in(): return http_reply.gen_sr_exception(LOGIN_ROUTE_NAME) d = http_request.parse_json() t = d.simulationType n = _parse_display_name(d) u = _get_user() with auth_db.thread_lock: r = _user_registration(u) r.display_name = n r.save() cookie.set_value(_COOKIE_STATE, _STATE_LOGGED_IN) return http_reply.gen_json_ok()
def api_authLogout(simulation_type=None): """Set the current user as logged out. Redirects to root simulation page. """ req = None if simulation_type: try: req = http_request.parse_params(type=simulation_type) except AssertionError: pass if _is_logged_in(): cookie.set_value(_COOKIE_STATE, _STATE_LOGGED_OUT) _set_log_user() return http_reply.gen_redirect_for_app_root(req and req.type)
def test_cookie_outside_of_flask_request(): from pykern import pkcompat from pykern.pkunit import pkeq from sirepo import cookie from sirepo import srunit with srunit.auth_db_session(), \ cookie.set_cookie_outside_of_flask_request(): cookie.set_value('hi4', 'hello') r = _Response(status_code=200) cookie.save_to_cookie(r) pkeq('sirepo_dev', r.args[0]) pkeq(False, r.kwargs['secure']) pkeq('hello', cookie.get_value('hi4')) cookie.unchecked_remove('hi4') pkeq(None, cookie.unchecked_get_value('hi4')) # Nest cookie contexts with cookie.process_header( 'sirepo_dev={}'.format(pkcompat.from_bytes(r.args[1])), ): pkeq('hello', cookie.get_value('hi4'))
def _login_user(module, uid): """Set up the cookie for logged in state If a deprecated or non-visible method, just login. Otherwise, check the db for registration. Args: module (module): what auth method uid (str): which uid """ cookie.set_value(_COOKIE_USER, uid) cookie.set_value(_COOKIE_METHOD, module.AUTH_METHOD) s = _STATE_LOGGED_IN if module.AUTH_METHOD_VISIBLE and module.AUTH_METHOD in cfg.methods: u = user_registration(uid) if not u.display_name: s = _STATE_COMPLETE_REGISTRATION cookie.set_value(_COOKIE_STATE, s) _set_log_user()
def reset_state(): cookie.unchecked_remove(_COOKIE_USER) cookie.unchecked_remove(_COOKIE_METHOD) cookie.set_value(_COOKIE_STATE, _STATE_LOGGED_OUT) _set_log_user()
def _update_session(login_state, user_name=''): cookie.set_value(_COOKIE_STATE, login_state) cookie.set_value(_COOKIE_NAME, user_name)
def _update_session(login_state, auth_method): cookie.set_value(_COOKIE_LOGIN_SESSION, login_state) cookie.set_value(_COOKIE_METHOD, auth_method)