def check_session_valid(self, auth_header): try: user_payload = decode_jwt_token(auth_header)['user'] except Exception: return False if 'session_key' not in user_payload: return False session_id = user_payload['session_key'] session_data = session_cache.get('%s%s' % (KEY_PREFIX, session_id)) if not session_data: return False if not set(('_auth_user_hash', '_auth_user_id')) <= set(session_data): return False if session_data['_auth_user_id'] != str(self.id): return False session_auth_hash = self.get_session_auth_hash() if session_data['_auth_user_hash'] != session_auth_hash: return False if not constant_time_compare(session_data['_auth_user_hash'], session_auth_hash): return False return True
def login_optional(req, resp, resource, *args, **kwargs): auth_header = req.get_header('Authorization') if not auth_header: req.user = AnonymousUser() return try: user_payload = () user_payload = decode_jwt_token(auth_header)['user'] except Exception: pass if not set(('session_key', 'email')) <= set(user_payload): req.user = AnonymousUser() return req.session = session_store(user_payload['session_key']) user = get_user(req) if user != AnonymousUser() and any( (not user, user.email != user_payload['email'], user.state != 'active')): user = AnonymousUser() req.user = user if user.id: connection.cursor().execute(f'SET myapp.userid = "{user.id}"')
def test_extended_permissions(self, active_user): header = get_auth_header(active_user, '1') payload = decode_jwt_token(header) assert payload['user']['roles'] == [] active_user.is_staff = True header = get_auth_header(active_user, '1') payload = decode_jwt_token(header) assert payload['user']['roles'] == ['editor'] active_user.is_staff = False active_user.is_superuser = True header = get_auth_header(active_user, '1') payload = decode_jwt_token(header) assert payload['user']['roles'] == ['admin']
def execute(self, req, resp, params): auth_header = req.get_header('Authorization') # import pdb; pdb.set_trace() if not auth_header: raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Missing authorization header'), code='token_missing' ) user_payload = decode_jwt_token(auth_header)['user'] if not set(('session_key', 'email')) <= set(user_payload): raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Invalid authorization header'), code='token_error' ) req.session = session_store(user_payload['session_key']) user = get_user(req) if not user or (hasattr(user, 'is_anonymous') and user.is_anonymous): raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Invalid token data'), code='authentication_error' ) if user.email != user_payload['email']: raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Invalid token data'), code='authentication_error' ) if user.state != 'active': if user.state not in settings.USER_STATE_LIST or user.state == 'deleted': raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Cannot login'), code='account_unavailable' ) if user.state in ('draft', 'blocked'): raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Account is blocked'), code='account_unavailable' ) if user.state == 'pending': raise falcon.HTTPForbidden( title='403 Forbidden', description=_('Email addres not confirmed'), code='account_inactive' ) req.user = user
def test_decode_token(self, now, valid_header, token_exp_delta): now_ts = timegm(now.utctimetuple()) exp_ts = timegm((now + timedelta(seconds=token_exp_delta)).utctimetuple()) payload = decode_jwt_token(valid_header) assert payload['iat'] == now_ts assert payload['nbf'] == now_ts assert payload['exp'] == exp_ts assert payload['user']['session_key'] == '1' assert payload['user']['role'] == 'user' assert payload['user']['email'] == 'a'
def test_extended_permissions(self, active_user): header = get_auth_header(active_user.email, active_user.system_role, '1') payload = decode_jwt_token(header) assert payload['user']['role'] == 'user' active_user.is_staff = True header = get_auth_header(active_user.email, active_user.system_role, '1') payload = decode_jwt_token(header) assert payload['user']['role'] == 'staff' active_user.is_staff = False active_user.is_superuser = True header = get_auth_header(active_user.email, active_user.system_role, '1') payload = decode_jwt_token(header) assert payload['user']['role'] == 'staff'
def execute(self, req, resp, params): auth_header = req.get_header('Authorization') if not auth_header: req.user = AnonymousUser() return try: user_payload = () user_payload = decode_jwt_token(auth_header)['user'] except Exception: pass if not set(('session_key', 'email')) <= set(user_payload): req.user = AnonymousUser() return req.session = session_store(user_payload['session_key']) user = get_user(req) if user != AnonymousUser() and any((not user, user.email != user_payload['email'], user.state != 'active')): user = AnonymousUser() req.user = user
def login_required(req, resp, resource, params, roles=('user', ), save=False, restore_from=None): # noqa: C901 if restore_from: if restore_from not in params: raise falcon.HTTPUnauthorized(title='401 Unauthorized', description=_('Missing token'), code='token_missing') redis_connection = get_redis_connection() _key = params[restore_from] if isinstance(_key, uuid.UUID): _key = _key.hex user_payload = redis_connection.get(_key) try: user_payload = json.loads(user_payload) except Exception: user_payload = {} else: auth_header = req.get_header('Authorization') if not auth_header: raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Missing authorization header'), code='token_missing') user_payload = decode_jwt_token(auth_header)['user'] if not set(('session_key', 'email')) <= set(user_payload): raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Invalid token') if restore_from else _('Invalid authorization header'), code='token_error') req.session = session_store(user_payload['session_key']) user = get_user(req) if not user or (hasattr(user, 'is_anonymous') and user.is_anonymous): raise falcon.HTTPUnauthorized(title='401 Unauthorized', description=_('Incorrect login data'), code='authentication_error') if user.email != user_payload['email']: raise falcon.HTTPUnauthorized(title='401 Unauthorized', description=_('Incorrect login data'), code='authentication_error') if user.state != 'active': if user.state not in settings.USER_STATE_LIST or user.state == 'deleted': raise falcon.HTTPUnauthorized(title='401 Unauthorized', description=_('Cannot login'), code='account_unavailable') if user.state in ('draft', 'blocked'): raise falcon.HTTPUnauthorized(title='401 Unauthorized', description=_('Account is blocked'), code='account_unavailable') if user.state == 'pending': raise falcon.HTTPForbidden( title='403 Forbidden', description=_('Email address not confirmed'), code='account_inactive') check_roles(user, roles) req.user = user connection.cursor().execute(f'SET myapp.userid = "{user.id}"') if save: redis_connection = get_redis_connection() _token = uuid.uuid4().hex user_payload = { 'session_key': req.session.session_key, 'email': req.user.email, } redis_connection.set(_token, json.dumps(user_payload), ex=60) resp._token = _token