def setup(): # Initializing OAuth oauth = OAuth(current_app) current_app.secret_key = 'random_string' global auth0 auth0 = oauth.register( 'auth0', client_id=os.environ['CLIENT_ID'], client_secret=os.environ['CLIENT_SECRET'], api_base_url=os.environ['AUTH0_DOMAIN'], access_token_url=os.environ['AUTH0_DOMAIN'] + '/oauth/token', authorize_url=os.environ['AUTH0_DOMAIN'] + '/authorize', client_kwargs={ 'scope': 'openid profile', }, )
def test_oauth2_access_token_with_post(self): app = Flask(__name__) app.secret_key = '!' oauth = OAuth(app) client = oauth.register('dev', client_id='dev', client_secret='dev', base_url='https://i.b/api', access_token_url='https://i.b/token', authorize_url='https://i.b/authorize') payload = {'code': 'a', 'state': 'b'} with app.test_request_context(data=payload, method='POST'): session['_dev_state_'] = 'b' with mock.patch('requests.sessions.Session.send') as send: send.return_value = mock_send_value(get_bearer_token()) token = client.authorize_access_token() self.assertEqual(token['access_token'], 'a')
def init_auth(state): global auth oauth = OAuth(state.app) config = state.app.config provider = config.get('AUTH_PROVIDER') scope = config.get('AUTH_SCOPE') domain = config.get('AUTH_DOMAIN') client_id = config.get('AUTH_CLIENT_ID') client_secret = config.get('AUTH_CLIENT_SECRET') auth = oauth.register( provider, client_id=client_id, client_secret=client_secret, api_base_url=domain, access_token_url='{}/oauth/token'.format(domain), authorize_url='{}/authorize'.format(domain), client_kwargs={ 'scope': scope, }, )
def test_request_with_refresh_token(self): app = Flask(__name__) app.secret_key = '!' oauth = OAuth() expired_token = { 'token_type': 'Bearer', 'access_token': 'expired-a', 'refresh_token': 'expired-b', 'expires_in': '3600', 'expires_at': 1566465749, } oauth.init_app(app, fetch_token=lambda name: expired_token) client = oauth.register('dev', client_id='dev', client_secret='dev', api_base_url='https://i.b/api', access_token_url='https://i.b/token', refresh_token_url='https://i.b/token', authorize_url='https://i.b/authorize') def fake_send(sess, req, **kwargs): if req.url == 'https://i.b/token': auth = req.headers['Authorization'] self.assertIn('Basic', auth) resp = mock.MagicMock() resp.json = get_bearer_token resp.status_code = 200 return resp resp = mock.MagicMock() resp.text = 'hi' resp.status_code = 200 return resp with app.test_request_context(): with mock.patch('requests.sessions.Session.send', fake_send): resp = client.get('/api/user', token=expired_token) self.assertEqual(resp.text, 'hi')
def test_request_withhold_token(self): app = Flask(__name__) app.secret_key = '!' oauth = OAuth(app) client = oauth.register('dev', client_id='dev', client_secret='dev', api_base_url='https://i.b/api', access_token_url='https://i.b/token', authorize_url='https://i.b/authorize') def fake_send(sess, req, **kwargs): auth = req.headers.get('Authorization') self.assertIsNone(auth) resp = mock.MagicMock() resp.text = 'hi' resp.status_code = 200 return resp with app.test_request_context(): with mock.patch('requests.sessions.Session.send', fake_send): resp = client.get('/api/user', withhold_token=True) self.assertEqual(resp.text, 'hi')
def test_oauth2_authorize_code_challenge(self): app = Flask(__name__) app.secret_key = '!' oauth = OAuth(app) client = oauth.register( 'dev', client_id='dev', api_base_url='https://i.b/api', access_token_url='https://i.b/token', authorize_url='https://i.b/authorize', code_challenge_method='S256', ) with app.test_request_context(): resp = client.authorize_redirect('https://b.com/bar') self.assertEqual(resp.status_code, 302) url = resp.headers.get('Location') self.assertIn('code_challenge=', url) self.assertIn('code_challenge_method=S256', url) state = session['_dev_authlib_state_'] self.assertIsNotNone(state) verifier = session['_dev_authlib_code_verifier_'] self.assertIsNotNone(verifier) def fake_send(sess, req, **kwargs): self.assertIn('code_verifier={}'.format(verifier), req.body) return mock_send_value(get_bearer_token()) path = '/?code=a&state={}'.format(state) with app.test_request_context(path=path): # session is cleared in tests session['_dev_authlib_state_'] = state session['_dev_authlib_code_verifier_'] = verifier with mock.patch('requests.sessions.Session.send', fake_send): token = client.authorize_access_token() self.assertEqual(token['access_token'], 'a')
from flask import render_template from flask import session from flask import url_for from authlib.flask.client import OAuth from six.moves.urllib.parse import urlencode red = redis.StrictRedis(host='localhost', port=6379, db=0) redis = redis.Redis() app = Flask(__name__, static_url_path='/static') oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id='PzTcCUU6vODEaglC6h9Q5P3ehAwsYvHD', client_secret= 'ZH2ukJcn_73uE407Zlr360qJnT-LvCcol0SHRQ9eEEYRoYT1bKvvowPvmzuwnE3H', api_base_url='https://darkflame666.eu.auth0.com', access_token_url='https://darkflame666.eu.auth0.com/oauth/token', authorize_url='https://darkflame666.eu.auth0.com/authorize', client_kwargs={ 'scope': 'openid profile', }, ) app.secret_key = b'0293jr i(UHoiawu hft923' app.jwt_secret_key = 'SecretKey' jwtPassword = '******' APP_ROOT = os.path.dirname(os.path.abspath(__file__)) UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static/uploads') app.upload_path = Path(os.path.join(APP_ROOT, './static/uploads')) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config.update( dict(
# AUTH0_DOMAIN = "{YOUR-AUTH0-DOMAIN}" AUTH0_DOMAIN = "172.42.42.30:8280" AUTH0_BASE_URL = 'https://' + AUTH0_DOMAIN # AUTH0_AUDIENCE = "{YOUR-AUDIENCE}" AUTH0_AUDIENCE = "account" oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id=AUTH0_CLIENT_ID, client_secret=AUTH0_CLIENT_SECRET, api_base_url=AUTH0_BASE_URL, # https://172.42.42.30:8280/auth/realms/bookshop/protocol/openid-connect/token access_token_url=AUTH0_BASE_URL + '/auth/realms/bookshop/protocol/openid-connect/token', # https://172.42.42.30:8280/auth/realms/bookshop/protocol/openid-connect/auth authorize_url=AUTH0_BASE_URL + '/auth/realms/bookshop/protocol/openid-connect/auth', client_kwargs={ 'scope': 'openid profile', }, ) servicesDomain = "" if (os.environ.get("SERVICES_DOMAIN") == None) else "." + os.environ.get("SERVICES_DOMAIN") details = { "name": "http://details{0}:9080".format(servicesDomain), "endpoint": "details", "children": []
app = Flask(__name__.split()[0], instance_relative_config='NO_INSTANCE_CONFIG' not in os.environ) # Loads configuration information from config.py and instance/config.py app.config.from_object('config') if 'NO_INSTANCE_CONFIG' not in os.environ: app.config.from_pyfile('config.py') celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) # Enable authentication if configured. oauth = None # pylint: disable=C0103 if app.config.get('WATERAUTH_AUTHORIZE_URL'): oauth = OAuth(app) # pylint: disable=C0103 oauth.register('waterauth', client_kwargs={'verify': app.config.get('VERIFY_CERT', True)} ) if app.config.get('LOGGING_ENABLED'): log_directory = app.config.get('LOGGING_DIRECTORY') loglevel = app.config.get('LOGGING_LEVEL') handler = _create_log_handler(log_directory) # Do not set logging level in the handler. # Otherwise, if Flask's DEBUG is set to False, # all logging will be disabled. # Instead, set the level in the logger object. app.logger.setLevel(loglevel) app.logger.addHandler(handler) # celery uses two loggers: one global/worker logger and a second task logger # global/worker logs are handled by the celeryd process running the VM # this configures a handler for the task logger:
from authlib.flask.client import OAuth import config from config import Config import os if os.getenv('FLASK_ENV') == 'production': config = eval("config.ProductionConfig") else: config = eval("config.DevelopmentConfig") oauth = OAuth() oauth.register('google', client_id=Config.GOOGLE_CLIENT_ID, client_secret=Config.GOOGLE_CLIENT_SECRET, access_token_url='https://accounts.google.com/o/oauth2/token', access_token_params=None, refresh_token_url=None, authorize_url='https://accounts.google.com/o/oauth2/auth', api_base_url='https://www.googleapis.com/oauth2/v1/', client_kwargs={ 'scope': 'https://www.googleapis.com/auth/userinfo.email', 'token_endpoint_auth_method': 'client_secret_basic', 'token_placement': 'header', 'prompt': 'consent' })
app = Flask(__name__.split()[0], instance_relative_config='NO_INSTANCE_CONFIG' not in os.environ) # Loads configuration information from config.py and instance/config.py app.config.from_object('config') if 'NO_INSTANCE_CONFIG' not in os.environ: app.config.from_pyfile('config.py') celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) # Enable authentication if configured. oauth = None # pylint: disable=C0103 if app.config.get('WATERAUTH_AUTHORIZE_URL'): oauth = OAuth(app) # pylint: disable=C0103 oauth.register('waterauth', client_kwargs={'verify': app.config.get('VERIFY_CERT', True)} ) if app.config.get('LOGGING_ENABLED'): log_directory = app.config.get('LOGGING_DIRECTORY') loglevel = app.config.get('LOGGING_LEVEL') handler = _create_log_handler(log_directory) # Do not set logging level in the handler. # Otherwise, if Flask's DEBUG is set to False, # all logging will be disabled. # Instead, set the level in the logger object. app.logger.setLevel(loglevel) app.logger.addHandler(handler) # celery uses two loggers: one global/worker logger and a second task logger # global/worker logs are handled by the celeryd process running the VM # this configures a handler for the task logger:
from six.moves.urllib.parse import urlencode # ----------------------------------------------------------------------------# # App Config. # ----------------------------------------------------------------------------# app = Flask(__name__) app.config.from_object('config') oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id=app.config['OAUTH_CLIENT_ID'], client_secret=app.config['OAUTH_CLIENT_SECRET'], api_base_url=app.config['OAUTH_API_BASE_URL'], access_token_url=app.config['OAUTH_ACCESS_TOKEN_URL'], authorize_url=app.config['OAUTH_AUTHORIZE_URL'], client_kwargs={ 'scope': 'openid profile email offline_access', }, ) logging.basicConfig(level='INFO') def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): if 'profile' not in session: # Redirect to Login page here return redirect('/login')
'http://localhost:5005/callback') #SESSION_TYPE = 'null' #SESSION_PERMANENT = False #SESSION_USE_SIGNER = True #PERMANENT_SESSION_LIFETIME = 4200 #app.config.from_object(__name__) #Session(app) auth0 = oauth.register( 'auth0', client_id=os.getenv('AUTH0_CLIENT_ID', par['client']), client_secret=os.getenv('AUTH0_CLIENT_SECRET', par['client_sec']), api_base_url=os.getenv('AUTH0_DOMAIN', par['domain']), access_token_url=os.getenv('AUTH0_DOMAIN' + '/oauth/token', par['domain'] + '/oauth/token'), authorize_url=os.getenv('AUTH0_DOMAIN' + '/authorize', par['domain'] + '/authorize'), client_kwargs={ 'scope': 'openid profile', }, ) def mail(from_who, subjectsend, message): from_email = Email(from_who) to_email = Email(receipent) subject = subjectsend content = Content("text/plain", message) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get())
app.secret_key = ConfigManager.get_config("APP_SECRET_KEY") app.config["APPLICATION_ROOT"] = ConfigManager.get_config( "APP_APPLICATION_ROOT") app.config.update(SESSION_COOKIE_HTTPONLY=__is_app_secured, SESSION_COOKIE_SECURE=__is_app_secured, REMEMBER_COOKIE_HTTPONLY=__is_app_secured, REMEMBER_COOKIE_SECURE=__is_app_secured) oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id=__oauth_client_id, client_secret=ConfigManager.get_config("OAUTH_CLIENT_SECRET"), api_base_url=ConfigManager.get_config("OAUTH_API_BASE_URL"), access_token_url=ConfigManager.get_config("OAUTH_ACCESS_TOKEN_URL"), authorize_url=ConfigManager.get_config("OAUTH_AUTHORIZE_URL"), client_kwargs={ 'scope': 'openid profile', }, ) def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): if 'sid' not in session: return ResponseManager.create_response_401() valid = SessionManager.check_session_valid(session['username'], session['sid'])
import requests from authlib.flask.client import OAuth from authlib.jose import jwk, jwt from authlib.oidc.core import CodeIDToken, ImplicitIDToken, UserInfo from flask import current_app from itsdangerous import URLSafeTimedSerializer from werkzeug.local import LocalProxy oauth = OAuth() oauth.register('oidc') secure_serializer = LocalProxy(lambda: URLSafeTimedSerializer( current_app.config['SECRET_KEY'], b'newdle')) # based on https://github.com/authlib/loginpass/blob/master/loginpass/_core.py (BSD) def parse_id_token(token_data, nonce): def load_key(header, payload): # TODO: cache this? jwk_set = requests.get(current_app.config['OIDC_JWKS_URL']).json() return jwk.loads(jwk_set, header.get('kid')) id_token = token_data['id_token'] claims_params = { 'nonce': nonce, 'client_id': current_app.config['OIDC_CLIENT_ID'] } if 'access_token' in token_data: claims_params['access_token'] = token_data['access_token'] claims_cls = CodeIDToken else:
from flask import redirect, render_template, url_for, request, session from app import log, app from . import auth import json from authlib.flask.client import OAuth oauth = OAuth(app) smartschool = oauth.register('smartschool') @auth.route('/', methods=['GET', 'POST']) def login(): if 'app_uri' in request.args: session['app_uri'] = request.args['app_uri'] # Step 1 : go to smartschool so that the user can log in with smartschool credentials redirect_uri = app.config['REDIRECT_URI'] return oauth.smartschool.authorize_redirect(redirect_uri) if 'code' in request.args: # received a request with a OAUTH code # Step 2 : with the code from smartschool, fetch the access_token from smartschool token = oauth.smartschool.authorize_access_token() return redirect( url_for('auth.smartschool_profile', token=json.dumps(token))) # OAUTH specific @auth.route('/smartschool_profile/<string:token>', methods=['GET', 'POST']) def smartschool_profile(token): # Step 3 : with the access_code, get the userinfo from SS resp = oauth.smartschool.get('fulluserinfo', token=json.loads(token)) profile = resp.json()
def create_app(): app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config['production']) app.config.from_pyfile('config.py') app.config['SERVER_DOMAIN'] = '.internmate.tech' app.config['SESSION_COOKIE_DOMAIN'] = '.internmate.tech' Bootstrap(app) csrf.init_app(app) oauth = OAuth(app) db.init_app(app) auth0 = oauth.register( 'auth0', client_id='b8IJ3nS40w2Hvetco79z5NChA6NLJOel', client_secret= 'tfIxeIut3gBZI_7Hwrwbd5vpxzFQRzIhrBqfbxHt-ArShk6GTyX_woPgQV1Hl_d8', api_base_url='https://internmate-dev.auth0.com', access_token_url='https://internmate-dev.auth0.com/oauth/token', authorize_url='https://internmate-dev.auth0.com/authorize', client_kwargs={ 'scope': 'openid profile email', }, ) from app import models from app.models import User from .users import user as user_blueprint app.register_blueprint(user_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) from .api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api') def add_user(user_info): #used when a new user signs in. We add them to db loginType = user_info['sub'] google = 'google' in loginType facebook = 'facebook' in loginType linkedin = 'linkedin' in loginType user = User(email=user_info['email'], name=user_info['name'], online=True, google=google, facebook=facebook, linkedin=linkedin, image_url=user_info['picture']) db.session.add(user) db.session.commit() """ After successful login from Auth0, we take a callback to verify the login mechanism """ @app.route('/callback') def callback_handling(): auth0.authorize_access_token() resp = auth0.get('userinfo') userinfo = resp.json() user = User.query.filter_by(email=userinfo['email']).first() # following can be improved loginType = userinfo['sub'] google = 'google' in loginType facebook = 'facebook' in loginType linkedin = 'linkedin' in loginType # add the new login flow on setup if there is any if user is not None: # user has already registered before # for the following if check, i am thinking of storing mode of login as an array instead of boolean to make it easier. if not user.google: user.google = google if not user.facebook: user.facebook = facebook if not user.linkedin: user.linkedin = linkedin update_login_mode = User.query.filter_by( user_id=user.user_id).update( dict(google=user.google, linkedin=user.linkedin, facebook=user.facebook, online=True)) db.session.commit() session['jwt_payload'] = userinfo session['profile'] = { 'user_id': user.user_id, 'name': userinfo['name'], 'picture': userinfo['picture'], 'email': userinfo['email'], 'username': userinfo['nickname'] } return redirect('/feed') else: add_user(userinfo) user = User.query.filter_by(email=userinfo['email']).first() session['jwt_payload'] = userinfo session['profile'] = { 'user_id': user.user_id, 'name': userinfo['name'], 'picture': userinfo['picture'], 'email': userinfo['email'], 'username': userinfo['nickname'] } return redirect('/complete/profile') @app.route('/login') def login(): print(session) if 'profile' in session: get_user = User.query.get(session['profile']['user_id']) if get_user is not None and get_user.online: return redirect('/feed') else: return auth0.authorize_redirect( redirect_uri='https://internmate.tech/callback', audience='https://internmate-dev.auth0.com/userinfo') return auth0.authorize_redirect( redirect_uri='https://internmate.tech/callback', audience='https://internmate-dev.auth0.com/userinfo') @app.route('/logout') def logout(): user_notonline = User.query.filter_by( email=session['profile']['email']).update(dict(online=False)) db.session.commit() session.clear() params = { 'returnTo': 'https://internmate.tech', 'client_id': '47qc5c1iQ4p39w7M5YtptgZQdGJR573b' } #return redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params)) return redirect('/') @app.route('/') def home(): if 'profile' in session: get_user = User.query.get(session['profile']['user_id']) if get_user is not None and get_user.online: return redirect('/feed') else: return render_template('home/index.html') @app.errorhandler(403) def forbidden(e): return render_template('403.html') return app
from six.moves.urllib.request import urlopen from six.moves.urllib.parse import urlencode from app.users.utils import add_user ALGORITHMS = ["RS256"] auth = Blueprint('auth', __name__, url_prefix='/api/v1/auth') oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id=CLIENT_ID, client_secret=SECRET_KEY, api_base_url='https://durian-inc.auth0.com', access_token_url='https://durian-inc.auth0.com/oauth/token', authorize_url='https://durian-inc.auth0.com/authorize', client_kwargs={ 'scope': 'openid profile', }, ) # TODO: Make above urls environment variables def requires_auth(func): """Decorator to specify that function needs to be authenticated""" @wraps(func) def decorated(*args, **kwargs): """Check authentication, or get failure"""
from authlib.flask.client import OAuth from flask import Blueprint, url_for, request, redirect from furl import furl from config import EIAS_OAUTH2_KEY, EIAS_OAUTH2_SECRET, EIAS_BASE_URL, FRONTED_URL, EIAS_USER_ME from models import OAuth2Token, db from schemas import OAuth2TokenSchema oauth_registration = Blueprint('oauth', __name__) eias = OAuth() eias.register( name='passport', client_id=EIAS_OAUTH2_KEY, client_secret=EIAS_OAUTH2_SECRET, access_token_url=EIAS_BASE_URL + 'oauth2/token/', authorize_url=EIAS_BASE_URL + 'oauth2/authorize/', api_base_url=EIAS_BASE_URL, ) @oauth_registration.route('/login') def login(): redirect_uri = url_for('oauth.authorize', _external=True) return eias.passport.authorize_redirect(redirect_uri) @oauth_registration.route('/authorize/') def authorize(): token = eias.passport.authorize_access_token() user = eias.passport.get(f'{EIAS_USER_ME}').json()
def create_app(test_config=None): # create and configure the app app = Flask(__name__) app.secret_key = "super secret key" setup_db(app) # setup cross origin CORS(app) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true') response.headers.add('Access-Control-Allow-Methods', 'GET,PATCH,POST,DELETE,OPTIONS') return response oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id=AUTH0_CLIENT_ID, client_secret=AUTH0_CLIENT_SECRET, api_base_url=AUTH0_BASE_URL, access_token_url=AUTH0_BASE_URL + '/oauth/token', authorize_url=AUTH0_BASE_URL + '/authorize', client_kwargs={ 'scope': 'openid profile email', }, ) # Setup home route @app.route('/') def index(): return render_template('index.html') @app.route('/login') def login(): return auth0.authorize_redirect(redirect_uri=AUTH0_CALLBACK_URL, audience=AUTH0_AUDIENCE) @app.route('/callback') def callback_handling(): # Handles response from token endpoint res = auth0.authorize_access_token() token = res.get('access_token') # Store the user information in flask session. session['jwt_token'] = token return redirect('/dashboard') @app.route('/logout') def logout(): # Clear session stored data session.clear() # Redirect user to logout endpoint params = { 'returnTo': url_for('index', _external=True), 'client_id': AUTH0_CLIENT_ID } return redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params)) @app.route('/dashboard') @requires_signed_in def dashboard(): return render_template( 'dashboard.html', token=session['jwt_token'], ) """Movies Routes""" # Route for getting all movies @app.route('/movies') @requires_auth('read:movies') def get_movies(jwt): """Get all movies route""" movies = Movie.query.all() return jsonify({ 'success': True, 'movies': [movie.format() for movie in movies], }), 200 # Route for getting a specific movie @app.route('/movies/<int:id>') @requires_auth('read:movies') def get_movie_by_id(jwt, id): """Get a specific movie route""" movie = Movie.query.get(id) # return 404 if there is no movie with id if movie is None: abort(404) else: return jsonify({ 'success': True, 'movie': movie.format(), }), 200 @app.route('/movies', methods=['POST']) @requires_auth('create:movies') def post_movie(jwt): """Create a movie route""" # Process request data data = request.get_json() title = data.get('title', None) release_date = data.get('release_date', None) # return 400 for empty title or release date if title is None or release_date is None: abort(400) movie = Movie(title=title, release_date=release_date) try: movie.insert() return jsonify({'success': True, 'movie': movie.format()}), 201 except Exception: abort(500) @app.route('/movies/<int:id>', methods=['PATCH']) @requires_auth('edit:movies') def patch_movie(jwt, id): """Update a movie route""" data = request.get_json() title = data.get('title', None) release_date = data.get('release_date', None) movie = Movie.query.get(id) if movie is None: abort(404) if title is None or release_date is None: abort(400) movie.title = title movie.release_date = release_date try: movie.update() return jsonify({'success': True, 'movie': movie.format()}), 200 except Exception: abort(500) @app.route('/movies/<int:id>', methods=['DELETE']) @requires_auth('delete:movies') def delete_movie(jwt, id): """Delete a movie route""" movie = Movie.query.get(id) if movie is None: abort(404) try: movie.delete() return jsonify({ 'success': True, 'message': f'movie id {movie.id}, titled {movie.title} was deleted', }) except Exception: db.session.rollback() abort(500) """Actors Routes""" @app.route('/actors') @requires_auth('read:actors') def get_actors(jwt): """Get all actors route""" actors = Actor.query.all() return jsonify({ 'success': True, 'actors': [actor.format() for actor in actors], }), 200 @app.route('/actors/<int:id>') @requires_auth('read:actors') def get_actor_by_id(jwt, id): """Get all actors route""" actor = Actor.query.get(id) if actor is None: abort(404) else: return jsonify({ 'success': True, 'actor': actor.format(), }), 200 @app.route('/actors', methods=['POST']) @requires_auth('create:actors') def post_actor(jwt): """Get all movies route""" data = request.get_json() name = data.get('name', None) age = data.get('age', None) gender = data.get('gender', None) actor = Actor(name=name, age=age, gender=gender) if name is None or age is None or gender is None: abort(400) try: actor.insert() return jsonify({'success': True, 'actor': actor.format()}), 201 except Exception: abort(500) @app.route('/actors/<int:id>', methods=['PATCH']) @requires_auth('edit:actors') def patch_actor(jwt, id): """Update an actor Route""" data = request.get_json() name = data.get('name', None) age = data.get('age', None) gender = data.get('gender', None) actor = Actor.query.get(id) if actor is None: abort(404) if name is None or age is None or gender is None: abort(400) actor.name = name actor.age = age actor.gender = gender try: actor.update() return jsonify({'success': True, 'actor': actor.format()}), 200 except Exception: abort(500) @app.route('/actors/<int:id>', methods=['DELETE']) @requires_auth('delete:actors') def delete_actor(jwt, id): """Delete an actor Route""" actor = Actor.query.get(id) if actor is None: abort(404) try: actor.delete() return jsonify({ 'success': True, 'message': f'actor id {actor.id}, named {actor.name} was deleted', }) except Exception: db.session.rollback() abort(500) # Error Handling @app.errorhandler(422) def unprocessable(error): return jsonify({ "success": False, "error": 422, "message": "unprocessable" }), 422 @app.errorhandler(404) def resource_not_found(error): return jsonify({ "success": False, "error": 404, "message": "resource not found" }), 404 @app.errorhandler(400) def bad_request(error): return jsonify({ "success": False, "error": 400, "message": "bad request" }), 400 @app.errorhandler(500) def internal_server_error(error): return jsonify({ "success": False, "error": 500, "message": "internal server error" }), 500 @app.errorhandler(AuthError) def handle_auth_error(exception): response = jsonify(exception.error) response.status_code = exception.status_code return response return app
def get_debug_flag() -> bool: if int(env.get('DEBUG', '1')) > 0: print('DEBUG ENABLED') return True return False DEBUG_FLAG = get_debug_flag() app.debug = DEBUG_FLAG oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id=env.get('AUTH0_CLIENT_ID', 'no-value'), client_secret=env.get('AUTH0_CLIENT_SECRET', 'no-value'), api_base_url=env.get('AUTH0_BASE_URL', 'no-value'), access_token_url='{}/oauth/token'.format( env.get('AUTH0_BASE_URL', 'no-value')), authorize_url='{}/authorize'.format(env.get('AUTH0_BASE_URL', 'no-value')), client_kwargs={ 'scope': 'openid profile', }, ) def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): if 'profile' not in session: # Redirect to Login page here return redirect('/') return f(*args, **kwargs)
from flask import Flask, redirect, request, render_template, session, jsonify from functools import wraps redirect_uri = 'http://*****:*****@app.route('/') def home(): return render_template('home.html') @app.route('/login') def login(): return client.authorize_redirect(redirect_uri=redirect_uri)
USE_SECURE_COOKIE = os.environ.get("NOTEBOOK_DEBUG") != "1" app.config.update(SECRET_KEY=SESSION_SECRET_KEY, SESSION_COOKIE_SAMESITE='Lax', SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SECURE=USE_SECURE_COOKIE) AUTH0_CLIENT_ID = 'Ck5wxfo1BfBTVbusBeeBOXHp3a7Z6fvZ' AUTH0_BASE_URL = 'https://hail.auth0.com' auth0 = oauth.register( 'auth0', client_id=AUTH0_CLIENT_ID, client_secret=read_string('/notebook-secrets/auth0-client-secret'), api_base_url=AUTH0_BASE_URL, access_token_url=f'{AUTH0_BASE_URL}/oauth/token', authorize_url=f'{AUTH0_BASE_URL}/authorize', client_kwargs={ 'scope': 'openid email profile', }, ) user_table = Table() WORKER_IMAGE = os.environ['HAIL_NOTEBOOK2_WORKER_IMAGE'] if 'BATCH_USE_KUBE_CONFIG' in os.environ: kube.config.load_kube_config() else: kube.config.load_incluster_config() k8s = kube.client.CoreV1Api()
from flask import render_template from flask import session from flask import url_for from authlib.flask.client import OAuth from six.moves.urllib.parse import urlencode app = Flask(__name__) oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id='ggwmdOXy58wn56tAoGVWreBQ9uiUdmpO', client_secret='AroCX2kyaIWiHrrUHpXk4u5EhEvu0hj0uSUZHJyUHD6pEfcPSWX-qWjIpAHu9zKB', api_base_url='https://snowy-block-6613.auth0.com', access_token_url='https://snowy-block-6613.auth0.com/oauth/token', authorize_url='https://snowy-block-6613.auth0.com/authorize', client_kwargs={ 'scope': 'openid profile', }, ) # /server.py # Here we're using the /callback route. @app.route('/callback') def callback_handling(): # Handles response from token endpoint auth0.authorize_access_token() resp = auth0.get('userinfo') userinfo = resp.json()
app.debug = True @app.errorhandler(Exception) def handle_auth_error(ex): response = jsonify(message=str(ex)) response.status_code = (ex.code if isinstance(ex, HTTPException) else 500) return response oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id=AUTH0_CLIENT_ID, client_secret=AUTH0_CLIENT_SECRET, api_base_url=AUTH0_BASE_URL, access_token_url=AUTH0_BASE_URL + '/oauth/token', authorize_url=AUTH0_BASE_URL + '/authorize', client_kwargs={ 'scope': 'openid profile email', }, ) def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): if 'profile' not in session: # Redirect to Login page here return redirect('/') return f(*args, **kwargs) return decorated
from sentry_sdk.integrations.flask import FlaskIntegration load_dotenv() sentry_sdk.init(dsn=os.environ["SENTRY_DSN"], integrations=[FlaskIntegration()]) app = Flask(__name__) app.config["SECRET_KEY"] = os.environ["SECRET_KEY"] oauth = OAuth(app) auth0 = oauth.register( "auth0", client_id=os.environ["AUTH0_CLIENT_ID"], client_secret=os.environ["AUTH0_CLIENT_SECRET"], api_base_url="https://codeguild.eu.auth0.com", access_token_url="https://codeguild.eu.auth0.com/oauth/token", authorize_url="https://codeguild.eu.auth0.com/authorize", client_kwargs={"scope": "openid profile"}, ) @app.before_request def before_request(): request.db = psycopg2.connect(dsn=os.environ["DATABASE_URL"]) @app.after_request def after_request(response): request.db.close() return response
# Check for Auth0 client secret if not os.getenv("AUTH0_SECRET"): raise RuntimeError("AUTH0_SECRET is not set.") else: AUTH0_SECRET = os.getenv("AUTH0_SECRET") # Set up Auth0 oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id='xSZQVTDHqPGkg2mpW8UBaVQ8uca3mu0V', client_secret=AUTH0_SECRET, api_base_url='https://bbhart1.auth0.com', access_token_url='https://bbhart1.auth0.com/oauth/token', authorize_url='https://bbhart1.auth0.com/authorize', client_kwargs={ 'scope': 'openid profile', }, ) # Check for environment variable if not os.getenv("DATABASE_URL"): raise RuntimeError("DATABASE_URL is not set") # Configure session to use filesystem app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app)
return token def fetch_flickr_token(): token = repository.get_token_by_id(session.get("current_user", "")) return token oauth.register( name='flickr', client_id=app.config['FLICKR_CLIENT_ID'], client_secret=app.config['FLICKR_CLIENT_SECRET'], request_token_url=app.config['FLICKR_REQUEST_TOKEN_URL'], request_token_params=app.config['FLICKR_REQUEST_TOKEN_PARAMS'], access_token_url=app.config['FLICKR_ACCESS_TOKEN_URL'], access_token_params=app.config['FLICKR_ACCESS_TOKEN_PARAMS'], authorize_url=app.config['FLICKR_AUTHORIZE_URL'], api_base_url=app.config['FLICKR_API_BASE_URL'], client_kwargs=None, save_request_token=save_request_token, fetch_request_token=fetch_request_token, fetch_token=fetch_flickr_token, ) @app.route("/") def hello(): similar_words("church") return "A"
def create_app(app_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__, static_url_path='/static', static_folder='./static', instance_relative_config=True) FLASK_SECRET_KEY = env.get('FLASK_SECRET_KEY') if not FLASK_SECRET_KEY: FLASK_SECRET_KEY = "secretdev" AUTH0_CALLBACK_URL = env.get(constants.AUTH0_CALLBACK_URL) AUTH0_CLIENT_ID = env.get(constants.AUTH0_CLIENT_ID) AUTH0_CLIENT_SECRET = env.get(constants.AUTH0_CLIENT_SECRET) AUTH0_DOMAIN = env.get(constants.AUTH0_DOMAIN) AUTH0_BASE_URL = 'https://' + AUTH0_DOMAIN AUTH0_AUDIENCE = env.get(constants.AUTH0_AUDIENCE) if AUTH0_AUDIENCE is '': AUTH0_AUDIENCE = AUTH0_BASE_URL + '/userinfo' app.config.from_mapping( # a default secret that should be overridden by instance config SECRET_KEY=FLASK_SECRET_KEY, ) if app_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.update(app_config) oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id=AUTH0_CLIENT_ID, client_secret=AUTH0_CLIENT_SECRET, api_base_url=AUTH0_BASE_URL, access_token_url=AUTH0_BASE_URL + '/oauth/token', authorize_url=AUTH0_BASE_URL + '/authorize', client_kwargs={ 'scope': 'openid profile', }, ) @app.route('/status') def status(): message = { 'apiVersion': API_VERSION, 'status_code': 200, 'message': 'OK' } return jsonify(message) @app.route('/callback') def callback_handling(): auth0.authorize_access_token() resp = auth0.get('userinfo') userinfo = resp.json() session[constants.JWT_PAYLOAD] = userinfo session[constants.PROFILE_KEY] = { 'user_id': userinfo['sub'], 'name': userinfo['name'], 'picture': userinfo['picture'] } return redirect('/order') @app.route('/favicon.ico') def favicon(): print("favicon") return send_from_directory(path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon') @app.route('/login') def login(): return auth0.authorize_redirect(redirect_uri=AUTH0_CALLBACK_URL, audience=AUTH0_AUDIENCE) @app.route('/logout') def logout(): session.clear() params = { 'returnTo': url_for('home', _external=True), 'client_id': AUTH0_CLIENT_ID } return redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params)) @app.route('/') @app.route('/home') def home(): if session and session[constants.PROFILE_KEY]: user_info_json = session[constants.JWT_PAYLOAD] user_id_string = user_info_json.get('sub', '0|0') user_id = user_id_string.split('|')[1] return render_template('home.html', userinfo=session[constants.PROFILE_KEY], userid=user_id) else: return render_template('home.html') @app.route('/order') @requires_auth def render_order_page(): user_info_json = session[constants.JWT_PAYLOAD] user_id_string = user_info_json.get('sub', '0|0') user_id = user_id_string.split('|')[1] return render_template('order.html', userinfo=session[constants.PROFILE_KEY], userid=user_id) @app.errorhandler(404) def page_not_found(e): """Send message to the user with notFound 404 status.""" return jsonify_error("Page Not Found. Refer to the API documentation.", 404) @app.errorhandler(Exception) def error_handler(ex): print(ex) status_code = (ex.code if isinstance(ex, HTTPException) else 500) message = { 'apiVersion': API_VERSION, 'status_code': status_code, 'message': str(ex) } response = jsonify(message) response.status_code = status_code return response # register the database commands from bookstore import bookstore_db bookstore_db.init_app(app) # apply the blueprints to the app from bookstore import bookstore_api app.register_blueprint(bookstore_api.bp) return app
SESSION_TIME = 180 INVALIDATE = -1 SESSION_ID = "session_id" db.set("users:" + "test", "test") db.set("users:" + "ivan", "ivan") db.set("users:" + "login", "password") oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id='zKR5GaNW9dAWqpUxUUXj7ZCN4gAtqPkr', client_secret= 'LsUabfN3AUVH2-1ytoDFya5dIlYVf5btKrUcmUiOxaNrw-O6RBkPW-oiWQ4nofpP', api_base_url='https://dev--q5a6esf.auth0.com', access_token_url='https://dev--q5a6esf.auth0.com/oauth/token', authorize_url='https://dev--q5a6esf.auth0.com/authorize', client_kwargs={ 'scope': 'openid profile email', }, ) @app.route('/') def index(): return render_template('login.html', WEB=WEB) @app.route('/auth', methods=['POST']) def auth(): response = make_response('', 303)
userprofile.picture = filename session.add(userprofile) session.commit() return redirect(url_for('profile')) else: return render_template("form.html") oauth = OAuth(app) auth0 = oauth.register( 'auth0', client_id='eMgwZqvguQVh0lKHfSdqbzA6RH0lVNp2', client_secret= 'xMP9FsIQCy5t2lqoCDgUMDJ4g2iVezRQTkYNlxg5HxqL8bzaQ_sigKq2ubs_Dwri', api_base_url='https://directme.auth0.com', access_token_url='https://directme.auth0.com/oauth/token', authorize_url='https://directme.auth0.com/authorize', client_kwargs={ 'scope': 'openid profile email', }, ) @app.route('/callback') def callback_handling(): # Handles response from token endpoint auth0.authorize_access_token() resp = auth0.get('userinfo') userinfo = resp.json() # Store the user information in flask session.
app.config.update( SECRET_KEY = SECRET_KEY, SESSION_COOKIE_SAMESITE = 'Lax', SESSION_COOKIE_HTTPONLY = True, SESSION_COOKIE_SECURE = USE_SECURE_COOKIE ) AUTH0_CLIENT_ID = 'Ck5wxfo1BfBTVbusBeeBOXHp3a7Z6fvZ' AUTH0_BASE_URL = 'https://hail.auth0.com' auth0 = oauth.register( 'auth0', client_id = AUTH0_CLIENT_ID, client_secret = read_string('/notebook-secrets/auth0-client-secret'), api_base_url = AUTH0_BASE_URL, access_token_url = f'{AUTH0_BASE_URL}/oauth/token', authorize_url = f'{AUTH0_BASE_URL}/authorize', client_kwargs = { 'scope': 'openid email profile', }, ) user_table = Table() if 'BATCH_USE_KUBE_CONFIG' in os.environ: kube.config.load_kube_config() else: kube.config.load_incluster_config() k8s = kube.client.CoreV1Api() log.info(f'KUBERNETES_TIMEOUT_IN_SECONDS {KUBERNETES_TIMEOUT_IN_SECONDS}')