Python http.HTTPStatus.UNAUTHORIZED Examples
The following are 30
code examples of http.HTTPStatus.UNAUTHORIZED().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
http.HTTPStatus
, or try the search function
.
Example #1
Source File: ch12_r07_server.py From Modern-Python-Cookbook with MIT License | 6 votes |
def authorization_required(view_function): @wraps(view_function) def decorated_function(*args, **kwargs): if 'Authorization' not in request.headers: abort(HTTPStatus.UNAUTHORIZED) kind, data = request.headers['Authorization'].split() if kind.upper() != 'BASIC': abort(HTTPStatus.UNAUTHORIZED) credentials = base64.b64decode(data) username_bytes, _, password_bytes = credentials.partition(b':') username = username_bytes.decode('ascii') password = password_bytes.decode('ascii') if username not in user_database: abort(HTTPStatus.UNAUTHORIZED) if not user_database[username].check_password(password): abort(HTTPStatus.UNAUTHORIZED) g.user = user_database[username] return view_function(*args, **kwargs) return decorated_function
Example #2
Source File: webserver.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def _check_status(self): """Check if the http status is what we expected.""" path_to_statuses = { '/favicon.ico': [HTTPStatus.OK, HTTPStatus.PARTIAL_CONTENT], '/does-not-exist': [HTTPStatus.NOT_FOUND], '/does-not-exist-2': [HTTPStatus.NOT_FOUND], '/404': [HTTPStatus.NOT_FOUND], '/redirect-later': [HTTPStatus.FOUND], '/redirect-self': [HTTPStatus.FOUND], '/redirect-to': [HTTPStatus.FOUND], '/relative-redirect': [HTTPStatus.FOUND], '/absolute-redirect': [HTTPStatus.FOUND], '/cookies/set': [HTTPStatus.FOUND], '/500-inline': [HTTPStatus.INTERNAL_SERVER_ERROR], '/500': [HTTPStatus.INTERNAL_SERVER_ERROR], } for i in range(15): path_to_statuses['/redirect/{}'.format(i)] = [HTTPStatus.FOUND] for suffix in ['', '1', '2', '3', '4', '5', '6']: key = ('/basic-auth/user{suffix}/password{suffix}' .format(suffix=suffix)) path_to_statuses[key] = [HTTPStatus.UNAUTHORIZED, HTTPStatus.OK] default_statuses = [HTTPStatus.OK, HTTPStatus.NOT_MODIFIED] sanitized = QUrl('http://localhost' + self.path).path() # Remove ?foo expected_statuses = path_to_statuses.get(sanitized, default_statuses) if self.status not in expected_statuses: raise AssertionError( "{} loaded with status {} but expected {}".format( sanitized, self.status, ' / '.join(repr(e) for e in expected_statuses)))
Example #3
Source File: build.py From FTDAnsible with GNU General Public License v3.0 | 6 votes |
def _authorize(self, username, password): def request_token(url): resp = open_url( url, method=HTTPMethod.POST, data=json.dumps({'grant_type': 'password', 'username': username, 'password': password}), headers=BASE_HEADERS, validate_certs=False ).read() return json.loads(to_text(resp)) api_versions = sorted(self._fetch_api_versions(), reverse=True) for version in api_versions: token_url = self._hostname + self.TOKEN_PATH_TEMPLATE.format(version) try: token = request_token(token_url) except urllib_error.HTTPError as e: logger.debug("Can't get token for API version: %s", version, exc_info=True) if e.code != HTTPStatus.UNAUTHORIZED: raise else: return token raise Exception("Can't fetch token via API")
Example #4
Source File: helpers.py From python-libmaas with GNU Affero General Public License v3.0 | 6 votes |
def authenticate_with_macaroon(url, insecure=False): """Login via macaroons and generate and return new API keys.""" executor = futures.ThreadPoolExecutor(max_workers=1) def get_token(): client = httpbakery.Client() resp = client.request( "POST", "{}/account/?op=create_authorisation_token".format(url), verify=not insecure, ) if resp.status_code == HTTPStatus.UNAUTHORIZED: # if the auteentication with Candid fails, an exception is raised # above so we don't get here raise MacaroonLoginNotSupported("Macaroon authentication not supported") if resp.status_code != HTTPStatus.OK: raise LoginError("Login failed: {}".format(resp.text)) result = resp.json() return "{consumer_key}:{token_key}:{token_secret}".format(**result) loop = asyncio.get_event_loop() return await loop.run_in_executor(executor, get_token)
Example #5
Source File: testing_farm.py From packit-service with MIT License | 6 votes |
def post(self): """ Submit Testing Farm results """ msg = request.json if not msg: logger.debug("/testing-farm/results: we haven't received any JSON data.") return "We haven't received any JSON data.", HTTPStatus.BAD_REQUEST try: self.validate_testing_farm_request() except ValidationFailed as exc: logger.info(f"/testing-farm/results {exc}") return str(exc), HTTPStatus.UNAUTHORIZED celery_app.send_task( name="task.steve_jobs.process_message", kwargs={"event": msg} ) return "Test results accepted", HTTPStatus.ACCEPTED
Example #6
Source File: app.py From Python-Programming-Blueprints with MIT License | 6 votes |
def _send_message(message): smtp = smtplib.SMTP_SSL('email-smtp.eu-west-1.amazonaws.com', 465) try: smtp.login( user='AKIAITZ6BSMD7DMZYTYQ', password='Ajf0ucUGJiN44N6IeciTY4ApN1os6JCeQqyglRSI2x4V') except SMTPAuthenticationError: return Response('Authentication failed', status=HTTPStatus.UNAUTHORIZED) try: smtp.sendmail(message['From'], message['To'], message.as_string()) except SMTPRecipientsRefused as e: return Response(f'Recipient refused {e}', status=HTTPStatus.INTERNAL_SERVER_ERROR) finally: smtp.quit() return Response('Email sent', status=HTTPStatus.OK)
Example #7
Source File: device_refresh_token.py From selene-backend with GNU Affero General Public License v3.0 | 6 votes |
def get(self): headers = self.request.headers if 'Authorization' not in headers: raise AuthenticationError('Oauth token not found') token_header = self.request.headers['Authorization'] if token_header.startswith('Bearer '): refresh = token_header[len('Bearer '):] session = self._refresh_session_token(refresh) # Trying to fetch a session using the refresh token if session: response = session, HTTPStatus.OK else: device = self.request.headers.get('Device') if device: # trying to fetch a session using the device uuid session = self._refresh_session_token_device(device) if session: response = session, HTTPStatus.OK else: response = '', HTTPStatus.UNAUTHORIZED else: response = '', HTTPStatus.UNAUTHORIZED else: response = '', HTTPStatus.UNAUTHORIZED return response
Example #8
Source File: test_jobs.py From asgard-api with MIT License | 5 votes |
def test_list_jobs_must_be_authenticated(self): resp = await self.client.get("/jobs") self.assertEqual(HTTPStatus.UNAUTHORIZED, resp.status)
Example #9
Source File: security_controller.py From flask-unchained with MIT License | 5 votes |
def login(self): """ View function to log a user in. Supports html and json requests. """ form = self._get_form('SECURITY_LOGIN_FORM') if form.validate_on_submit(): try: self.security_service.login_user(form.user, form.remember.data) except AuthenticationError as e: form.errors = {'_error': [str(e)]} else: self.after_this_request(self._commit) if request.is_json: return self.jsonify({'token': form.user.get_auth_token(), 'user': form.user}) self.flash(_('flask_unchained.bundles.security:flash.login'), category='success') return self.redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT') else: # FIXME-identity identity_attrs = app.config.SECURITY_USER_IDENTITY_ATTRIBUTES msg = f"Invalid {', '.join(identity_attrs)} and/or password." # we just want a single top-level form error form.errors = {'_error': [msg]} for field in form._fields.values(): field.errors = None if form.errors and request.is_json: return self.jsonify({'error': form.errors.get('_error')[0]}, code=HTTPStatus.UNAUTHORIZED) return self.render('login', login_user_form=form, **self.security.run_ctx_processor('login'))
Example #10
Source File: test_jobs.py From asgard-api with MIT License | 5 votes |
def test_update_job_with_required(self): resp = await self.client.put("/jobs/my-job-id") self.assertEqual(HTTPStatus.UNAUTHORIZED, resp.status)
Example #11
Source File: test_jobs.py From asgard-api with MIT License | 5 votes |
def test_delete_job_auth_required(self): resp = await self.client.delete("/jobs/my-job-id") self.assertEqual(HTTPStatus.UNAUTHORIZED, resp.status)
Example #12
Source File: test_utils.py From opentelemetry-python with Apache License 2.0 | 5 votes |
def test_http_status_to_canonical_code(self): for status_code, expected in ( (HTTPStatus.OK, StatusCanonicalCode.OK), (HTTPStatus.ACCEPTED, StatusCanonicalCode.OK), (HTTPStatus.IM_USED, StatusCanonicalCode.OK), (HTTPStatus.MULTIPLE_CHOICES, StatusCanonicalCode.OK), (HTTPStatus.BAD_REQUEST, StatusCanonicalCode.INVALID_ARGUMENT), (HTTPStatus.UNAUTHORIZED, StatusCanonicalCode.UNAUTHENTICATED), (HTTPStatus.FORBIDDEN, StatusCanonicalCode.PERMISSION_DENIED), (HTTPStatus.NOT_FOUND, StatusCanonicalCode.NOT_FOUND), ( HTTPStatus.UNPROCESSABLE_ENTITY, StatusCanonicalCode.INVALID_ARGUMENT, ), ( HTTPStatus.TOO_MANY_REQUESTS, StatusCanonicalCode.RESOURCE_EXHAUSTED, ), (HTTPStatus.NOT_IMPLEMENTED, StatusCanonicalCode.UNIMPLEMENTED), (HTTPStatus.SERVICE_UNAVAILABLE, StatusCanonicalCode.UNAVAILABLE), ( HTTPStatus.GATEWAY_TIMEOUT, StatusCanonicalCode.DEADLINE_EXCEEDED, ), ( HTTPStatus.HTTP_VERSION_NOT_SUPPORTED, StatusCanonicalCode.INTERNAL, ), (600, StatusCanonicalCode.UNKNOWN), (99, StatusCanonicalCode.UNKNOWN), ): with self.subTest(status_code=status_code): actual = http_status_to_canonical_code(int(status_code)) self.assertEqual(actual, expected, status_code)
Example #13
Source File: request_filter.py From openbrokerapi with MIT License | 5 votes |
def get_auth_filter(broker_credentials): def requires_auth(): """Check authentication over all provided usernames else sends a 401 response that enables basic auth""" from flask import request auth = request.authorization if auth: for credentials in broker_credentials: if auth.username == credentials.username and auth.password == credentials.password: return return to_json_response(ErrorResponse( description='Could not verify your access level for that URL.\nYou have to login with proper credentials' )), HTTPStatus.UNAUTHORIZED, {'WWW-Authenticate': 'Basic realm="Login Required"'} return requires_auth
Example #14
Source File: webservice.py From galaxy-integration-humblebundle with GNU General Public License v3.0 | 5 votes |
def _is_session_valid(self): """Simply asks about order list to know if session is valid. galaxy.api.errors instances cannot be catched so galaxy.http.handle_excpetion is the final check with all the logic under its context. """ with handle_exception(): try: await self._session.request('get', self._AUTHORITY + self._ORDER_LIST_URL) except aiohttp.ClientResponseError as e: if e.status == HTTPStatus.UNAUTHORIZED: return False raise return True
Example #15
Source File: viewsets.py From viettel-shake with MIT License | 5 votes |
def login(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.data phone = data['phone'] otp = data['otp'] shake_turn = data['shake_turn'] is_admin = request.user and request.user.is_staff # only admin can override shake turn session = ViettelSession(phone=phone) try: login = session.login(otp=otp) logger.info(login) except (HTTPError, LoginFailed): return Response({'error': 'Login failed!'}, status=HTTPStatus.UNAUTHORIZED) # create Viettel user instance when login success ensure_viettel_user(phone) # request profile of Viettel user profile = session.profile() logger.info(profile) total_turn_left = profile['data']['totalTurnLeft'] logger.info('{} total turn left: {}'.format(session.user_id, total_turn_left)) if not is_admin or shake_turn == USE_TOTAL_SHAKE_TURN: shake_turn = total_turn_left if shake_turn > 0: # dumps headers to string for serializable when send Celery task headers_json = json.dumps(dict(session.headers)) chain( shake_task.signature( (phone, headers_json), immutable=True, # http://docs.celeryproject.org/en/latest/userguide/canvas.html#immutability countdown=randint(settings.MIN_COUNTDOWN, settings.MAX_COUNTDOWN)) for _ in range(shake_turn) )() return Response(session.profile())
Example #16
Source File: ch13_ex5.py From Mastering-Object-Oriented-Python-Second-Edition with MIT License | 5 votes |
def valid_api_key(view_function: Callable) -> Callable: @wraps(view_function) def confirming_view_function(*args, **kw): api_key = request.headers.get("Api-Key") if api_key not in VALID_API_KEYS: current_app.logger.error(f"Rejecting Api-Key:{api_key!r}") abort(HTTPStatus.UNAUTHORIZED) return view_function(*args, **kw) return confirming_view_function
Example #17
Source File: ch13_ex5.py From Mastering-Object-Oriented-Python-Second-Edition with MIT License | 5 votes |
def api_key_in(valid_values: Set[str]): def concrete_decorator(view_function: Callable) -> Callable: @wraps(view_function) def confirming_view_function(*args, **kw): api_key = request.headers.get("Api-Key") if api_key not in valid_values: current_app.logger.error(f"Rejecting Api-Key:{api_key!r}") abort(HTTPStatus.UNAUTHORIZED) return view_function(*args, **kw) return confirming_view_function return concrete_decorator
Example #18
Source File: extension.py From flask-react-spa with MIT License | 5 votes |
def unauthorized_handler(): abort(HTTPStatus.UNAUTHORIZED)
Example #19
Source File: login.py From flask-react-spa with MIT License | 5 votes |
def login(): if request.is_json: form = _security.login_form(MultiDict(request.get_json())) else: form = _security.login_form(request.form) if form.validate_on_submit(): login_user(form.user, remember=form.remember.data) after_this_request(_commit) if not request.is_json: return redirect(get_post_login_redirect(form.next.data)) if not request.is_json: return _security.render_template(config_value('LOGIN_USER_TEMPLATE'), login_user_form=form, **_ctx('login')) # override error messages if necessary confirmation_required = get_message('CONFIRMATION_REQUIRED')[0] if confirmation_required in form.errors.get('email', []): return jsonify({ 'error': confirmation_required, }), HTTPStatus.UNAUTHORIZED elif form.errors: username_fields = config_value('USER_IDENTITY_ATTRIBUTES') return jsonify({ 'error': f"Invalid {', '.join(username_fields)} and/or password." }), HTTPStatus.UNAUTHORIZED return jsonify({ 'user': form.user, 'token': form.user.get_auth_token(), })
Example #20
Source File: test_drivers_rackspace.py From cloudstorage with MIT License | 5 votes |
def test_container_generate_upload_url_expiration(container, text_stream): form_post = container.generate_upload_url(blob_name="", expires=-10) assert "url" in form_post and "fields" in form_post assert uri_validator(form_post["url"]) url = form_post["url"] fields = form_post["fields"] multipart_form_data = {"file": text_stream} response = requests.post(url, data=fields, files=multipart_form_data) assert response.status_code == HTTPStatus.UNAUTHORIZED, response.text
Example #21
Source File: test_drivers_rackspace.py From cloudstorage with MIT License | 5 votes |
def test_blob_generate_download_url_expiration(binary_blob): download_url = binary_blob.generate_download_url(expires=-10) assert uri_validator(download_url) response = requests.get(download_url) assert response.status_code == HTTPStatus.UNAUTHORIZED, response.text
Example #22
Source File: http.py From galaxy-integrations-python-api with MIT License | 5 votes |
def handle_exception(): """ Context manager translating network related exceptions to custom :mod:`~galaxy.api.errors`. """ try: yield except asyncio.TimeoutError: raise BackendTimeout() except aiohttp.ServerDisconnectedError: raise BackendNotAvailable() except aiohttp.ClientConnectionError: raise NetworkError() except aiohttp.ContentTypeError as error: raise UnknownBackendResponse(error.message) except aiohttp.ClientResponseError as error: if error.status == HTTPStatus.UNAUTHORIZED: raise AuthenticationRequired(error.message) if error.status == HTTPStatus.FORBIDDEN: raise AccessDenied(error.message) if error.status == HTTPStatus.SERVICE_UNAVAILABLE: raise BackendNotAvailable(error.message) if error.status == HTTPStatus.TOO_MANY_REQUESTS: raise TooManyRequests(error.message) if error.status >= 500: raise BackendError(error.message) if error.status >= 400: logger.warning( "Got status %d while performing %s request for %s", error.status, error.request_info.method, str(error.request_info.url) ) raise UnknownError(error.message) except aiohttp.ClientError as e: logger.exception("Caught exception while performing request") raise UnknownError(repr(e))
Example #23
Source File: __init__.py From zimfarm with GNU General Public License v3.0 | 5 votes |
def register_handlers(app: Flask): app.errorhandler(BadRequest)(BadRequest.handler) app.errorhandler(OfflinerConfigNotValid)(OfflinerConfigNotValid.handler) app.errorhandler(Unauthorized)(Unauthorized.handler) app.errorhandler(NotFound)(NotFound.handler) app.errorhandler(InternalError)(InternalError.handler) app.errorhandler(oauth2.OAuth2Base)(oauth2.handler) app.errorhandler(http.HTTPBase)(http.handler) @app.errorhandler(marshmallow.exceptions.ValidationError) def handler_validationerror(e): return make_response(jsonify({"message": e.messages}), HTTPStatus.BAD_REQUEST) @app.errorhandler(jwt_exceptions.ExpiredSignature) def handler_expiredsig(_): return make_response( jsonify({"error": "token expired"}), HTTPStatus.UNAUTHORIZED ) @app.errorhandler(jwt_exceptions.InvalidTokenError) def handler_invalidtoken(_): return make_response( jsonify({"error": "token invalid"}), HTTPStatus.UNAUTHORIZED ) # 400
Example #24
Source File: __init__.py From zimfarm with GNU General Public License v3.0 | 5 votes |
def handler(e): if isinstance(e, Unauthorized) and e.message is not None: return make_response(jsonify({"error": e.message}), HTTPStatus.UNAUTHORIZED) return Response(status=HTTPStatus.UNAUTHORIZED)
Example #25
Source File: oauth2.py From zimfarm with GNU General Public License v3.0 | 5 votes |
def __init__(self, description: str): super().__init__(HTTPStatus.UNAUTHORIZED, "invalid_grant", description)
Example #26
Source File: device_email.py From selene-backend with GNU Affero General Public License v3.0 | 5 votes |
def validate_response_invalid_device(context): response = context.email_invalid_response assert_that(response.status_code, equal_to(HTTPStatus.UNAUTHORIZED)) email_client: MagicMock = context.client_config['EMAIL_CLIENT'] email_client.send_message.assert_not_called()
Example #27
Source File: webserver_sub.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def basic_auth(user='user', passwd='passwd'): """Prompt the user for authorization using HTTP Basic Auth.""" auth = flask.request.authorization if not auth or auth.username != user or auth.password != passwd: r = flask.make_response() r.status_code = HTTPStatus.UNAUTHORIZED r.headers = {'WWW-Authenticate': 'Basic realm="Fake Realm"'} return r return flask.jsonify(authenticated=True, user=user)
Example #28
Source File: responses.py From maubot with GNU Affero General Public License v3.0 | 5 votes |
def bad_auth(self) -> web.Response: return web.json_response({ "error": "Invalid username or password", "errcode": "invalid_auth", }, status=HTTPStatus.UNAUTHORIZED)
Example #29
Source File: responses.py From maubot with GNU Affero General Public License v3.0 | 5 votes |
def no_token(self) -> web.Response: return web.json_response({ "error": "Authorization token missing", "errcode": "auth_token_missing", }, status=HTTPStatus.UNAUTHORIZED)
Example #30
Source File: responses.py From maubot with GNU Affero General Public License v3.0 | 5 votes |
def invalid_token(self) -> web.Response: return web.json_response({ "error": "Invalid authorization token", "errcode": "auth_token_invalid", }, status=HTTPStatus.UNAUTHORIZED)