Python flask_oauthlib.client.OAuth() Examples

The following are 8 code examples of flask_oauthlib.client.OAuth(). 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 flask_oauthlib.client , or try the search function .
Example #1
Source File: auth.py    From gae-angular-material-starter with MIT License 6 votes vote down vote up
def signin_oauth(oauth_app, scheme=None):
    """Attemps to sign in via given oauth_app. If successfull it will redirect to
    appropriate url. E.g. if signing via github it will call github_authorized
    as callback function

    Args:
        oauth_app (OAuth): Flask Oauth app
        scheme (string): http or https to use in callback url
    """
    if scheme is None:
        scheme = 'https' if config.PRODUCTION else 'http'
    try:
        flask.session.pop('oauth_token', None)
        save_request_params()
        return oauth_app.authorize(callback=flask.url_for(
            '%s_authorized' % oauth_app.name, _external=True, _scheme=scheme
        ))
    except oauth.OAuthException:
        flask.flash('Something went wrong with sign in. Please try again.')
        return flask.redirect(flask.url_for('index')) 
Example #2
Source File: auth.py    From ok with Apache License 2.0 6 votes vote down vote up
def record_params(setup_state):
    """ Load used app configs into local config on registration from
    server/__init__.py """
    global provider_name
    global provider_auth
    global oauth
    oauth = OAuth()
    app = setup_state.app
    provider_name = app.config.get('OAUTH_PROVIDER', GOOGLE)
    provider_auth = oauth.remote_app(
        provider_name, 
        app_key=provider_name
    )
    
    oauth.init_app(app)
    #instead of decorator set the fn pointer to the func here:
    provider_auth._tokengetter = provider_token 
Example #3
Source File: oauth.py    From dino with Apache License 2.0 5 votes vote down vote up
def __init__(self, env: GNEnvironment):
        if env.config.get(ConfigKeys.INSECURE, domain=ConfigKeys.WEB, default=False):
            os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true'

        self.oauth_base = env.config.get(ConfigKeys.OAUTH_BASE, domain=ConfigKeys.WEB)
        self.oauth_path = env.config.get(ConfigKeys.OAUTH_PATH, domain=ConfigKeys.WEB)
        self.service_id = env.config.get(ConfigKeys.SERVICE_ID, domain=ConfigKeys.WEB)
        self.service_secret = env.config.get(ConfigKeys.SERVICE_SECRET, domain=ConfigKeys.WEB)
        self.authorize_url = env.config.get(ConfigKeys.AUTH_URL, domain=ConfigKeys.WEB)
        self.token_url = env.config.get(ConfigKeys.TOKEN_URL, domain=ConfigKeys.WEB)
        self.callback_url = env.config.get(ConfigKeys.CALLBACK_URL, domain=ConfigKeys.WEB)
        self.unauthorized_url = env.config.get(ConfigKeys.UNAUTH_URL, domain=ConfigKeys.WEB)
        self.root_url = env.config.get(ConfigKeys.ROOT_URL, domain=ConfigKeys.WEB)

        self.check_token_url = '{}/{}'.format(self.oauth_base.rstrip('/'), self.oauth_path.lstrip('/'))

        from dino.web import app
        self.oauth = OAuth(app)
        self.logger = logging.getLogger(__name__)
        self.env = env

        self.auth = self.oauth.remote_app(
            self.service_id,
            consumer_key=self.service_id,
            consumer_secret=self.service_secret,
            base_url=self.oauth_base,
            request_token_params={},
            request_token_url=None,
            access_token_method='POST',
            access_token_url=self.token_url,
            authorize_url=self.authorize_url
        )

        @self.auth.tokengetter
        def get_sso_token():
            return request.cookies.get('token') 
Example #4
Source File: auth.py    From gae-angular-material-starter with MIT License 5 votes vote down vote up
def create_oauth_app(service_config, name):
    """Creates oauth app for particaular web service

    Args:
        service_config (dict): config required for creating oauth app
        name (string): name of the service, e.g github
    """
    upper_name = name.upper()
    app.config[upper_name] = service_config
    service_oauth = oauth.OAuth()
    service_app = service_oauth.remote_app(name, app_key=upper_name)
    service_oauth.init_app(app)
    return service_app 
