示例#1
0
    def test_access_token_with_fetch_token(self):
        app = Flask(__name__)
        app.secret_key = '!'
        oauth = OAuth()

        token = get_bearer_token()
        oauth.init_app(app, fetch_token=lambda name: 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',
                                authorize_url='https://i.b/authorize')

        def fake_send(sess, req, **kwargs):
            auth = req.headers['Authorization']
            self.assertEqual(auth, 'Bearer {}'.format(token['access_token']))
            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')
                self.assertEqual(resp.text, 'hi')

                # trigger ctx.authlib_client_oauth_token
                resp = client.get('/api/user')
                self.assertEqual(resp.text, 'hi')
示例#2
0
    def test_init_app_params(self):
        app = Flask(__name__)
        oauth = OAuth()
        oauth.init_app(app, SimpleCache())
        self.assertIsNotNone(oauth.cache)
        self.assertIsNone(oauth.update_token)

        oauth.init_app(app, update_token=lambda o: o)
        self.assertIsNotNone(oauth.update_token)
示例#3
0
def get_oauth2_client(token):
    oauth2_client = OAuth()

    def fetch_token(name):
        return token

    oauth2_client.init_app(current_app, fetch_token=fetch_token)
    oauth2_client.register('principal')

    return oauth2_client
 def test_init_app_later(self):
     app = Flask(__name__)
     app.config.update({
         'DEV_CLIENT_KEY': 'dev',
         'DEV_CLIENT_SECRET': 'dev',
     })
     oauth = OAuth()
     remote = oauth.register('dev')
     self.assertRaises(RuntimeError, lambda: oauth.dev.client_key)
     oauth.init_app(app)
     self.assertEqual(oauth.dev.client_key, 'dev')
     self.assertEqual(remote.client_key, 'dev')
示例#5
0
    def test_init_app_later(self):
        app = Flask(__name__)
        app.config.update({
            'DEV_CLIENT_ID': 'dev',
            'DEV_CLIENT_SECRET': 'dev',
        })
        oauth = OAuth()
        remote = oauth.register('dev')
        self.assertRaises(RuntimeError, lambda: oauth.dev.client_id)
        oauth.init_app(app)
        self.assertEqual(oauth.dev.client_id, 'dev')
        self.assertEqual(remote.client_id, 'dev')

        self.assertIsNone(oauth.cache)
        self.assertIsNone(oauth.fetch_token)
        self.assertIsNone(oauth.update_token)
示例#6
0
class Federation:
    def __init__(self):
        self.clients = set()
        self._authlib_clients = OAuth()

    def register(self, client_name, **kwargs):
        self.clients.add(client_name)
        self._authlib_clients.register(client_name, **kwargs)

    def get(self, client_name):
        if client_name in self.clients:
            return self._authlib_clients.create_client(client_name)
        return None

    def init_app(self, app):
        self.register('solidsea',
                      client_cls=OIDCClient,
                      discovery_url=app.config['SOLIDSEA_DISCOVERY_URL'])
        self._authlib_clients.init_app(app)
示例#7
0
class Federation:
    def __init__(self):
        self.clients = []
        self._authlib_clients = OAuth()

    def register(self, client_name, **kwargs):
        self.clients.append(client_name)
        self._authlib_clients.register(client_name, **kwargs)

    def get(self, client_name):
        if client_name in self.clients:
            return self._authlib_clients.create_client(client_name)
        return None

    def init_app(self, app):
        for client_name in app.config['FEDERATION']:
            log.info('Registering client "{}"'.format(client_name))
            module_name = app.config.get('{}_CLIENT_MODULE'.format(
                client_name.upper()))
            self.register(client_name, client_cls=get_client_cls(module_name))
        self._authlib_clients.init_app(app)
示例#8
0
    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')
示例#9
0
def init_app(app):
    global oauth_registry
    # Reinitialize the Oauth registry.
    # In tests for instance, the app module is imported once, thus the registry
    # kept its _clients and _registry values.
    oauth_registry = OAuth()
    oauth_registry.init_app(app)
    if settings.MOCK_OAUTH:
        _logger.info("MOCK_OAUTH set, using Mock oauth client.")
        oauth_registry.register(settings.OAUTH_CLIENT_NAME, client_cls=MockClient)
    else:
        if not settings.OAUTH_JWKS_URL:
            raise Exception("Please set OAUTH_JWKS_URL.")
        _logger.info("Registering Auth0 oauth client")
        oauth_registry.register(
            settings.OAUTH_CLIENT_NAME,
            client_id=settings.OAUTH_CLIENT_ID,
            client_secret=settings.OAUTH_CLIENT_SECRET,
            api_base_url=settings.OAUTH_BASE_URL,
            access_token_url=settings.OAUTH_BASE_URL + "/oauth/token",
            authorize_url=settings.OAUTH_BASE_URL + "/authorize",
            client_kwargs={"scope": "openid profile"},
            client_cls=Auth0Client,
        )
