def api_send_request_with_mocked_url(context, mocker, mocked_url, mocked_data, **mock_kwargs): if context.user: token = get_auth_token(context.user, session_key=str(context.user.id)) mocker.patch('mcod.core.api.hooks.get_user', return_value=context.user) context.api.headers['Authorization'] = "Bearer %s" % token # cookies have to be sent in Cookie header: https://github.com/falconry/falcon/issues/1640 if context.api.cookies: cookies = '' for cookie_name, cookie_value in context.api.cookies.items(): cookies += '%s=%s; ' % (cookie_name, cookie_value) if cookies: if context.api.headers.get('Cookie'): context.api.headers['Cookie'] += '; ' + cookies else: context.api.headers['Cookie'] = cookies o = parse.urlparse(settings.API_URL) kwargs = { 'method': context.api.method, 'path': context.api.path, 'headers': context.api.headers, 'params': context.api.params, 'protocol': o.scheme, 'host': o.netloc, } if context.api.method in ('POST', 'PUT', 'PATCH', 'DELETE'): kwargs['json'] = context.obj mock_request = mock_kwargs['mock_request'] mock_request.post(mocked_url, headers={'content-type': 'application/rdf+xml'}, content=mocked_data.encode('utf-8')) resp = TestClient(app).simulate_request(**kwargs) skip_validation = False api_version = resp.headers['x-api-version'] if api_version == '1.0': skip_validation = True if resp.status_code in (202, 204): skip_validation = True if not skip_validation: valid, validated, errors = jsonapi_validator(resp.json) assert valid is True # TODO: this does not work on gitlab... # Counter().save_counters() # TODO: check pagination context.response = resp mocker.stopall()
def _get_data(self, cleaned, *args, **kwargs): cleaned = cleaned['data']['attributes'] cleaned['email'] = cleaned['email'].lower() try: user = User.objects.get(email=cleaned['email'], is_removed=False, is_permanently_removed=False) except User.DoesNotExist: raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Invalid email or password'), code='account_not_exist') if user.state != 'active': if user.state not in settings.USER_STATE_LIST or user.state == 'deleted': raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Account is not available'), 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') user = authenticate(request=self.request, **cleaned) if user is None: raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Invalid email or password'), code='authorization_error') if not hasattr(self.request, 'session'): self.request.session = session_store() self.request.META = {} login(self.request, user) self.request.session.save() user.token = get_auth_token(user, self.request.session.session_key) return user
def process_template_response(self, request, response): # if user and no cookie, set cookie domain = request.META.get("HTTP_HOST", "localhost") if domain.startswith('admin.'): domain = domain.replace('admin.', "") elif domain.startswith('localhost'): domain = domain.split(":")[0] if request.user.is_authenticated and not request.COOKIES.get('mcod_token'): token = get_auth_token(request.user.email, request.user.system_role, request.session.session_key) response.set_cookie("mcod_token", token, domain=domain) elif not request.user.is_authenticated: # else if no user and cookie remove user cookie, logout response.delete_cookie("mcod_token", domain=domain) return response
def _data(self, request, cleaned, *args, **kwargs): try: user = User.objects.get(email=cleaned['email']) except User.DoesNotExist: raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Invalid email or password'), code='account_not_exist') if user.state is not 'active': if user.state not in settings.USER_STATE_LIST or user.state == 'deleted': raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Account is not available'), 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') user = authenticate(request=request, **cleaned) if user is None: raise falcon.HTTPUnauthorized( title='401 Unauthorized', description=_('Invalid email or password'), code='authorization_error') if not hasattr(request, 'session'): request.session = session_store() request.META = {} login(request, user) request.session.save() user.token = get_auth_token(user.email, user.system_role, request.session.session_key) return user
def __call__(self, request): response = self.get_response(request) apiauthcookie = settings.API_TOKEN_COOKIE_NAME if apiauthcookie in request.COOKIES: if not request.user.is_authenticated: response.delete_cookie(apiauthcookie, domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH) else: if request.user.is_authenticated: token = get_auth_token(request.user, request.session.session_key) response.set_cookie( apiauthcookie, token, domain=settings.SESSION_COOKIE_DOMAIN, httponly=False, # Make it readable for angular samesite=settings.SESSION_COOKIE_SAMESITE, secure=settings.SESSION_COOKIE_SECURE, path=settings.SESSION_COOKIE_PATH, max_age=settings.JWT_EXPIRATION_DELTA) return response