Example #5
Source File: auth.py    From ok with Apache License 2.0 5 votes vote down vote up
def check_oauth_token(scopes=None):
    """ Check the request for OAuth creds.
    Requires: Flask Request and access_token in request.args
    Return Token or None
    """
    if scopes is None:
        scopes = []
    # Check with local OAuth Provider for user
    valid, req = oauth_provider.verify_request(scopes)
    if valid:
        return req 
Example #6
Source File: auth.py    From ok with Apache License 2.0 5 votes vote down vote up
def use_testing_login():
    """
    Return True if we use the unsecure testing login instead of service provider OAuth.
    Requires TESTING_LOGIN = True in the config and the environment is not prod.
    """
    return (current_app.config.get('TESTING_LOGIN', False) and
            current_app.config.get('ENV') != 'prod') 
Example #7
Source File: test_oauth.py    From ok with Apache License 2.0 5 votes vote down vote up
def test_client_form_admin(self):
        self._setup_clients()
        self.login(self.admin.email)

        redirect_uris = [
            'http://myapp.com/authorize',
            'https://myapp.com/authorize',
        ]
        default_scopes = ['email', 'all']
        data = {
            'name': 'My App',
            'description': 'A web app that does stuff',
            'client_id': 'my-app',
            'client_secret': 'my-secret-key',
            'is_confidential': 'true',
            'redirect_uris': ', '.join(redirect_uris),
            'default_scopes': ', '.join(default_scopes),
        }

        self.assert_200(self.client.post('/admin/clients/',
            data=data, follow_redirects=True))

        client = Client.query.filter_by(client_id="my-app").one()
        self.assertEqual(client.name, data['name'])
        self.assertTrue(client.active) # Admin created OAuth clients start active
        self.assertEqual(client.user_id, self.admin.id)
        self.assertEqual(client.description, data['description'])
        self.assertEqual(client.client_id, data['client_id'])
        self.assertEqual(client.client_secret, data['client_secret'])
        self.assertTrue(client.is_confidential)
        self.assertEqual(client.redirect_uris, redirect_uris)
        self.assertEqual(client.default_scopes, default_scopes)

        # Ensure admins can see additional form element
        response = self.client.get('admin/clients/{}'.format(client.client_id))
        self.assertTrue(b'Active' in response.data) # Should see active checkbox
        self.assertTrue(b'Default Scope' in response.data) # Should see scopes text input 
Example #8
Source File: test_oauth.py    From ok with Apache License 2.0 4 votes vote down vote up
def _setup_clients(self, scope='email'):
        self.setup_course()

        self.oauth_client = Client(
            name='Testing Client', client_id='normal', client_secret='normal',
            redirect_uris=['http://127.0.0.1:8000/authorized'],
            is_confidential=False,
            active=True,
            description='Sample App for testing OAuth',
            default_scopes=scope
        )
        db.session.add(self.oauth_client)
        db.session.commit()

        self.temp_grant = Grant(
            user_id=self.user1.id, client_id='normal',
            code='12345', scopes=['email'],
            expires=dt.datetime.utcnow() + dt.timedelta(seconds=100)
        )
        db.session.add(self.temp_grant)

        self.expired_token = Token(
            user_id=self.user1.id, client_id='normal',
            scopes=[scope],
            access_token='expired', expires=dt.datetime.utcnow() - dt.timedelta(seconds=1)
        )
        db.session.add(self.expired_token)

        self.valid_token = Token(
            user_id=self.user1.id, client_id='normal',
            scopes=[scope],
            access_token='soo_valid', expires=dt.datetime.utcnow() + dt.timedelta(seconds=3600)
        )
        db.session.add(self.valid_token)

        self.valid_token_bad_scope = Token(
            user_id=self.user1.id, client_id='normal',
            scopes=['invalid'],
            access_token='soo_valid12', expires=dt.datetime.utcnow() + dt.timedelta(seconds=3600)
        )
        db.session.add(self.valid_token_bad_scope)

        self.valid_token_all_scope = Token(
            user_id=self.user1.id, client_id='normal',
            scopes=['all'],
            access_token='soo_valid322', expires=dt.datetime.utcnow() + dt.timedelta(seconds=3600)
        )
        db.session.add(self.valid_token_all_scope)
        db.session.commit()