示例#10
0
    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 https://www.googleapis.com/auth/userinfo.profile',
        'token_endpoint_auth_method': 'client_secret_basic',
        'token_placement': 'header',
        'prompt': 'consent'
    })

oauth.init_app(app)

# SuperAdmins
super_admins = {'ahmedramzy160', 'josh777'}

# Flask_Assets
assets = Environment(app)

js = Bundle('js/vendor/brainTree_1.14.1.js',
            'js/vendor/jquery_3.2.1.js',
            'js/vendor/popper_1.11.0.js',
            'js/vendor/bootstrap_4.1.1.js',
            'js/vendor/following_counter.js',
            filters='jsmin',
            output='gen/packed.%(version)s.js')
示例#11
0
def init_webapp(config, test=False):
    """Initialize the web application.

    Initializes and configures the Flask web application. Call this method to
    make the web application and respective database engine usable.

    If initialized with `test=True` the application will use an in-memory
    SQLite database, and should be used for unit testing, but not much else.

    """

    # Make app work with proxies (like nginx) that set proxy headers.
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # logging.getLogger('flask_cors').level = logging.DEBUG

    # Note, this url namespace also exists for the Flask-Restless extension and
    # is where CRUD interfaces live, so be careful not to collide with model
    # names here. We could change this, but it's nice to have API live in the
    # same url namespace.
    app.register_blueprint(api, url_prefix='/api')

    # Initialize Flask configuration
    if test:
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
    else:
        app.config['SQLALCHEMY_DATABASE_URI'] = config['webapp'][
            'database_uri']

    # FIXME: Port these over to configobj.
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'abc123')
    app.config['SECURITY_TOKEN_MAX_AGE'] = 60
    app.config['SECURITY_TOKEN_AUTHENTICATION_HEADER'] = 'Auth-Token'
    app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
    app.config['SECURITY_PASSWORD_SALT'] = os.environ.get('SALT', 'salt123')
    app.config['SECURITY_REGISTERABLE'] = True
    app.config['SECURITY_CONFIRMABLE'] = False
    app.config['SECURITY_SEND_REGISTER_EMAIL'] = False

    # This thing is a supreme PIA with API, and because we're using token based
    # authentication.
    app.config['WTF_CSRF_ENABLED'] = False

    # Initialize Flask-CORS
    CORS(app, supports_credentials=True)
    # CORS(app, supports_credentials=True, resources={r"/*": {"origins": "*"}})

    # Initialize Flask-Bootstrap
    Bootstrap(app)

    # Initialize Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    Security(app, user_datastore)

    app.config['GOOGLE_CLIENT_ID'] = os.environ.get('GOOGLE_CLIENT_ID',
                                                    'abc123')
    app.config['GOOGLE_CLIENT_SECRET'] = os.environ.get(
        'GOOGLE_CLIENT_SECRET', 'password')
    app.config[
        'GOOGLE_REFRESH_TOKEN_URL'] = 'https://www.googleapis.com/oauth2/v4/token'
    app.config['GOOGLE_CLIENT_KWARGS'] = dict(scope=' '.join([
        'openid',
        'https://www.googleapis.com/auth/userinfo.profile',
        'https://www.googleapis.com/auth/calendar.readonly',
    ]))

    # Initialize Authlib.
    oauth = OAuth()
    oauth.init_app(app,
                   fetch_token=authlib_fetch_token,
                   update_token=authlib_update_token)
    google_blueprint = create_flask_blueprint(Google, oauth,
                                              authlib_handle_authorize)
    app.register_blueprint(google_blueprint, url_prefix='/google')
    # Save the oauth object in the app so handlers can use it to build clients.
    app.oauth = oauth

    # Initialize Flask-SQLAlchemy
    db.app = app
    db.init_app(app)
    # NOTE: You don't want to use this if you're using alembic, since alembic
    # is now in charge of creating/upgrading/downgrading your database. If you
    # choose to not use alembic, you can add this line here.
    # db.create_all()

    # Initialize Flask-Restless
    manager = APIManager(
        app,
        flask_sqlalchemy_db=db,
        preprocessors=dict(GET_MANY=[restless_api_auth_func]),
    )
    # manager.create_api(TableName methods=['GET', 'POST', 'OPTIONS'])
    return app