from typing import List, Optional from authlib.oauth2 import OAuth2Error from flask import Flask, g, jsonify, request from flask.typing import ResponseReturnValue from owslib import auth from owslib.enums import Environment from owslib.urlpath import is_path_match class JWTAuth: def __init__( self, environment: Environment = Environment.PROD, enabled: Optional[bool] = None, cache_timeout: Optional[int] = auth.DEFAULT_CACHE_TIMEOUT, realm: Optional[str] = None, exclude_paths: Optional[List[str]] = None, ) -> None: self.enabled = auth.jwt_auth_enabled_for_env(environment, enabled=enabled) self.exclude_paths = exclude_paths self.auth = auth.jwt_auth_from_config( environment, cache_timeout=cache_timeout, realm=realm ) def init_app(self, app: Flask) -> None: if self.enabled: app.before_request(self.authenticate_request) def authenticate_request(self) -> Optional[ResponseReturnValue]: if is_path_match(request.path, match=self.exclude_paths): return None authorization = request.headers.get("authorization") try: token = self.auth.authenticate(authorization) except OAuth2Error as exc: return ( jsonify( code=exc.error or "Authentication error", message=exc.get_error_description(), detail={}, ), exc.status_code, dict(exc.get_headers()), ) g.token = token return None