def get_app() -> API: auth_backend = JWTAuthBackend(user_loader, SECRET, algorithm="HS256", leeway=30) auth_middleware = FalconAuthMiddleware( auth_backend, exempt_routes=["/auth", "/register"], exempt_methods=["HEAD", "OPTIONS"], ) _app = falcon.API(middleware=[ Marshmallow(), auth_middleware, ] # middleware=[auth_middleware] - add to enable jwt authentication ) _app.add_route("/decoder", JWTDecoder()) _app.add_route("/auth", JWTIssuer()) _app.add_route("/item/{name}", Item()) _app.add_route("/items", ItemList()) _app.add_route("/register", UserRegister()) _app.add_route("/store/{name}", Store()) _app.add_route("/stores", StoreList()) return _app
def test_require_scope_no_user(): auth_backend = NoneAuthBackend(lambda: None) auth_middleware = FalconAuthMiddleware(auth_backend) api = falcon.App(middleware=[auth_middleware]) api.add_route("/test", TestResource()) client = testing.TestClient(api) result = client.simulate_get("/test") assert result.status == falcon.HTTP_FORBIDDEN
def do_get(scope): def user_loader(): return Auth0User({"scope": scope}, lambda: {}) auth_backend = NoneAuthBackend(user_loader) auth_middleware = FalconAuthMiddleware(auth_backend) api = falcon.App(middleware=[auth_middleware]) api.add_route("/test", TestResource()) client = testing.TestClient(api) return client.simulate_get("/test")
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.multipart_middleware = MultipartMiddleware() self.auth_backend = TokenAuthBackend(user_loader, auth_header_prefix='Token') self.auth_middleware = FalconAuthMiddleware(self.auth_backend, exempt_routes=['/api/login'], exempt_methods=['HEAD']) self.auth = False self.cors_origins = list()
def __build_api(db: Session) -> API: api = API( middleware=[ RequireJSON(), JSONTranslator(), FalconAuthMiddleware( JwtAuth(default_jwt_config, db).get_backend(), [], ['HEAD'] ) ] ) api.req_options.auto_parse_form_urlencoded = True return api
def test_falcon_request_logs_user(user): user_dict = dict([(user.key or 'username', user.name)]) basic_auth = BasicAuthBackend(lambda username, password: user_dict) app = falcon.API(middleware=[ falcon_logging.LoggingMiddleware(), FalconAuthMiddleware(basic_auth) ]) app.add_route('/test/path', TestResource()) args = [app, user.key] if user.key else [app] _set_up_falcon_logging(*args) expected = {'remote_user': v_str(user.name)} _check_falcon_request_log( app, {'Authorization': str(auth_basic(user.name, 'pass'))}, expected)
def __init__(self, sql_conn: sqlite3.Connection, data_path: str, **kwargs): users_resource = UsersResource(sql_conn, data_path) auth_backend = JWTAuthBackend(users_resource.validate_claims, JWT_KEY, required_claims=['exp', 'selected_campaign', 'email']) auth_middleware = FalconAuthMiddleware(auth_backend, exempt_routes=['/users', '/login', '/captcha'], exempt_methods=['HEAD', 'OPTIONS']) super().__init__(middleware=[auth_middleware], **kwargs) auth_resource = Login(sql_conn, data_path) profile_resource = Profile(sql_conn, data_path) captcha_resource = Captcha(sql_conn, data_path) characters_resource = Characters(sql_conn, data_path) character_resource = Character(sql_conn, data_path) factions_resource = Factions(sql_conn, data_path) faction_resource = Faction(sql_conn, data_path) places_resource = Places(sql_conn, data_path) place_resource = Place(sql_conn, data_path) things_resource = Things(sql_conn, data_path) thing_resource = Thing(sql_conn, data_path) entries_resource = ChronicleEntries(sql_conn, data_path) entry_resource = ChronicleEntry(sql_conn, data_path) char_rels_resource = CharacterRelations(sql_conn, data_path) char_rel_resource = CharacterRelation(sql_conn, data_path) faction_rels_resource = FactionRelations(sql_conn, data_path) self.add_route("/users/", users_resource) self.add_route("/login", auth_resource) self.add_route("/profile", profile_resource) self.add_route("/profile/{profile_id}", profile_resource) self.add_route("/profile/campaigns/{campaign_id}", profile_resource) self.add_route("/captcha/", captcha_resource) self.add_route("/characters/", characters_resource) self.add_route("/characters/{character_id}", character_resource) self.add_route("/factions/", factions_resource) self.add_route("/factions/{faction_id}", faction_resource) self.add_route("/places/", places_resource) self.add_route("/places/{place_id}", place_resource) self.add_route("/things/", things_resource) self.add_route("/things/{thing_id}", thing_resource) self.add_route("/chronicle/", entries_resource) self.add_route("/chronicle/{entry_id}", entry_resource) self.add_route("/characters/{character_id}/relations/{relation_type}", char_rels_resource) self.add_route("/characters/{character_id}/relations/{relation_type}/{relation_id}", char_rel_resource) self.add_route("/factions/{faction_id}/relations/{relation_type}", faction_rels_resource) self.add_route("/{relation_type}/{relation_id}/relations/characters/{character_id}", char_rel_resource)
def __init__(self): self.redis_account = redis.StrictRedis.from_url(url=REDIS_URL, db=7, charset="utf-8", decode_responses=True) self.redis_auth = redis.StrictRedis.from_url(url=REDIS_URL, db=6, charset="utf-8", decode_responses=True) try: self._secret_key = os.environ['ANNOUNCEMENTS_SECRET_KEY'] except KeyError: if self.redis_auth.exists('secret_key'): self._secret_key = self.redis_auth.get('secret_key') else: self.redis_auth.set('secret_key', secrets.token_hex()) self._secret_key = self.redis_auth.get('secret_key') self.jwt_auth = JWTAuthBackend(self.jwt_user_loader, secret_key=self._secret_key, auth_header_prefix='Bearer', leeway=60, expiration_delta=JWT_EXPIRE_TIME) self.auth_middleware = FalconAuthMiddleware(self.jwt_auth)
''' Created on 2018/12/6 @author: shimakaze-git ''' import json import falcon from auth import user_loader, SECRET_KEY, ExampleUser from falcon_auth import FalconAuthMiddleware, JWTAuthBackend API_ENDPOINT = "/api" auth_backend = JWTAuthBackend(user_loader, SECRET_KEY) auth_middleware = FalconAuthMiddleware(auth_backend, exempt_routes=None, exempt_methods=None) app = falcon.API(middleware=[auth_middleware]) class TokenAuth: auth = { 'auth_disabled': True, # 'exempt_methods': ['POST'] } def on_post(self, req, resp, **params): body = req.stream.read() data = json.loads(body)
d = dict(index=index, doc_type=doc_type, id=id, body=body) d_latest = dict(index=latest_index, doc_type=latest_doc_type, id=1, body=body) print(d) print(d_latest) #self.es.index(**d) #self.es.index(**d_latest) resp.status = falcon.HTTP_200 user_loader = lambda username, password: { 'username': username, 'password': password } auth_backend = BasicAuthBackend(user_loader) auth_middleware = FalconAuthMiddleware(auth_backend, exempt_routes=['/api/status']) api = falcon.API(middleware=[auth_middleware]) api.add_route('/api/status', StatusResource()) api.add_route('/api/latest/all', LatestAllResource()) # Get Latest / Post Latest from AI api.add_route('/api/latest/{coin}', LatestCoinResource()) # Get Latest / Post Latest from coinmarketcap api.add_route('/api/coinmarketcap/{coin}', CoinmarketcapCoinResource()) api.add_route('/api/coinmarketcap/update', CoinmarketcapUpdateResource())
import falcon from falcon_cors import CORS from falcon_auth import FalconAuthMiddleware, TokenAuthBackend from app.routes.create_user import CreateUser from app.routes.create_project import CreateProject cors = CORS(allow_origins_list=['http://localhost:8080']) # a loader function to fetch user from username, password user_loader = lambda username, password: {'username': username} # basic auth backend token_auth = TokenAuthBackend(user_loader=lambda token: {'id': '123'}) auth_middleware = FalconAuthMiddleware( token_auth, exempt_routes=['/api/v1/create-project']) api = falcon.API(middleware=[auth_middleware, cors.middleware]) public_cors = CORS(allow_all_origins=True) api.add_route('/api/v1/create-user', CreateUser()) api.add_route('/api/v1/create-project', CreateProject())
def create_app(conf_file): """ Main web application. IMPORTANT NOTICE: This application is designed to run under a single process and single thread in WSGI. It will not work properly if multiple processes operate using the same data at once. Parameters ---------- conf_file: String Configuration file in ini format. See file ini/example_eeris.ini for an example. """ # Config file parsing config = configparser.ConfigParser() config.read(conf_file) # Set logging level if 'loglevel' not in config['eeRIS'].keys(): loglevel = logging.DEBUG else: loglevel = eval('logging.' + config['eeRIS']['loglevel']) logging.basicConfig(level=loglevel) # DB connection logging.info("Connecting to database") mclient = pymongo.MongoClient(config['eeRIS']['dburl']) dbname = config['eeRIS']['dbname'] dblist = mclient.list_database_names() if dbname in dblist: mdb = mclient[dbname] else: sys.stderr.write('ERROR: Database ' + dbname + ' not found. Exiting.') return # Authentication auth_backend = JWTAuthBackend(lambda user: user, config['REST']['jwt_psk'], algorithm='HS256', expiration_delta=24 * 60 * 60) auth_middleware = FalconAuthMiddleware(auth_backend, exempt_methods=['HEAD']) # auth_middleware = FalconAuthMiddleware(auth_backend) api = falcon.API(middleware=[auth_middleware]) # api = falcon.API() # NILM logging.info("Setting up connections") nilm = eeris_nilm.nilm.NILM(mdb, config) api.add_route('/nilm/{inst_id}', nilm) api.add_route('/nilm/{inst_id}/clustering', nilm, suffix='clustering') api.add_route('/nilm/{inst_id}/activations', nilm, suffix='activations') api.add_route('/nilm/{inst_id}/recomputation', nilm, suffix='recomputation') api.add_route('/nilm/{inst_id}/start_thread', nilm, suffix='start_thread') api.add_route('/nilm/{inst_id}/stop_thread', nilm, suffix='stop_thread') api.add_route('/nilm/{inst_id}/appliance_name', nilm, suffix='appliance_name') # Installation manager (for database management - limited functionality) # inst_ids = [x.strip() for x in config['eeRIS']['inst_ids'].split(",")] # inst_manager = eeris_nilm.installation.\ # InstallationManager(mdb, inst_list=inst_ids) # api.add_route('/installation/{inst_id}/model', inst_manager, # suffix='model') logging.info("Ready") return api
def on_get(self, req, resp): resp.append_header('Content-Type', 'text/plain') resp.append_header('Access-Control-Allow-Headers', 'Content-Type') resp.append_header('Access-Control-Allow-Methods', 'GET') resp.append_header('Access-Control-Allow-Origin', '*') try: dbx = dropbox.Dropbox(DROPBOX_KEY) all_files = dbx.files_list_folder('').entries all_files = list(filter(lambda file: 'treatmentprobabilities.csv' in file.name, all_files)) last_file = all_files[-1].name today = datetime.now().strftime('%Y-%m-%d') if last_file == f'{today}_treatmentprobabilities.csv': resp.body = 'pass' else: resp.body = 'fail' except DoesNotExist: resp.body = 'fail' token_auth = TokenAuthBackend(user_loader=user_loader) auth_middleware = FalconAuthMiddleware(token_auth, exempt_routes=['/thompson-probs/','/check-treatmentcsv/']) api = application = falcon.API(middleware=[auth_middleware]) api.add_route('/check-treatmentcsv/', CheckTreatmentCSV()) api.add_route('/thompson-probs/', ThompsonResource()) api.add_route('/job-openings/', JobOpeningResource()) api.add_route('/job-seekers/', JobSeekerResource()) api.add_route('/firms/', FirmResource()) api.add_route('/matches/', MatchResource()) api.add_route('/users/', UserResource()) api.add_route('/job-matches/', JobMatchResource()) api.add_route('/', HomeResource())
import falcon from models import * from playhouse.shortcuts import model_to_dict import json import uuid from g.auth import Auth from falcon_auth import FalconAuthMiddleware, BasicAuthBackend user_loader = lambda username, password: {'username': username} auth_backend = BasicAuthBackend(user_loader) auth_middleware = FalconAuthMiddleware(auth_backend, exempt_routes=['/exempt', '/jwt'], exempt_methods=['HEAD']) class MAuth(): auth = {'auth_disabled': False} def on_get(self, req, resp): if not 'user' in req.context: resp.status = falcon.HTTP_404 return user = req.context['user'] print(user) resp.body = "User Found: {}\n".format(user['username']) def on_head(self, req, resp): resp.body = '?'
# Allow requiring authentication via JWT if config["bel_api"]["authenticated"]: # Loads user data from JWT def user_loader(payload): # log.info(payload) return True auth_backend = JWTAuthBackend( user_loader=user_loader, secret_key=config["secrets"]["bel_api"]["shared_secret"], required_claims=["exp", "iat"], ) auth_middleware = FalconAuthMiddleware( auth_backend, exempt_routes=["/simple_status", "/healthcheck", "/version"], exempt_methods=["HEAD"], ) app = application = falcon.API(middleware=[stats_middleware, auth_middleware, cors.middleware]) else: app = application = falcon.API(middleware=[stats_middleware, cors.middleware]) # Add exception handling middleware.falcon_exceptions.register_defaults(app) # Add Swagger UI services.swaggerui.register_swaggerui(app)
import os import falcon_jsonify from falcon_auth import FalconAuthMiddleware, JWTAuthBackend import pymongo dbcfg = { 'host': 'localhost', # or external server address 'port': 27017, 'username': os.environ.get(''), 'password': os.environ.get(''), } # my_client = pymongo.MongoClient("mongodb://localhost:27017/") # my_db = my_client["iteqorchestrator"] # my_col = my_db["user"] # # # x = mycol.find_one() # mydict = {"userId": "BBOKYA01", "password": "******", "role": "bau"} # x = my_col.insert_one(mydict) # print(x) secret_key = 'ocr123' user_loader = lambda user: {'user': user} auth_backend = JWTAuthBackend(user_loader, secret_key) auth_middleware = FalconAuthMiddleware(auth_backend, exempt_routes=['/authenticate'], exempt_methods=['HEAD']) middleware = [auth_middleware]
# Setup Middlewares for Falcon API from falcon_auth import FalconAuthMiddleware, JWTAuthBackend from app.controllers.cred_checker import cred_checker from app.settings import ( jwt_secret_key, jwt_algorithm, jwt_auth_header_prefix, jwt_leeway, jwt_expiration_delta ) # Setup falcon-auth JWT Authentication based Middleware jwt_auth = JWTAuthBackend( user_loader=cred_checker, secret_key=jwt_secret_key, algorithm=jwt_algorithm, auth_header_prefix=jwt_auth_header_prefix, leeway=jwt_leeway, expiration_delta=jwt_expiration_delta, ) middleware = [ FalconAuthMiddleware(jwt_auth) ]
redis_conn = redis.StrictRedis.from_url(REDIS_URI) q: Queue = Queue(connection=redis_conn) # Elasticsearch es = Elasticsearch(ELASTICSEARCH_URI) if ELASTICSEARCH_URI else None # TODO might have to load a different configuration for production, look into # SQLAlchemy db: SQLAlchemy = SQLAlchemy(DATABASE_URI) from app import models # noqa # Authentication from .utilities import user_loader # noqa auth_backend = JWTAuthBackend(user_loader, secret_key=SECRET_KEY) auth_middleware = FalconAuthMiddleware(auth_backend, exempt_routes=["/swagger"]) # Falcon app_middleware = [ auth_middleware, SQLAlchemySessionManager(db), SerializationMiddleware(), ] api = falcon.API(middleware=app_middleware) # Documentation spec = APISpec( title="Movie Recommendation", version="0.0.1", openapi_version="2.0", info=dict(description="An example project API"),
def create_api(context: Context) -> falcon.App: auth_middleware = FalconAuthMiddleware(context.auth_backend) api = falcon.App(cors_enable=True, middleware=[auth_middleware, context.cache.middleware]) ebl.error_handler.set_up(api) return api
if config['bel_api']['authenticated']: # Loads user data from JWT def user_loader(payload): # log.info(payload) return True auth_backend = JWTAuthBackend( user_loader=user_loader, secret_key=config['secrets']['bel_api']['shared_secret'], required_claims=['exp', 'iat'], ) auth_middleware = FalconAuthMiddleware(auth_backend, exempt_routes=[ '/simple_status', '/healthcheck', '/version', ], exempt_methods=['HEAD']) api = application = falcon.API(middleware=[ stats_middleware, auth_middleware, cors.middleware, ]) else: api = application = falcon.API(middleware=[ stats_middleware, cors.middleware, ])
self.session.commit() resp.media = result('success') except NoResultFound: resp.media = error('no such user') ### END ### def jwt_loader(data): return data user_loader = jwt_loader auth_backend = JWTAuthBackend(user_loader, secret_key = SECRET_KEY, required_claims=['exp']) auth_middleware = FalconAuthMiddleware(auth_backend, exempt_routes=[ '/user/token', '/user/signup', ]) ### CORS CONFIG ### cors = CORS(allow_all_origins=True, allow_all_headers=True, allow_all_methods=True) ### END ### api = falcon.API(middleware=[cors.middleware, auth_middleware, SQLAlchemySessionManager(Session)]) ### USER Router ### api.add_route('/user/token', UserSignInResource()) # POST api.add_route('/user/signup', UserSignUpResource()) # POST ### END ### ### POST Router ###
import falcon from falcon_auth import FalconAuthMiddleware, BasicAuthBackend, TokenAuthBackend from .db import db # https://github.com/loanzen/falcon-auth def user_loader(username, password): return {"username": username} auth_backend = BasicAuthBackend(user_loader) auth_middleware = FalconAuthMiddleware( auth_backend, exempt_routes=["/exempt"], exempt_methods=["HEAD"] ) # auth = {"auth_disabled": True} class AppsResource: auth = {"backend": TokenAuthBackend(user_loader), "exempt_methods": ["GET", "HEAD"]} def on_get(self, req, resp): """Handles GET requests.""" quote = {"apps": {app.uuid: app.as_dict() for app in db.apps}} resp.media = quote def on_post(self, req, resp):
def create_app(): # type: () -> API # Get configuration config = Configuration() logging_args = { 'level': config.log_level } if config.log_output: logging_args['filename'] = config.log_output if config.log_format: logging_args['format'] = config.log_format if config.log_style: logging_args['style'] = config.log_style if config.log_dateformat: logging_args['datefmt'] = config.log_dateformat logging.basicConfig(**logging_args) logger = logging.getLogger(__name__) # Create SQLAlchemy engine basedir = os.path.abspath(os.path.dirname(__file__)) database = '%s:///%s' % (config.db_type, os.path.join(basedir, config.db_name)) engine = create_engine(database) sql_middleware = SqlAlchemy(engine) # Drop DB if required if config.drop_db: logger.debug('Dropping current DB...') drop_db(engine) logger.debug('Current DB dropped. Recreating new DB...') else: logger.debug('Creating DB if not present') # Create DB if needed create_db(engine) logger.debug('DB created (if needed). Initializing DB content if needed.') init_db(sql_middleware.new_session(), config.matches_txt_timezone) logger.debug('DB content initialized (if needed).') sql_middleware.delete_session() # Create TimeBase service timebase = TimeBase() # Create basic authenticator for use with all Auth backend authenticator = Authenticator(timebase, sql_middleware) # Create default Token Auth backend backend = TokenAuthBackend(authenticator) # Create Falcon API with proper middleware: Marshmallow (validation), SQLAlchemy (persistence) api = API(middleware=[LoggingMiddleware(), sql_middleware, FalconAuthMiddleware(backend), context_middleware, Marshmallow()]) api.add_error_handler(Exception, ExceptionHandler(falcon.HTTP_INTERNAL_SERVER_ERROR, "Internal error")) api.add_error_handler(DBAPIError, ExceptionHandler(falcon.HTTP_INTERNAL_SERVER_ERROR, "Database error")) api.add_error_handler(IntegrityError, ExceptionHandler(falcon.HTTP_UNPROCESSABLE_ENTITY, "Integrity constraint error")) # We have to re-register the following handlers because although registered by default, # they will never get called due to our Exception handler api.add_error_handler(falcon.HTTPError, api._http_error_handler) api.add_error_handler(falcon.HTTPStatus, api._http_status_handler) from .resources import Team, Teams, Venue, Venues, Match, Matches, Bets, User, Users, Token, Time, Profile if config.timebase_changes: api.add_route('/time', Time(timebase)) api.add_route('/token', Token()) api.add_route('/team', Teams()) api.add_route('/team/{id:int}', Team()) api.add_route('/venue', Venues()) api.add_route('/venue/{id:int}', Venue()) api.add_route('/match', Matches()) api.add_route('/match/{id:int}', Match(timebase)) api.add_route('/user', Users(timebase)) api.add_route('/user/{id_or_name}', User()) api.add_route('/bet', Bets(timebase)) api.add_route('/profile', Profile(timebase)) logger.info('API service started.') return api
def __init__(self, cfg): token_auth = TokenAuthBackend(User.get_by_token) basic_auth = BasicAuthBackend(User.get_by_basic_auth) multi_auth = MultiAuthBackend(token_auth, basic_auth) auth_middleware = FalconAuthMiddleware(multi_auth) super(AnalystService, self).__init__( middleware=[ CORSComponentMiddleware(), RequireJSONMiddleware(), auth_middleware, ] ) handlers = falcon.media.Handlers({"application/json": DateTimeJSONHandler()}) self.resp_options.media_handlers.update(handlers) self.resp_options.default_media_type = "application/json" self.router_options.converters["ipv4_addr"] = IPV4Converter self.router_options.converters[ "lowercase_alpha_num" ] = LowerCaseAlphaNumConverter self.cfg = cfg # Build an object to manage our db connections. self.manager = DBManager(self.cfg.db.file_path) self.manager.setup() # Build routes self.add_route(f"/api/{self.cfg.version}/init", users.InitResource()) self.add_route(f"/api/{self.cfg.version}/users", users.UsersResource()) self.add_route( f"/api/{self.cfg.version}/users/{{username:lowercase_alpha_num}}", users.UsersResource(), ) self.add_route( f"/api/{self.cfg.version}/tokens/{{username:lowercase_alpha_num}}", tokens.TokensResource(), ) self.add_route( f"/api/{self.cfg.version}/asn", asn.ASNResource(self.cfg.asn_path) ) self.add_route( f"/api/{self.cfg.version}/asn/{{ip:ipv4_addr}}", asn.ASNResource(self.cfg.asn_path), ) self.add_route( f"/api/{self.cfg.version}/geo", geo.GeoResource(self.cfg.geo_path) ) self.add_route( f"/api/{self.cfg.version}/geo/{{ip:ipv4_addr}}", geo.GeoResource(self.cfg.geo_path), ) self.add_route(f"/api/{self.cfg.version}/iplists", iplists.IPListResource()) self.add_route( f"/api/{self.cfg.version}/iplists/{{ip_list_name:lowercase_alpha_num}}", iplists.IPListResource(), ) self.add_route( f"/api/{self.cfg.version}/iplists/{{ip_list_name:lowercase_alpha_num}}/items", iplists.IPListItemResource(), )
user = _users.get(uid) except Exception as e: try: email = args[0]['user']['subject'] user = _users.first(email=email) except Exception as e: console.error(e) raise return user secret_key = os.environ.get('SECRET_KEY') auth_backend = JWTAuthBackend(user_loader, secret_key) auth_middleware = FalconAuthMiddleware(auth_backend, exempt_routes=EXEMPT_ROUTES, exempt_methods=['HEAD']) # Setup CORS cors = CORS(allow_origins_list=[ 'http://localhost:8080', 'http://smpa-frontend-staging.s3-website.eu-west-2.amazonaws.com', 'https://planningapplication.hackney.gov.uk', 'https://planningapplication-staging.hackney.gov.uk' ], allow_all_headers=True, allow_all_methods=True) # Create the Falcon app # api = application = falcon.API() # NO AUTH api = application = falcon.API(
import falcon from falcon_auth import FalconAuthMiddleware import jwtapi.env as ENV import jwtapi.app_auth as app_auth import jwtapi.app_resources as app_resources from jwtapi.app_db import Session, SQLAlchemySessionManager open_routes = ['/api/v1/auth/login', '/api/v1/auth/refresh', '/api/v1/auth/user-mgmt', '/api/v1/media/public', ] auth_middleware = FalconAuthMiddleware(app_auth.jwt_auth, exempt_routes=open_routes) db_middleware = SQLAlchemySessionManager(Session) cors_middleware = app_auth.CORSComponent() def create_app(): api = falcon.API(middleware=[auth_middleware, db_middleware, cors_middleware]) api.add_route('/api/v1/auth/login', app_auth.Login()) api.add_route('/api/v1/auth/refresh', app_auth.RefreshToken()) api.add_route('/api/v1/auth/invalidate', app_auth.InvalidateToken()) api.add_route('/api/v1/auth/user-mgmt', app_auth.UserMgmt()) api.add_route('/api/v1/media/public', app_resources.PublicInfo()) api.add_route('/api/v1/media/private', app_resources.PrivateInfo()) # Secure cookies (http/https) #api.resp_options.secure_cookies_by_default = ENV.RUNNING_IN_PROD #
#Auth from auth import (auth_backend, loadUser) #URLs from urls import urls from api.v1.server import serverInfo cors = CORS(allow_origins_list=['*'], allow_all_methods=True, allow_all_origins=True, allow_all_headers=True) #Auth values auth_middleware = FalconAuthMiddleware(auth_backend, exempt_methods=['OPTIONS']) #Create the app app = falcon.API(middleware=[ cors.middleware, auth_middleware, PeeweeConnectionMiddleware(), MultipartMiddleware(), ]) #Routes app.add_route('/info', serverInfo()) app.add_route('/api/v1/accounts/{username}', getUser()) app.add_route('/api/v1/accounts/{username}/statuses', getStatuses()) app.add_route('/api/v1/accounts/{username}/followers', getFollowers())
import falcon from falcon_auth import FalconAuthMiddleware, BasicAuthBackend, TokenAuthBackend def user_loader(username, password): return {'username': username} auth_backend = BasicAuthBackend(user_loader) auth_middleware = FalconAuthMiddleware(auth_backend) api = falcon.API(middleware=[auth_middleware]) class ApiResourceBasicAuth: def on_post(self, req, resp): user = req.context['user'] resp.body = 'User Found: {}'.format(user['username']) # def on_get(self, req, resp): # resp.body = "This is resource doesn't need authentication" class ApiResourceTokenAuth: auth = { 'backend': TokenAuthBackend(user_loader=lambda token: {'id': 'token123'}), 'exempt_methods': ['GET'] }
import falcon from falcon_auth import FalconAuthMiddleware from utils import constants as cst os.environ['BASEPATH'] = cst.BASE_PATH sys.path.append(cst.BASE_PATH) from middleware.authorization import Authorization from middleware.cors import CORSComponent from middleware.json_translator import JSONTranslator from middleware.require_json import RequireJSON from endpoints.v1.test import Test auth_middleware = FalconAuthMiddleware(Authorization(), exempt_routes=['/api/v1/test']) api = falcon.API(middleware=[ auth_middleware, CORSComponent(), JSONTranslator(), RequireJSON() ]) test = Test() ROUTES = {"/test": test} for k, v in ROUTES.items(): api.add_route(cst.ROUTE_PREFIX + k, v)
from falcon_auth import FalconAuthMiddleware, JWTAuthBackend def user_loader(payload: dict): username = payload.get('username') password = payload.get('password') if username == settings.JWT_CONFIG[ 'username'] and password == settings.JWT_CONFIG['password']: # noqa return username else: return None auth_backend = JWTAuthBackend(user_loader, secret_key=settings.JWT_CONFIG['secret_key'], verify_claims=['exp'], required_claims=['exp']) exempt_routes = ['/'] auth_middleware = FalconAuthMiddleware(auth_backend, exempt_routes=exempt_routes, exempt_methods=['HEAD']) app = falcon.API(middleware=[ auth_middleware, db.SQLAlchemySessionManager(db.Session), ], ) app.add_route('/', resources.HomeResource()) app.add_route('/customers', resources.CustomerCollectionResource()) app.add_route('/customers/{customer_id}', resources.CustomerItemResource())