示例#1
0
    def test_lazy_load(self):
        oauth = OAuth()
        twitter = oauth.remote_app(
            'twitter',
            base_url='https://api.twitter.com/1/',
            app_key='twitter'
        )
        assert twitter.base_url == 'https://api.twitter.com/1/'

        app = Flask(__name__)
        app.config.update({
            'twitter': dict(
                consumer_key='twitter key',
                consumer_secret='twitter secret',
                request_token_url='request url',
                access_token_url='token url',
                authorize_url='auth url',
            )
        })
        oauth.init_app(app)
        assert twitter.consumer_key == 'twitter key'
        assert twitter.consumer_secret == 'twitter secret'
        assert twitter.request_token_url == 'request url'
        assert twitter.access_token_url == 'token url'
        assert twitter.authorize_url == 'auth url'
        assert twitter.content_type is None
示例#2
0
def get_collection_tweets():

    tweets = []
    oauth = OAuth(current_app)
    twitter = oauth.remote_app(
        'twitter',
        base_url='https://api.twitter.com/1.1/',
        request_token_url='https://api.twitter.com/oauth/request_token',
        access_token_url='https://api.twitter.com/oauth/access_token',
        authorize_url='https://api.twitter.com/oauth/authenticate',
        consumer_key=current_app.config['TWITTER_CONSUMER_KEY'],
        consumer_secret=current_app.config['TWITTER_CONSUMER_SECRET']
    )

    @twitter.tokengetter
    def get_twitter_token():
        return (
            current_app.config['TWITTER_ACCESS_TOKEN'],
            current_app.config['TWITTER_ACCESS_TOKEN_SECRET']
        )

    response = twitter.request('statuses/user_timeline.json', data={
        'screen_name': current_app.config['TWITTER_SCREEN_NAME'],
        'count': current_app.config['TWITTER_LIMIT'],
    })

    if response.status == 200:
        tweets = response.data

    return tweets
示例#3
0
def enable_github_oauth(GITHUB_ENABLE):
    if not GITHUB_ENABLE:
        return None, None
    from flask_oauthlib.client import OAuth
    oauth = OAuth(app)
    github = oauth.remote_app(
        'github',
        consumer_key=app.config['GITHUB_OAUTH_KEY'],
        consumer_secret=app.config['GITHUB_OAUTH_SECRET'],
        request_token_params={'scope': app.config['GITHUB_OAUTH_SCOPE']},
        base_url=app.config['GITHUB_OAUTH_URL'],
        request_token_url=None,
        access_token_method='POST',
        access_token_url=app.config['GITHUB_OAUTH_TOKEN'],
        authorize_url=app.config['GITHUB_OAUTH_AUTHORIZE']
    )

    @app.route('/user/authorized')
    def authorized():
        session['github_oauthredir'] = url_for('.authorized', _external=True)
        resp = github.authorized_response()
        if resp is None:
            return 'Access denied: reason=%s error=%s' % (
                request.args['error'],
                request.args['error_description']
            )
        session['github_token'] = (resp['access_token'], '')
        return redirect(url_for('.login'))

    @github.tokengetter
    def get_github_oauth_token():
        return session.get('github_token')

    return oauth, github
示例#4
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('over_achiever.config')
    db = SQLAlchemy(app, metadata=models.metadata)
    db.create_all()
    resources.db = app.db = db

    oauth = OAuth(app)
    github = oauth.remote_app(
        'github',
        consumer_key='507e57ab372adeb8051b',
        consumer_secret='08a7dbaa06ac16daab00fac53724ee742c8081c5',
        request_token_params={'scope': 'user:email'},
        base_url='https://api.github.com/',
        request_token_url=None,
        access_token_method='POST',
        access_token_url='https://github.com/login/oauth/access_token',
        authorize_url='https://github.com/login/oauth/authorize'
    )

    # set the token getter for the auth client
    github._tokengetter = lambda: session.get('github_token')
    resources.github = app.github = github

    api = Api(app)
    resource_map = (
        (User, '/v1.0/users'),
        (Goal, '/v1.0/goals'),
    )

    for resource, route in resource_map:
        api.add_resource(resource, route)

    return app
def make_twitter(flask_app):
    oauth = OAuth(flask_app)
    return oauth.remote_app('twitter',
            base_url='https://api.twitter.com/1.1/',
            request_token_url='https://api.twitter.com/oauth/request_token',
            access_token_url='https://api.twitter.com/oauth/access_token',
            authorize_url='https://api.twitter.com/oauth/authenticate',
            consumer_key=os.getenv('TWITTER_CONSUMER_KEY'),
            consumer_secret=os.getenv('TWITTER_CONSUMER_SECRET'))
def make_lepture(app, ck, cs):
    oauth = OAuth(app)
    return oauth.remote_app('lepture',
            consumer_key=ck,
            consumer_secret=cs,
            request_token_params={
                'realm': 'email'},
            base_url='http://127.0.0.1:5000/api/',
            request_token_url='http://127.0.0.1:5000/oauth/request_token',
            access_token_method='GET',
            access_token_url='http://127.0.0.1:5000/oauth/access_token',
            authorize_url='http://127.0.0.1:5000/oauth/authorize')
示例#7
0
 def __init__(self):
     super().__init__('twitter')
     oauth = OAuth()
     self.service = oauth.remote_app(
         'twitter',
         base_url='https://api.twitter.com/1/',
         request_token_url='https://api.twitter.com/oauth/request_token',
         access_token_url='https://api.twitter.com/oauth/access_token',
         authorize_url='https://api.twitter.com/oauth/authenticate',
         consumer_key=app.config['TWITTER_CUSTOMER_KEY'],
         consumer_secret=app.config['TWITTER_CUSTOMER_SECRET']
     )
     self.service.tokengetter = TwitterSignIn.get_token
示例#8
0
def create_client(app):
    oauth = OAuth(app)

    dev = oauth.remote_app(
        'dev',
        consumer_key='dev',
        consumer_secret='dev',
        request_token_params={'scope': 'email'},
        base_url='http://127.0.0.1:5000/api/',
        request_token_url=None,
        access_token_method='GET',
        access_token_url='http://127.0.0.1:5000/oauth/access_token',
        authorize_url='http://127.0.0.1:5000/oauth/authorize'
    )

    @app.route('/')
    def index():
        if 'dev_token' in session:
            ret = dev.get('email')
            return jsonify(ret.data)
        return redirect(url_for('login'))

    @app.route('/login')
    def login():
        return dev.authorize(callback=url_for('authorized', _external=True))

    @app.route('/logout')
    def logout():
        session.pop('dev_token', None)
        return redirect(url_for('index'))

    @app.route('/authorized')
    @dev.authorized_handler
    def authorized(resp):
        if resp is None:
            return 'Access denied: error=%s' % (
                request.args['error']
            )
        session['dev_token'] = (resp['access_token'], '')
        return jsonify(resp)

    @app.route('/address')
    def address():
        ret = dev.get('address')
        return ret.raw_data

    @dev.tokengetter
    def get_oauth_token():
        return session.get('dev_token')

    return app
def install_github_oauth(app):
    oauth = OAuth(app)
    github_auth = oauth.remote_app(
        'github',
        consumer_key=app.config['GITHUB_CLIENT_ID'],
        consumer_secret=app.config['GITHUB_CLIENT_SECRET'],
        request_token_params={'scope': 'repo,user'},
        base_url='https://api.github.com/',
        request_token_url=None,
        access_token_method='POST',
        access_token_url='https://github.com/login/oauth/access_token',
        authorize_url='https://github.com/login/oauth/authorize'
    )

    @app.route('/login')
    def login():
        return github_auth.authorize(callback=url_for('authorized', _external=True, next=request.args.get('next') or request.referrer or None))


    @app.route('/logout')
    def logout():
        session.pop('token', None)
        return redirect(url_for('index'))


    @app.route('/oauth_callback')
    @github_auth.authorized_handler
    def authorized(resp):
        next_url = request.args.get('next') or url_for('index')
        if resp is None:
            return 'Access denied: reason=%s error=%s' % (
                request.args['error_reason'],
                request.args['error_description']
            )
        session['token'] = resp['access_token']
        user_info = github.get_current_user_info(session['token'])
        if not user_info:
            return "Unable to get user info."
        session['login'] = user_info['login']
        return redirect(next_url)


    @github_auth.tokengetter
    def get_github_oauth_token():
        token = session.get('token')
        if token:
            return (token, '')
        else:
            return token
示例#10
0
def create_oauth(app):
    oauth = OAuth(app)

    remote = oauth.remote_app(
        'dev',
        consumer_key='dev',
        consumer_secret='dev',
        request_token_params={'realm': 'email'},
        base_url='http://127.0.0.1:5000/api/',
        request_token_url='http://127.0.0.1:5000/oauth/request_token',
        access_token_method='GET',
        access_token_url='http://127.0.0.1:5000/oauth/access_token',
        authorize_url='http://127.0.0.1:5000/oauth/authorize'
    )
    return remote
示例#11
0
    def create_client(self, app):
        oauth = OAuth(app)

        remote = oauth.remote_app(
            'dev',
            consumer_key='noclient',
            consumer_secret='dev',
            request_token_params={'realm': 'email'},
            base_url='http://localhost/api/',
            request_token_url='http://localhost/oauth/request_token',
            access_token_method='GET',
            access_token_url='http://localhost/oauth/access_token',
            authorize_url='http://localhost/oauth/authorize'
        )
        return create_client(app, remote)
    def init_app(self, flask_app):
        self.flask_app = flask_app

        self.login_manager.init_app(self.flask_app)

        self.ghe_oauth = OAuth(self.flask_app).remote_app(
            'ghe',
            consumer_key=get_config_param('client_id'),
            consumer_secret=get_config_param('client_secret'),
            # need read:org to get team member list
            request_token_params={'scope': 'user:email,read:org'},
            base_url=self.ghe_host,
            request_token_url=None,
            access_token_method='POST',
            access_token_url=''.join(['https://',
                                      self.ghe_host,
                                      '/login/oauth/access_token']),
            authorize_url=''.join(['https://',
                                   self.ghe_host,
                                   '/login/oauth/authorize']))

        self.login_manager.user_loader(self.load_user)

        self.flask_app.add_url_rule(get_config_param('oauth_callback_route'),
                                    'ghe_oauth_callback',
                                    self.oauth_callback)
示例#13
0
def test_app():
    app = Flask(__name__)
    oauth = OAuth(app)
    remote = oauth.remote_app(
        'dev',
        consumer_key='dev',
        consumer_secret='dev',
        request_token_params={'scope': 'email'},
        base_url='http://127.0.0.1:5000/api/',
        request_token_url=None,
        access_token_method='POST',
        access_token_url='http://127.0.0.1:5000/oauth/token',
        authorize_url='http://127.0.0.1:5000/oauth/authorize'
    )
    client = app.extensions['oauthlib.client']
    assert client.dev.name == 'dev'
示例#14
0
    def __init__(self, consumer_key, consumer_secret):
        oauth = OAuth()
        self.api = oauth.remote_app('500px-fav-downloader',
                                    base_url='https://api.500px.com/v1/',
                                    request_token_url='https://api.500px.com/v1/oauth/request_token',
                                    access_token_url='https://api.500px.com/v1/oauth/access_token',
                                    authorize_url='https://api.500px.com/v1/oauth/authorize',
                                    consumer_key=consumer_key,
                                    consumer_secret=consumer_secret
                                    )

        self.oauth_token = None
        self.oauth_token_secret = None

        # Register the function to get the tokens
        self.api.tokengetter(self.get_oauth_token)
示例#15
0
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
示例#16
0
 def __init__(self, client_id, client_secret):
   super(GoogleSignIn, self).__init__(provider_name="google")
   oauth = OAuth()
   self.service = oauth.remote_app(
     'google',
     consumer_key=client_id,
     consumer_secret=client_secret,
     request_token_params={
       'scope': 'email'
     },
     base_url='https://www.googleapis.com/oauth2/v1/',
     request_token_url=None,
     access_token_method='POST',
     access_token_url='https://accounts.google.com/o/oauth2/token',
     authorize_url='https://accounts.google.com/o/oauth2/auth',
   )
   self.service.tokengetter(GoogleSignIn._get_token)
示例#17
0
 def __init__(self):
     super().__init__('google')
     oauth = OAuth()
     self.service = oauth.remote_app(
         'google',
         consumer_key=app.config['GOOGLE_CLIENT_ID'],
         consumer_secret=app.config['GOOGLE_CLIENT_SECRET'],
         request_token_params={
             'scope': 'email'
         },
         base_url='https://www.googleapis.com/oauth2/v1/',
         request_token_url=None,
         access_token_method='POST',
         access_token_url='https://accounts.google.com/o/oauth2/token',
         authorize_url='https://accounts.google.com/o/oauth2/auth',
     )
     self.service.tokengetter(GoogleSignIn.get_token)
示例#18
0
    def test_lazy_load_with_plain_text_config(self):
        oauth = OAuth()
        twitter = oauth.remote_app('twitter', app_key='TWITTER')

        app = Flask(__name__)
        app.config['TWITTER_CONSUMER_KEY'] = 'twitter key'
        app.config['TWITTER_CONSUMER_SECRET'] = 'twitter secret'
        app.config['TWITTER_REQUEST_TOKEN_URL'] = 'request url'
        app.config['TWITTER_ACCESS_TOKEN_URL'] = 'token url'
        app.config['TWITTER_AUTHORIZE_URL'] = 'auth url'

        oauth.init_app(app)

        assert twitter.consumer_key == 'twitter key'
        assert twitter.consumer_secret == 'twitter secret'
        assert twitter.request_token_url == 'request url'
        assert twitter.access_token_url == 'token url'
        assert twitter.authorize_url == 'auth url'
示例#19
0
 def __init__(self,app,oauth_name=None,oauth_key=None,oauth_secret=None,oauth_scope=None,oauth_access_token_url=None,
              oauth_authorize_url=None,oauth_request_token_url=None,oauth_base_api_url=None,oauth_callback_url=None,
              *args,**kwargs):
     super(NemoOauthPlugin, self).__init__(*args,**kwargs)
     oauth = OAuth(app)
     self.authobj = oauth.remote_app(
         oauth_name,
         consumer_key=oauth_key,
         consumer_secret=oauth_secret,
         request_token_params={'scope':oauth_scope},
         base_url=oauth_base_api_url,
         request_token_url=oauth_request_token_url,
         access_token_method='POST',
         access_token_url=oauth_access_token_url,
         authorize_url=oauth_authorize_url
     )
     self.authobj.tokengetter(self.oauth_token)
     self.authcallback = oauth_callback_url
示例#20
0
def get_google( app ):
    oauth = OAuth(app)
    app.logger.debug( app.config.keys() )
    google = oauth.remote_app(
        'google',
        consumer_key=app.config.get('GOOGLE_ID'),
        consumer_secret=app.config.get('GOOGLE_SECRET'),
        request_token_params={
            'scope': ['profile', 'https://www.googleapis.com/auth/userinfo.email'],
            'approval_prompt' : 'force',
            'access_type':'offline'
        },
        base_url='https://www.googleapis.com/oauth2/v1/',
        request_token_url=None,
        access_token_method='POST',
        access_token_url='https://accounts.google.com/o/oauth2/token',
        authorize_url='https://accounts.google.com/o/oauth2/auth',
    )
    return google
示例#21
0
def create_oauth(app):
    oauth = OAuth(app)
    google = oauth.remote_app('google',
        consumer_key=GOOGLE_ID,
        consumer_secret=GOOGLE_SECRET,
        request_token_params={
            'scope': 'https://www.googleapis.com/auth/userinfo.email'
        },
        base_url='https://www.googleapis.com/oauth2/v1/',
        request_token_url=None,
        access_token_method='POST',
        access_token_url='https://accounts.google.com/o/oauth2/token',
        authorize_url='https://accounts.google.com/o/oauth2/auth',
    )

    @google.tokengetter
    def get_google_oauth_token():
        return session.get('google_token')

    return google
示例#22
0
def get_oauth_provider(provider):
    oauth = OAuth(current_app)
    if provider == 'github':
        github = oauth.remote_app(
            'github',
            consumer_key=_cfg('gh-oauth-id'),
            consumer_secret=_cfg('gh-oauth-secret'),
            request_token_params={'scope': 'user:email'},
            base_url='https://api.github.com/',
            request_token_url=None,
            access_token_method='POST',
            access_token_url='https://github.com/login/oauth/access_token',
            authorize_url='https://github.com/login/oauth/authorize'
        )

        @github.tokengetter
        def get_github_oauth_token():
            return session.get('github_token')

        return github

    if provider == 'google':
        google = oauth.remote_app(
            'google',
            consumer_key=_cfg('google-oauth-id'),
            consumer_secret=_cfg('google-oauth-secret'),
            request_token_params={'scope': 'email'},
            base_url='https://www.googleapis.com/oauth2/v1/',
            request_token_url=None,
            access_token_method='POST',
            access_token_url='https://accounts.google.com/o/oauth2/token',
            authorize_url='https://accounts.google.com/o/oauth2/auth',
        )

        @google.tokengetter
        def get_google_oauth_token():
            return session.get('google_token')

        return google

    raise Exception('This OAuth provider was not implemented: ' + provider)
示例#23
0
    def __init__(self):
        self.oauth = OAuth(self.app)

        # Map of remote apps indexed by service ID.
        self.remote = dict()

        # Create remote apps.
        for config_id in self.configs:
            print 'Registered OAuth: {0}'.format(config_id)
            self.app.config[config_id] = self.configs[config_id]
            remote = self.oauth.remote_app(config_id, app_key=config_id)
            self.remote[config_id] = remote
示例#24
0
 def init_app(self, app):  # pragma: no cover
     """Method to init object following factories pattern."""
     from flask import session
     self.app = app
     self.oauth_client = OAuth().remote_app(
         'flickr',
         request_token_url='https://www.flickr.com/services/oauth/request_token',
         access_token_url='https://www.flickr.com/services/oauth/access_token',
         authorize_url='https://www.flickr.com/services/oauth/authorize',
         consumer_key=app.config['FLICKR_API_KEY'],
         consumer_secret=app.config['FLICKR_SHARED_SECRET'],
         access_token_method='GET')
     tokengetter = functools.partial(self.get_token, session)
     self.oauth_client.tokengetter(tokengetter)
示例#25
0
文件: auth.py 项目: eyalr/frippery
def initialize(app):
    app.secret_key = 'development'
    oauth = OAuth(app)

    host_eb_apis = {
        'tourney': oauth.remote_app(
            'eventbrite-tourney',
            consumer_key=settings.tourney_consumer_key,
            consumer_secret=settings.tourney_secret_key,
            request_token_params={
                'state': lambda: security.gen_salt(10)
            },
            base_url='https://www.eventbriteapi.com/v3/',
            request_token_url=None,
            access_token_method='POST',
            access_token_url='https://www.eventbrite.com/oauth/token',
            authorize_url='https://www.eventbrite.com/oauth/authorize',
        ),
        'secret-santa': oauth.remote_app(
            'eventbrite-ss',
            consumer_key=settings.secret_santa_consumer_key,
            consumer_secret=settings.secret_santa_secret_key,
            request_token_params={
                'state': lambda: security.gen_salt(10)
            },
            base_url='https://www.eventbriteapi.com/v3/',
            request_token_url=None,
            access_token_method='POST',
            access_token_url='https://www.eventbrite.com/oauth/token',
            authorize_url='https://www.eventbrite.com/oauth/authorize',
        ),
    }
    for _api in host_eb_apis.values():
        _api.tokengetter(lambda *args: session.get('eventbrite_token'))

    return host_eb_apis
示例#26
0
    def __init__(self, appbuilder):
        super(BaseSecurityManager, self).__init__(appbuilder)
        app = self.appbuilder.get_app
        # Base Security Config
        app.config.setdefault('AUTH_ROLE_ADMIN', 'Admin')
        app.config.setdefault('AUTH_ROLE_PUBLIC', 'Public')
        app.config.setdefault('AUTH_TYPE', AUTH_DB)
        # Self Registration
        app.config.setdefault('AUTH_USER_REGISTRATION', False)
        app.config.setdefault('AUTH_USER_REGISTRATION_ROLE', self.auth_role_public)

        # LDAP Config
        if self.auth_type == AUTH_LDAP:
            if 'AUTH_LDAP_SERVER' not in app.config:
                raise Exception("No AUTH_LDAP_SERVER defined on config with AUTH_LDAP authentication type.")
            app.config.setdefault('AUTH_LDAP_USE_TLS', False)
            app.config.setdefault('AUTH_LDAP_SEARCH', '')
            app.config.setdefault('AUTH_LDAP_BIND_USER', '')
            app.config.setdefault('AUTH_LDAP_APPEND_DOMAIN', '')
            app.config.setdefault('AUTH_LDAP_USERNAME_FORMAT', '')
            app.config.setdefault('AUTH_LDAP_BIND_PASSWORD', '')
            app.config.setdefault('AUTH_LDAP_ALLOW_SELF_SIGNED', False)
            app.config.setdefault('AUTH_LDAP_UID_FIELD', 'uid')
            app.config.setdefault('AUTH_LDAP_FIRSTNAME_FIELD', 'givenName')
            app.config.setdefault('AUTH_LDAP_LASTNAME_FIELD', 'sn')
            app.config.setdefault('AUTH_LDAP_EMAIL_FIELD', 'mail')

        if self.auth_type == AUTH_OID:
            self.oid = OpenID(app)
        if self.auth_type == AUTH_OAUTH:
            from flask_oauthlib.client import OAuth
            self.oauth = OAuth()
            self.oauth_remotes = dict()
            for _provider in self.oauth_providers:
                provider_name = _provider['name']
                log.debug("OAuth providers init {0}".format(provider_name))
                obj_provider = self.oauth.remote_app(provider_name, **_provider['remote_app'])
                obj_provider._tokengetter = self.oauth_tokengetter
                if not self.oauth_user_info:
                    self.oauth_user_info = self.get_oauth_user_info
                # Whitelist only users with matching emails
                if 'whitelist' in _provider:
                    self.oauth_whitelists[provider_name] = _provider['whitelist']
                self.oauth_remotes[provider_name] = obj_provider

        self.lm = LoginManager(app)
        self.lm.login_view = 'login'
        self.lm.user_loader(self.load_user)
    def __init__(self, session):
        """setup the token used for all the api calls and all the urls for the current session

        :param session: session
        """
        def get_gitlab_token():
            """Return session token"""
            return session.get('access_token')

        self.oauth = OAuth()
        self.auth = self.oauth.remote_app(
            'gitlab',
            consumer_key=config.GITLAB_APP_ID,
            consumer_secret=config.GITLAB_APP_SECRET,
            base_url=config.GITLAB_URL,
            access_token_url='{0}/oauth/token'.format(config.GITLAB_URL),
            authorize_url='{0}/oauth/authorize'.format(config.GITLAB_URL),
            content_type='application/json'
        )
        self.auth.tokengetter(get_gitlab_token)
        self._url = '{0}/api/v3'.format(self.auth.base_url)
示例#28
0
    def init_app(self, flask_app):
        self.flask_app = flask_app

        self.login_manager.init_app(self.flask_app)

        self.google_oauth = OAuth(self.flask_app).remote_app(
            'google',
            consumer_key=get_config_param('client_id'),
            consumer_secret=get_config_param('client_secret'),
            request_token_params={'scope': '''https://www.googleapis.com/auth/userinfo.profile
                                        https://www.googleapis.com/auth/userinfo.email'''},
            base_url='https://www.google.com/accounts/',
            request_token_url=None,
            access_token_method='POST',
            access_token_url='https://accounts.google.com/o/oauth2/token',
            authorize_url='https://accounts.google.com/o/oauth2/auth')

        self.login_manager.user_loader(self.load_user)

        self.flask_app.add_url_rule(get_config_param('oauth_callback_route'),
                                    'google_oauth_callback',
                                    self.oauth_callback)
示例#29
0
    "sandbox",  # sandbox or live
    "client_id":
    "AXB5ZNlu09cxhnvYv4uxBhikgPhyzu_XAV1bTYwvzNKUXuNRh9RyVKA89cbCXuzHKIyhDCN5XpEthIZw",
    "client_secret":
    "EF8UMLBnyoKq6U3dPmFy8xaj_XFqeRncS21RnN0V-4k1cB6QFf4cmJ7c6ym79LkLZS2kiBwLk18tBs0D"
})

global_linked = {}
sof_user_id = None
github_uname = None

app = Flask('skilladvisor')
app.debug = True
app.secret_key = 'development'
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
oauth = OAuth(app)


@app.route('/home')
def home():
    return render_template('home.html')


@app.route('/')
@cache.cached(60)
def webprint():
    return render_template('home.html', git_res='', sof_res='', linked_res='')


@app.route('/main')
def main():
示例#30
0
# oauth_server
# CLIENT_ID = 'zkuYDhPdCNFWtDIV0G7sqZF8B11AVadTGzNh6SY7'
# CLIENT_SECRET = 'ZbzRADpSV46ULHduImU9yVmMmnSCVZIHlsgLDlZkgaxr3eApR2'

# api_server_test
CLIENT_ID = '8raj6Vk9H5Q0gQEA3pe7Pq953MVbjKL7pWJ8cUJj'
CLIENT_SECRET = 'klP2FQUKVTvhpZNnXx8VBYTDjphnwAn9Oo9ibzzORAPdzf1HXU'

# configuration
# DEBUG = True
SECRET_KEY = 'secret'

app = Flask(__name__)
app.config.from_object(__name__)
oauth = OAuth(app)

myssu = oauth.remote_app(
    'myssu',
    consumer_key=CLIENT_ID,
    consumer_secret=CLIENT_SECRET,
    request_token_params={'scope': 'email'},
    request_token_url=None,
    base_url='http://127.0.0.1:5000/api/',
    access_token_url='http://127.0.0.1:5000/oauth/token',
    authorize_url='http://127.0.0.1:5000/oauth/authorize',
    # base_url='https://api.yourssu.com/api/',
    # access_token_url='https://api.yourssu.com/oauth/token',
    # authorize_url='https://api.yourssu.com/oauth/authorize'
)
示例#31
0
from flask import render_template
from flask import flash
import pprint
import os

# This code originally from https://github.com/lepture/flask-oauthlib/blob/master/example/github.py
# Edited by P. Conrad for SPIS 2016 to add getting Client Id and Secret from
# environment variables, so that this will work on Heroku.
# Edited by S. Adams for Designing Software for the Web to add comments and remove flash messaging

app = Flask(__name__)

app.debug = True #Change this to False for production

app.secret_key = os.environ['SECRET_KEY'] 
oauth = OAuth(app)

#Sets Up github as oauth provider
github = oauth.remote_app(
    'github',
    consumer_key=os.environ['GITHUB_CLIENT_ID'], 
    consumer_secret=os.environ['GITHUB_CLIENT_SECRET'],
    request_token_params={'scope': 'user:email'}, #request read-only access to the user's email.  For a list of possible scopes, see developer.github.com/apps/building-oauth-apps/scopes-for-oauth-apps
    base_url='https://api.github.com/',
    request_token_url=None,
    access_token_method='POST',
    access_token_url='https://github.com/login/oauth/access_token',  
    authorize_url='https://github.com/login/oauth/authorize' #URL for github's OAuth login
)

示例#32
0
from flask_oauthlib.client import OAuth
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy


from backend.config import EnvironmentConfig


def format_url(endpoint):
    parts = "/".join([i for i in endpoint.split("/") if i])
    return "/api/{}/{}/".format(EnvironmentConfig.API_VERSION, parts)


db = SQLAlchemy()
migrate = Migrate()
oauth = OAuth()

osm = oauth.remote_app("osm", app_key="OSM_OAUTH_SETTINGS")

# Import all models so that they are registered with SQLAlchemy
from backend.models.postgis import *  # noqa


def create_app(env=None):
    """
    Bootstrap function to initialise the Flask app and config
    :return: Initialised Flask app
    """

    app = Flask(
        __name__,
示例#33
0
def create_client(app):
    oauth = OAuth(app)

    remote = oauth.remote_app(
        'dev',
        consumer_key='dev',
        consumer_secret='dev',
        request_token_params={'scope': 'email'},
        base_url='http://127.0.0.1:5000/api/',
        request_token_url=None,
        access_token_method='POST',
        access_token_url='http://127.0.0.1:5000/oauth/token',
        authorize_url='http://127.0.0.1:5000/oauth/authorize'
    )

    @app.route('/')
    def index():
        if 'dev_token' in session:
            ret = remote.get('email')
            return jsonify(ret.data)
        return redirect(url_for('login'))

    @app.route('/login')
    def login():
        return remote.authorize(callback=url_for('authorized', _external=True))

    @app.route('/logout')
    def logout():
        session.pop('dev_token', None)
        return redirect(url_for('index'))

    @app.route('/authorized')
    def authorized():
        resp = remote.authorized_response()
        if resp is None:
            return 'Access denied: error=%s' % (
                request.args['error']
            )
        if isinstance(resp, dict) and 'access_token' in resp:
            session['dev_token'] = (resp['access_token'], '')
            return jsonify(resp)
        return str(resp)

    @app.route('/client')
    def client_method():
        ret = remote.get("client")
        if ret.status not in (200, 201):
            return abort(ret.status)
        return ret.raw_data

    @app.route('/address')
    def address():
        ret = remote.get('address/hangzhou')
        if ret.status not in (200, 201):
            return ret.raw_data, ret.status
        return ret.raw_data

    @app.route('/method/<name>')
    def method(name):
        func = getattr(remote, name)
        ret = func('method')
        return ret.raw_data

    @remote.tokengetter
    def get_oauth_token():
        return session.get('dev_token')

    return remote
示例#34
0

import os
import json
from functools import wraps

from flask import abort
from flask import Flask
from flask import redirect
from flask import session
from flask_oauthlib.client import OAuth


__version__ = "0.0.1"
app = Flask(__name__)
oauth = OAuth()
evesso = oauth.remote_app("evesso", app_key="EVESSO")
HEARTBEAT = "<!-- HEARTBEAT -->"


# setup flask
APP_SECRET = os.environ.get("FLASK_APP_SECRET_KEY")


if not APP_SECRET:
    raise RuntimeError("FLASK_APP_SECRET_KEY is required!")


if os.path.isfile(APP_SECRET):
    with open(APP_SECRET, "r") as opensecret:
        APP_SECRET = opensecret.read().strip()
示例#35
0
import os

from flask import g
from flask_oauthlib.client import OAuth

oauth = OAuth()

github = oauth.remote_app(
    'github',
    consumer_key=os.getenv('GITHUB_CONSUMER_KEY'),
    consumer_secret=os.getenv('GITHUB_CONSUMER_SECRET'),
    request_token_params={"scope": "user.email"},
    base_url="https://api.github.com/",
    request_token_url=
    None,  # This is None for OAuth2.0, for OAuth1 we need request token
    access_token_method="POST",
    access_token_url="https://github.com/login/oauth/access_token",
    authorize_url="https://github.com/login/oauth/authorize")


@github.tokengetter
def get_github_token():
    if 'access_token' in g:
        return g.access_token
示例#36
0
from pymongo.errors import (ConnectionFailure)

from flask_debugtoolbar import DebugToolbarExtension
toolbar = DebugToolbarExtension()

from flask_bootstrap import Bootstrap
bootstrap = Bootstrap()

from scout.adapter import MongoAdapter
store = MongoAdapter()

from flask_login import LoginManager
from flask_oauthlib.client import OAuth
login_manager = LoginManager()
oauth = OAuth()
# use Google as remote application
# you must configure 3 values from Google APIs console
# https://code.google.com/apis/console
google = oauth.remote_app('google', app_key='GOOGLE')

from flask_mail import Mail
mail = Mail()

from loqusdb.plugins import MongoAdapter as LoqusDBMongoAdapter

from scout.adapter.client import get_connection


class LoqusDB(LoqusDBMongoAdapter):
    def init_app(self, app):
示例#37
0
from flask_socketio import SocketIO, emit, join_room
from flask_session import Session
import gevent
from gevent import monkey
monkey.patch_all()

import config

APP = flask.Flask(__name__, template_folder='static/templates')
APP.debug = True
APP.secret_key = 'development'
APP.config['SESSION_TYPE'] = 'filesystem'

Session(APP)
socketio = SocketIO(APP, manage_session=False, async_mode="gevent")
OAUTH = OAuth(APP)
MSGRAPH = OAUTH.remote_app(
    'microsoft',
    consumer_key=config.CLIENT_ID,
    consumer_secret=config.CLIENT_SECRET,
    request_token_params={'scope': config.SCOPES},
    base_url=config.RESOURCE + config.API_VERSION + '/',
    request_token_url=None,
    access_token_method='POST',
    access_token_url=config.AUTHORITY_URL + config.TOKEN_ENDPOINT,
    authorize_url=config.AUTHORITY_URL + config.AUTH_ENDPOINT)


@APP.route('/')
def homepage():
    """Render the home page."""
示例#38
0
from flask import Flask, redirect, url_for, session, request, jsonify
from flask_oauthlib.client import OAuth

app = Flask(__name__)
app.config['GOOGLE_ID'] = "GOOGLEID"
app.config['GOOGLE_SECRET'] = "GOOGLESECRET"
app.debug = True
app.secret_key = 'development'
oauth = OAuth(app)

google = oauth.remote_app(
    name='google',
    consumer_key=app.config.get('GOOGLE_ID'),
    consumer_secret=app.config.get('GOOGLE_SECRET'),
    request_token_params={'scope': 'email'},
    base_url='https://www.googleapis.com/oauth2/v1/',
    request_token_url=None,
    access_token_method='POST',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    authorize_url='https://accounts.google.com/o/oauth2/auth')


@app.route('/')
def index():
    access_token = session.get('access_token')
    if access_token is None:
        return redirect(url_for('login'))

    access_token = access_token[0]
    from urllib2 import Request, urlopen, URLError
示例#39
0
文件: app.py 项目: leb9212/hitman
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_oauthlib.client import OAuth
from .util.config import config

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///auth.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = config.crypto.key
app.config['SERVER_NAME'] = config.http.name

# create Database
db = SQLAlchemy(app)
oauth = OAuth(app)

from .api.auth import auth_app
app.register_blueprint(auth_app, url_prefix='/auth')

from .api.slack import slack_app
app.register_blueprint(slack_app, url_prefix='/slack')
示例#40
0
from flask import Flask, redirect, url_for, session, request, jsonify
from flask_oauthlib.client import OAuth
import requests

app = Flask(__name__)
app.debug = True
app.secret_key = 'super secret key'
oauth = OAuth(app)

google = oauth.remote_app(
    'google',
    consumer_key = '533897933561-av8uoahfptbgboh22rimfsvv7i9f9829.apps.googleusercontent.com',
    consumer_secret = 'wif9PC9DEWkvnis7KGtkL-24',
    request_token_params = {
        'scope': 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/drive'
    },
    base_url = 'https://www.googleapis.com/oauth2/v1/',
    request_token_url = None,
    access_token_method = 'POST',
    access_token_url = 'https://accounts.google.com/o/oauth2/token',
    authorize_url = 'https://accounts.google.com/o/oauth2/auth',
)

@app.route('/')
def index():
    if 'google_token' in session:
        me = google.get('userinfo')
        return jsonify({"data": me.data})
    return redirect(url_for('login'))

@app.route('/login')
""")

#def connect():
#   # Substitute the 5 pieces of information you got when creating
#   # the Mongo DB Database (underlined in red in the screenshots)
#   # Obviously, do not store your password as plaintext in practice
#    connection = MongoClient(MONGO_DB_HOST, MONGO_DB_PORT)
#    handle = connection[MONGO_DB_DATABASE_NAME]
#    handle.authenticate(MONGO_DB_DATABASE_USERNAME, MONGO_DB_DATABASE_PASSWORD)
#    return handle

app = Flask(__name__)

app.secret_key = os.environ['APP_SECRET_KEY']
oauth = OAuth(app)

app.config['MONGO_HOST'] = os.environ['MONGO_HOST']
app.config['MONGO_PORT'] = int(os.environ['MONGO_PORT'])
app.config['MONGO_DBNAME'] = os.environ['MONGO_DBNAME']
app.config['MONGO_USERNAME'] = os.environ['MONGO_USERNAME']
app.config['MONGO_PASSWORD'] = os.environ['MONGO_PASSWORD']
mongo = PyMongo(app)

# This code originally from https://github.com/lepture/flask-oauthlib/blob/master/example/github.py
# Edited by P. Conrad for SPIS 2016 to add getting Client Id and Secret from
# environment variables, so that this will work on Heroku.

github = oauth.remote_app(
    'github',
    consumer_key=os.environ['GITHUB_CLIENT_ID'],
示例#42
0
principals = Principal(app)

# Moment 时间插件
moment = Moment(app)

# 短信通道
sms_client = SmsChuangLanIsoApi(app.config['SMS']['UN'], app.config['SMS']['PW'])

# SendCloud 邮件
send_cloud_client = SendCloudClient(app)

# 七牛云存储
qi_niu_client = QiNiuClient(app)

# 第三方开放授权登录
oauth = OAuth(app)

# GitHub
oauth_github = oauth.remote_app(
    'github',
    **app.config['GITHUB_OAUTH']
)

# QQ
oauth_qq = oauth.remote_app(
    'qq',
    **app.config['QQ_OAUTH']
)

# WeiBo
oauth_weibo = oauth.remote_app(
示例#43
0
    login_user.email = user.email
    login_user.objectid = user._id
    login_user.username = user.username
    login_user.gravatar = gravatar(user.email)
    login_user.roles = user.roles
    login_user.groups = user.groups
    try:
        login_user.full_name = user.full_name
    except KeyError:
        pass

    return login_user


# Set up authentication
oauth = OAuth(app)
if app.config.get('SOCIAL_BLENDER_ID'):
    blender_id = oauth.remote_app(
        'blender_id',
        consumer_key=app.config.get('SOCIAL_BLENDER_ID')['app_id'],
        consumer_secret=app.config.get('SOCIAL_BLENDER_ID')['app_secret'],
        request_token_params={'scope': 'email'},
        base_url=app.config['BLENDER_ID_OAUTH_URL'],
        request_token_url=None,
        access_token_url=app.config['BLENDER_ID_BASE_ACCESS_TOKEN_URL'],
        authorize_url=app.config['BLENDER_ID_AUTHORIZE_URL'])
else:
    blender_id = None


class UserClass(UserMixin):
示例#44
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import basedir

from flask_oauthlib.client import OAuth

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
lm.refresh_view = 'refresh'

oauth = OAuth(app)

twitter = oauth.remote_app(
    'twitter',
    consumer_key='tqC2q3KhStpJ14H90BqNg',
    consumer_secret='c4uaYwUkpSYIvGUjCQAj80z8GcowPwtK896GN8BjM',
    base_url='https://api.twitter.com/1.1/',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authenticate',
)

from app import views, models

示例#45
0
class BaseSecurityManager(AbstractSecurityManager):
    auth_view = None
    """ The obj instance for authentication view """
    user_view = None
    """ The obj instance for user view """
    registeruser_view = None
    """ The obj instance for registering user view """
    lm = None
    """ Flask-Login LoginManager """
    oid = None
    """ Flask-OpenID OpenID """
    oauth = None
    """ Flask-OAuth """
    oauth_remotes = None
    """ OAuth email whitelists """
    oauth_whitelists = {}
    """ Initialized (remote_app) providers dict {'provider_name', OBJ } """
    oauth_tokengetter = _oauth_tokengetter
    """ OAuth tokengetter function override to implement your own tokengetter method """
    oauth_user_info = None

    user_model = None
    """ Override to set your own User Model """
    role_model = None
    """ Override to set your own Role Model """
    permission_model = None
    """ Override to set your own Permission Model """
    viewmenu_model = None
    """ Override to set your own ViewMenu Model """
    permissionview_model = None
    """ Override to set your own PermissionView Model """
    registeruser_model = None
    """ Override to set your own RegisterUser Model """

    userdbmodelview = UserDBModelView
    """ Override if you want your own user db view """
    userldapmodelview = UserLDAPModelView
    """ Override if you want your own user ldap view """
    useroidmodelview = UserOIDModelView
    """ Override if you want your own user OID view """
    useroauthmodelview = UserOAuthModelView
    """ Override if you want your own user OAuth view """
    userremoteusermodelview = UserRemoteUserModelView
    """ Override if you want your own user REMOTE_USER view """
    registerusermodelview = RegisterUserModelView

    authdbview = AuthDBView
    """ Override if you want your own Authentication DB view """
    authldapview = AuthLDAPView
    """ Override if you want your own Authentication LDAP view """
    authoidview = AuthOIDView
    """ Override if you want your own Authentication OID view """
    authoauthview = AuthOAuthView
    """ Override if you want your own Authentication OAuth view """
    authremoteuserview = AuthRemoteUserView
    """ Override if you want your own Authentication REMOTE_USER view """

    registeruserdbview = RegisterUserDBView
    """ Override if you want your own register user db view """
    registeruseroidview = RegisterUserOIDView
    """ Override if you want your own register user OpenID view """
    registeruseroauthview = RegisterUserOAuthView
    """ Override if you want your own register user OAuth view """

    resetmypasswordview = ResetMyPasswordView
    """ Override if you want your own reset my password view """
    resetpasswordview = ResetPasswordView
    """ Override if you want your own reset password view """
    userinfoeditview = UserInfoEditView
    """ Override if you want your own User information edit view """

    rolemodelview = RoleModelView
    permissionmodelview = PermissionModelView
    userstatschartview = UserStatsChartView
    viewmenumodelview = ViewMenuModelView
    permissionviewmodelview = PermissionViewModelView

    def __init__(self, appbuilder):
        super(BaseSecurityManager, self).__init__(appbuilder)
        app = self.appbuilder.get_app
        # Base Security Config
        app.config.setdefault('AUTH_ROLE_ADMIN', 'Admin')
        app.config.setdefault('AUTH_ROLE_PUBLIC', 'Public')
        app.config.setdefault('AUTH_TYPE', AUTH_DB)
        # Self Registration
        app.config.setdefault('AUTH_USER_REGISTRATION', False)
        app.config.setdefault('AUTH_USER_REGISTRATION_ROLE',
                              self.auth_role_public)

        # LDAP Config
        if self.auth_type == AUTH_LDAP:
            if 'AUTH_LDAP_SERVER' not in app.config:
                raise Exception(
                    "No AUTH_LDAP_SERVER defined on config with AUTH_LDAP authentication type."
                )
            app.config.setdefault('AUTH_LDAP_SEARCH', '')
            app.config.setdefault('AUTH_LDAP_BIND_USER', '')
            app.config.setdefault('AUTH_LDAP_APPEND_DOMAIN', '')
            app.config.setdefault('AUTH_LDAP_USERNAME_FORMAT', '')
            app.config.setdefault('AUTH_LDAP_BIND_PASSWORD', '')
            # TLS options
            app.config.setdefault('AUTH_LDAP_USE_TLS', False)
            app.config.setdefault('AUTH_LDAP_ALLOW_SELF_SIGNED', False)
            app.config.setdefault('AUTH_LDAP_TLS_DEMAND', False)
            app.config.setdefault('AUTH_LDAP_TLS_CACERTDIR', '')
            app.config.setdefault('AUTH_LDAP_TLS_CACERTFILE', '')
            app.config.setdefault('AUTH_LDAP_TLS_CERTFILE', '')
            app.config.setdefault('AUTH_LDAP_TLS_KEYFILE', '')
            # Mapping options
            app.config.setdefault('AUTH_LDAP_UID_FIELD', 'uid')
            app.config.setdefault('AUTH_LDAP_FIRSTNAME_FIELD', 'givenName')
            app.config.setdefault('AUTH_LDAP_LASTNAME_FIELD', 'sn')
            app.config.setdefault('AUTH_LDAP_EMAIL_FIELD', 'mail')

        if self.auth_type == AUTH_OID:
            self.oid = OpenID(app)
        if self.auth_type == AUTH_OAUTH:
            from flask_oauthlib.client import OAuth
            self.oauth = OAuth()
            self.oauth_remotes = dict()
            for _provider in self.oauth_providers:
                provider_name = _provider['name']
                log.debug("OAuth providers init {0}".format(provider_name))
                obj_provider = self.oauth.remote_app(provider_name,
                                                     **_provider['remote_app'])
                obj_provider._tokengetter = self.oauth_tokengetter
                if not self.oauth_user_info:
                    self.oauth_user_info = self.get_oauth_user_info
                # Whitelist only users with matching emails
                if 'whitelist' in _provider:
                    self.oauth_whitelists[provider_name] = _provider[
                        'whitelist']
                self.oauth_remotes[provider_name] = obj_provider

        self.lm = LoginManager(app)
        self.lm.login_view = 'login'
        self.lm.user_loader(self.load_user)

    @property
    def get_url_for_registeruser(self):
        return url_for('%s.%s' % (self.registeruser_view.endpoint,
                                  self.registeruser_view.default_view))

    @property
    def get_user_datamodel(self):
        return self.user_view.datamodel

    @property
    def get_register_user_datamodel(self):
        return self.registerusermodelview.datamodel

    @property
    def auth_type(self):
        return self.appbuilder.get_app.config['AUTH_TYPE']

    @property
    def auth_role_admin(self):
        return self.appbuilder.get_app.config['AUTH_ROLE_ADMIN']

    @property
    def auth_role_public(self):
        return self.appbuilder.get_app.config['AUTH_ROLE_PUBLIC']

    @property
    def auth_ldap_server(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_SERVER']

    @property
    def auth_ldap_use_tls(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_USE_TLS']

    @property
    def auth_user_registration(self):
        return self.appbuilder.get_app.config['AUTH_USER_REGISTRATION']

    @property
    def auth_user_registration_role(self):
        return self.appbuilder.get_app.config['AUTH_USER_REGISTRATION_ROLE']

    @property
    def auth_ldap_search(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_SEARCH']

    @property
    def auth_ldap_bind_user(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_BIND_USER']

    @property
    def auth_ldap_bind_password(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_BIND_PASSWORD']

    @property
    def auth_ldap_append_domain(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_APPEND_DOMAIN']

    @property
    def auth_ldap_username_format(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_USERNAME_FORMAT']

    @property
    def auth_ldap_uid_field(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_UID_FIELD']

    @property
    def auth_ldap_firstname_field(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_FIRSTNAME_FIELD']

    @property
    def auth_ldap_lastname_field(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_LASTNAME_FIELD']

    @property
    def auth_ldap_email_field(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_EMAIL_FIELD']

    @property
    def auth_ldap_bind_first(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_BIND_FIRST']

    @property
    def auth_ldap_allow_self_signed(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_ALLOW_SELF_SIGNED']

    @property
    def auth_ldap_tls_demand(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_TLS_DEMAND']

    @property
    def auth_ldap_tls_cacertdir(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_TLS_CACERTDIR']

    @property
    def auth_ldap_tls_cacertfile(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_TLS_CACERTFILE']

    @property
    def auth_ldap_tls_certfile(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_TLS_CERTFILE']

    @property
    def auth_ldap_tls_keyfile(self):
        return self.appbuilder.get_app.config['AUTH_LDAP_TLS_KEYFILE']

    @property
    def openid_providers(self):
        return self.appbuilder.get_app.config['OPENID_PROVIDERS']

    @property
    def oauth_providers(self):
        return self.appbuilder.get_app.config['OAUTH_PROVIDERS']

    def oauth_user_info_getter(self, f):
        """
            Decorator function to be the OAuth user info getter
            for all the providers, receives provider and response
            return a dict with the information returned from the provider.
            The returned user info dict should have it's keys with the same
            name as the User Model.

            Use it like this an example for GitHub ::

                @appbuilder.sm.oauth_user_info_getter
                def my_oauth_user_info(sm, provider, response=None):
                    if provider == 'github':
                        me = sm.oauth_remotes[provider].get('user')
                        return {'username': me.data.get('login')}
                    else:
                        return {}
        """
        def wraps(provider, response=None):
            ret = f(self, provider, response=response)
            # Checks if decorator is well behaved and returns a dict as supposed.
            if not type(ret) == dict:
                log.error(
                    "OAuth user info decorated function did not returned a dict, but: {0}"
                    .format(type(ret)))
                return {}
            return ret

        self.oauth_user_info = wraps
        return wraps

    def get_oauth_token_key_name(self, provider):
        """
            Returns the token_key name for the oauth provider
            if none is configured defaults to oauth_token
            this is configured using OAUTH_PROVIDERS and token_key key.
        """
        for _provider in self.oauth_providers:
            if _provider['name'] == provider:
                return _provider.get('token_key', 'oauth_token')

    def get_oauth_token_secret_name(self, provider):
        """
            Returns the token_secret name for the oauth provider
            if none is configured defaults to oauth_secret
            this is configured using OAUTH_PROVIDERS and token_secret
        """
        for _provider in self.oauth_providers:
            if _provider['name'] == provider:
                return _provider.get('token_secret', 'oauth_token_secret')

    def set_oauth_session(self, provider, oauth_response):
        """
            Set the current session with OAuth user secrets
        """
        # Get this provider key names for token_key and token_secret
        token_key = self.appbuilder.sm.get_oauth_token_key_name(provider)
        token_secret = self.appbuilder.sm.get_oauth_token_secret_name(provider)
        # Save users token on encrypted session cookie
        session['oauth'] = (oauth_response[token_key],
                            oauth_response.get(token_secret, ''))
        session['oauth_provider'] = provider

    def get_oauth_user_info(self, provider, resp):
        """
            Since there are different OAuth API's with different ways to
            retrieve user info
        """
        # for GITHUB
        if provider == 'github' or provider == 'githublocal':
            me = self.appbuilder.sm.oauth_remotes[provider].get('user')
            log.debug("User info from Github: {0}".format(me.data))
            return {'username': "******" + me.data.get('login')}
        # for twitter
        if provider == 'twitter':
            me = self.appbuilder.sm.oauth_remotes[provider].get(
                'account/settings.json')
            log.debug("User info from Twitter: {0}".format(me.data))
            return {'username': "******" + me.data.get('screen_name', '')}
        # for linkedin
        if provider == 'linkedin':
            me = self.appbuilder.sm.oauth_remotes[provider].get(
                'people/~:(id,email-address,first-name,last-name)?format=json')
            log.debug("User info from Linkedin: {0}".format(me.data))
            return {
                'username': "******" + me.data.get('id', ''),
                'email': me.data.get('email-address', ''),
                'first_name': me.data.get('firstName', ''),
                'last_name': me.data.get('lastName', '')
            }
        # for Google
        if provider == 'google':
            me = self.appbuilder.sm.oauth_remotes[provider].get('userinfo')
            log.debug("User info from Google: {0}".format(me.data))
            return {
                'username': "******" + me.data.get('id', ''),
                'first_name': me.data.get('given_name', ''),
                'last_name': me.data.get('family_name', ''),
                'email': me.data.get('email', '')
            }
        # for Azure AD Tenant. Azure OAuth response contains JWT token which has user info.
        # JWT token needs to be base64 decoded.
        # https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code
        if provider == 'azure':
            log.debug("Azure response received : {0}".format(resp))
            id_token = resp['id_token']
            log.debug(str(id_token))
            me = self._azure_jwt_token_parse(id_token)
            log.debug("Parse JWT token : {0}".format(me))
            return {
                'name': me['name'],
                'email': me['upn'],
                'first_name': me['given_name'],
                'last_name': me['family_name'],
                'id': me['oid'],
                'username': me['oid']
            }
        else:
            return {}

    def _azure_parse_jwt(self, id_token):
        jwt_token_parts = r"^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$"
        matches = re.search(jwt_token_parts, id_token)
        if not matches or len(matches.groups()) < 3:
            log.error('Unable to parse token.')
            return {}

        return {
            'header': matches.group(1),
            'Payload': matches.group(2),
            'Sig': matches.group(3)
        }

    def _azure_jwt_token_parse(self, id_token):
        jwt_split_token = self._azure_parse_jwt(id_token)
        if not jwt_split_token:
            return

        jwt_payload = jwt_split_token['Payload']
        # Prepare for base64 decoding
        payload_b64_string = jwt_payload
        payload_b64_string += '=' * (4 - ((len(jwt_payload) % 4)))
        decoded_payload = base64.urlsafe_b64decode(
            payload_b64_string.encode('ascii'))

        if not decoded_payload:
            log.error('Payload of id_token could not be base64 url decoded.')
            return

        jwt_decoded_payload = json.loads(decoded_payload.decode('utf-8'))

        return jwt_decoded_payload

    def register_views(self):
        if self.auth_user_registration:
            if self.auth_type == AUTH_DB:
                self.registeruser_view = self.registeruserdbview()
            elif self.auth_type == AUTH_OID:
                self.registeruser_view = self.registeruseroidview()
            elif self.auth_type == AUTH_OAUTH:
                self.registeruser_view = self.registeruseroauthview()
            if self.registeruser_view:
                self.appbuilder.add_view_no_menu(self.registeruser_view)

        self.appbuilder.add_view_no_menu(self.resetpasswordview())
        self.appbuilder.add_view_no_menu(self.resetmypasswordview())
        self.appbuilder.add_view_no_menu(self.userinfoeditview())

        if self.auth_type == AUTH_DB:
            self.user_view = self.userdbmodelview
            self.auth_view = self.authdbview()

        elif self.auth_type == AUTH_LDAP:
            self.user_view = self.userldapmodelview
            self.auth_view = self.authldapview()
        elif self.auth_type == AUTH_OAUTH:
            self.user_view = self.useroauthmodelview
            self.auth_view = self.authoauthview()
        elif self.auth_type == AUTH_REMOTE_USER:
            self.user_view = self.userremoteusermodelview
            self.auth_view = self.authremoteuserview()
        else:
            self.user_view = self.useroidmodelview
            self.auth_view = self.authoidview()
            if self.auth_user_registration:
                pass
                # self.registeruser_view = self.registeruseroidview()
                # self.appbuilder.add_view_no_menu(self.registeruser_view)

        self.appbuilder.add_view_no_menu(self.auth_view)

        self.user_view = self.appbuilder.add_view(self.user_view,
                                                  "List Users",
                                                  icon="fa-user",
                                                  label=_("List Users"),
                                                  category="Security",
                                                  category_icon="fa-cogs",
                                                  category_label=_('Security'))

        role_view = self.appbuilder.add_view(self.rolemodelview,
                                             "List Roles",
                                             icon="fa-group",
                                             label=_('List Roles'),
                                             category="Security",
                                             category_icon="fa-cogs")
        role_view.related_views = [self.user_view.__class__]

        self.appbuilder.add_view(self.userstatschartview,
                                 "User's Statistics",
                                 icon="fa-bar-chart-o",
                                 label=_("User's Statistics"),
                                 category="Security")

        if self.auth_user_registration:
            self.appbuilder.add_view(self.registerusermodelview,
                                     "User's Statistics",
                                     icon="fa-user-plus",
                                     label=_("User Registrations"),
                                     category="Security")

        self.appbuilder.menu.add_separator("Security")
        self.appbuilder.add_view(self.permissionmodelview,
                                 "Base Permissions",
                                 icon="fa-lock",
                                 label=_("Base Permissions"),
                                 category="Security")
        self.appbuilder.add_view(self.viewmenumodelview,
                                 "Views/Menus",
                                 icon="fa-list-alt",
                                 label=_('Views/Menus'),
                                 category="Security")
        self.appbuilder.add_view(self.permissionviewmodelview,
                                 "Permission on Views/Menus",
                                 icon="fa-link",
                                 label=_('Permission on Views/Menus'),
                                 category="Security")

    def create_db(self):
        """
            Setups the DB, creates admin and public roles if they don't exist.
        """
        self.add_role(self.auth_role_admin)
        self.add_role(self.auth_role_public)
        if self.count_users() == 0:
            log.warning(LOGMSG_WAR_SEC_NO_USER)

    def reset_password(self, userid, password):
        """
            Change/Reset a user's password for authdb.
            Password will be hashed and saved.

            :param userid:
                the user.id to reset the password
            :param password:
                The clear text password to reset and save hashed on the db
        """
        user = self.get_user_by_id(userid)
        user.password = generate_password_hash(password)
        self.update_user(user)

    def update_user_auth_stat(self, user, success=True):
        """
            Update authentication successful to user.

            :param user:
                The authenticated user model
            :param success:
                Default to true, if false increments fail_login_count on user model
        """
        if not user.login_count:
            user.login_count = 0
        if not user.fail_login_count:
            user.fail_login_count = 0
        if success:
            user.login_count += 1
            user.fail_login_count = 0
        else:
            user.fail_login_count += 1
        user.last_login = datetime.datetime.now()
        self.update_user(user)

    def auth_user_db(self, username, password):
        """
            Method for authenticating user, auth db style

            :param username:
                The username or registered email address
            :param password:
                The password, will be tested against hashed password on db
        """
        if username is None or username == "":
            return None
        user = self.find_user(username=username)
        if user is None:
            user = self.find_user(email=username)
        if user is None or (not user.is_active):
            log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(username))
            return None
        elif check_password_hash(user.password, password):
            self.update_user_auth_stat(user, True)
            return user
        else:
            self.update_user_auth_stat(user, False)
            log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(username))
            return None

    def _search_ldap(self, ldap, con, username):
        """
            Searches LDAP for user, assumes ldap_search is set.

            :param ldap: The ldap module reference
            :param con: The ldap connection
            :param username: username to match with auth_ldap_uid_field
            :return: ldap object array
        """
        if self.auth_ldap_append_domain:
            username = username + '@' + self.auth_ldap_append_domain
        filter_str = "%s=%s" % (self.auth_ldap_uid_field, username)
        user = con.search_s(
            self.auth_ldap_search, ldap.SCOPE_SUBTREE, filter_str, [
                self.auth_ldap_firstname_field, self.auth_ldap_lastname_field,
                self.auth_ldap_email_field
            ])
        if user:
            if not user[0][0]:
                return None
        return user

    def _bind_indirect_user(self, ldap, con):
        """
            If using AUTH_LDAP_BIND_USER bind this user before performing search
            :param ldap: The ldap module reference
            :param con: The ldap connection
        """
        indirect_user = self.auth_ldap_bind_user
        if indirect_user:
            indirect_password = self.auth_ldap_bind_password
            log.debug("LDAP indirect bind with: {0}".format(indirect_user))
            con.bind_s(indirect_user, indirect_password)
            log.debug("LDAP BIND indirect OK")

    def _bind_ldap(self, ldap, con, username, password):
        """
            Private to bind/Authenticate a user.
            If AUTH_LDAP_BIND_USER exists then it will bind first with it,
            next will search the LDAP server using the username with UID
            and try to bind to it (OpenLDAP).
            If AUTH_LDAP_BIND_USER does not exit, will bind with username/password
        """
        try:
            if self.auth_ldap_bind_user:
                self._bind_indirect_user(ldap, con)
                user = self._search_ldap(ldap, con, username)
                if user:
                    log.debug("LDAP got User {0}".format(user))
                    # username = DN from search
                    username = user[0][0]
                else:
                    return False
            log.debug("LDAP bind with: {0} {1}".format(username, "XXXXXX"))
            if self.auth_ldap_username_format:
                username = self.auth_ldap_username_format % username
            if self.auth_ldap_append_domain:
                username = username + '@' + self.auth_ldap_append_domain
            con.bind_s(username, password)
            log.debug("LDAP bind OK: {0}".format(username))
            return True
        except ldap.INVALID_CREDENTIALS:
            return False

    @staticmethod
    def ldap_extract(ldap_dict, field, fallback):
        if not ldap_dict.get(field):
            return fallback
        return ldap_dict[field][0].decode('utf-8') or fallback

    def auth_user_ldap(self, username, password):
        """
            Method for authenticating user, auth LDAP style.
            depends on ldap module that is not mandatory requirement
            for F.A.B.

            :param username:
                The username
            :param password:
                The password
        """
        if username is None or username == "":
            return None
        user = self.find_user(username=username)
        if user is not None and (not user.is_active):
            return None
        else:
            try:
                import ldap
            except:
                raise Exception("No ldap library for python.")
            try:
                if self.auth_ldap_allow_self_signed:
                    ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,
                                    ldap.OPT_X_TLS_ALLOW)
                    ldap.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
                elif self.auth_ldap_tls_demand:
                    ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,
                                    ldap.OPT_X_TLS_DEMAND)
                    ldap.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
                if self.auth_ldap_tls_cacertdir:
                    ldap.set_option(ldap.OPT_X_TLS_CACERTDIR,
                                    self.auth_ldap_tls_cacertdir)
                if self.auth_ldap_tls_cacertfile:
                    ldap.set_option(ldap.OPT_X_TLS_CACERTFILE,
                                    self.auth_ldap_tls_cacertfile)
                if self.auth_ldap_tls_certfile and self.auth_ldap_tls_keyfile:
                    ldap.set_option(ldap.OPT_X_TLS_CERTFILE,
                                    self.auth_ldap_tls_certfile)
                    ldap.set_option(ldap.OPT_X_TLS_KEYFILE,
                                    self.auth_ldap_tls_keyfile)
                con = ldap.initialize(self.auth_ldap_server)
                con.set_option(ldap.OPT_REFERRALS, 0)
                if self.auth_ldap_use_tls:
                    try:
                        con.start_tls_s()
                    except Exception:
                        log.info(
                            LOGMSG_ERR_SEC_AUTH_LDAP_TLS.format(
                                self.auth_ldap_server))
                        return None
                # Authenticate user
                if not self._bind_ldap(ldap, con, username, password):
                    if user:
                        self.update_user_auth_stat(user, False)
                    log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(username))
                    return None
                # If user does not exist on the DB and not self user registration, go away
                if not user and not self.auth_user_registration:
                    return None
                # User does not exist, create one if self registration.
                elif not user and self.auth_user_registration:
                    self._bind_indirect_user(ldap, con)
                    new_user = self._search_ldap(ldap, con, username)
                    if not new_user:
                        log.warning(LOGMSG_WAR_SEC_NOLDAP_OBJ.format(username))
                        return None
                    ldap_user_info = new_user[0][1]
                    if self.auth_user_registration and user is None:
                        user = self.add_user(
                            username=username,
                            first_name=self.ldap_extract(
                                ldap_user_info, self.auth_ldap_firstname_field,
                                username),
                            last_name=self.ldap_extract(
                                ldap_user_info, self.auth_ldap_lastname_field,
                                username),
                            email=self.ldap_extract(
                                ldap_user_info, self.auth_ldap_email_field,
                                username + '@email.notfound'),
                            role=self.find_role(
                                self.auth_user_registration_role))

                self.update_user_auth_stat(user)
                return user

            except ldap.LDAPError as e:
                if type(e.message) == dict and 'desc' in e.message:
                    log.error(
                        LOGMSG_ERR_SEC_AUTH_LDAP.format(e.message['desc']))
                    return None
                else:
                    log.error(e)
                    return None

    def auth_user_oid(self, email):
        """
            OpenID user Authentication

            :type self: User model
        """
        user = self.find_user(email=email)
        if user is None or (not user.is_active):
            log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(email))
            return None
        else:
            self.update_user_auth_stat(user)
            return user

    def auth_user_remote_user(self, username):
        """
            REMOTE_USER user Authentication

            :type self: User model
        """
        user = self.find_user(username=username)

        # User does not exist, create one if auto user registration.
        if user is None and self.auth_user_registration:
            user = self.add_user(
                # All we have is REMOTE_USER, so we set
                # the other fields to blank.
                username=username,
                first_name=username,
                last_name='-',
                email='-',
                role=self.find_role(self.auth_user_registration_role))

        # If user does not exist on the DB and not auto user registration,
        # or user is inactive, go away.
        elif user is None or (not user.is_active):
            log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(username))
            return None

        self.update_user_auth_stat(user)
        return user

    def auth_user_oauth(self, userinfo):
        """
            OAuth user Authentication

            :userinfo: dict with user information the keys have the same name
            as User model columns.
        """
        if 'username' in userinfo:
            user = self.find_user(username=userinfo['username'])
        elif 'email' in userinfo:
            user = self.find_user(email=userinfo['email'])
        else:
            log.error('User info does not have username or email {0}'.format(
                userinfo))
            return None
        # User is disabled
        if user and not user.is_active:
            log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(userinfo))
            return None
        # If user does not exist on the DB and not self user registration, go away
        if not user and not self.auth_user_registration:
            return None
        # User does not exist, create one if self registration.
        if not user:
            user = self.add_user(username=userinfo['username'],
                                 first_name=userinfo['first_name'],
                                 last_name=userinfo['last_name'],
                                 email=userinfo['email'],
                                 role=self.find_role(
                                     self.auth_user_registration_role))
            if not user:
                log.error("Error creating a new OAuth user %s" %
                          userinfo['username'])
                return None
        self.update_user_auth_stat(user)
        return user

    """
        ----------------------------------------
            PERMISSION ACCESS CHECK
        ----------------------------------------
    """

    def is_item_public(self, permission_name, view_name):
        """
            Check if view has public permissions

            :param permission_name:
                the permission: can_show, can_edit...
            :param view_name:
                the name of the class view (child of BaseView)
        """
        permissions = self.get_public_permissions()
        if permissions:
            for i in permissions:
                if (view_name == i.view_menu.name) and (permission_name
                                                        == i.permission.name):
                    return True
            return False
        else:
            return False

    def _has_view_access(self, user, permission_name, view_name):
        roles = user.roles
        for role in roles:
            permissions = role.permissions
            if permissions:
                for permission in permissions:
                    if (view_name == permission.view_menu.name) and (
                            permission_name == permission.permission.name):
                        return True
        return False

    def has_access(self, permission_name, view_name):
        """
            Check if current user or public has access to view or menu
        """
        if current_user.is_authenticated:
            return self._has_view_access(g.user, permission_name, view_name)
        else:
            return self.is_item_public(permission_name, view_name)

    def add_permissions_view(self, base_permissions, view_menu):
        """
            Adds a permission on a view menu to the backend

            :param base_permissions:
                list of permissions from view (all exposed methods): 'can_add','can_edit' etc...
            :param view_menu:
                name of the view or menu to add
        """
        view_menu_db = self.add_view_menu(view_menu)
        perm_views = self.find_permissions_view_menu(view_menu_db)

        if not perm_views:
            # No permissions yet on this view
            for permission in base_permissions:
                pv = self.add_permission_view_menu(permission, view_menu)
                role_admin = self.find_role(self.auth_role_admin)
                self.add_permission_role(role_admin, pv)
        else:
            # Permissions on this view exist but....
            role_admin = self.find_role(self.auth_role_admin)
            for permission in base_permissions:
                # Check if base view permissions exist
                if not self.exist_permission_on_views(perm_views, permission):
                    pv = self.add_permission_view_menu(permission, view_menu)
                    self.add_permission_role(role_admin, pv)
            for perm_view in perm_views:
                if perm_view.permission.name not in base_permissions:
                    # perm to delete
                    roles = self.get_all_roles()
                    perm = self.find_permission(perm_view.permission.name)
                    # del permission from all roles
                    for role in roles:
                        self.del_permission_role(role, perm)
                    self.del_permission_view_menu(perm_view.permission.name,
                                                  view_menu)
                elif perm_view not in role_admin.permissions:
                    # Role Admin must have all permissions
                    self.add_permission_role(role_admin, perm_view)

    def add_permissions_menu(self, view_menu_name):
        """
            Adds menu_access to menu on permission_view_menu

            :param view_menu_name:
                The menu name
        """
        self.add_view_menu(view_menu_name)
        pv = self.find_permission_view_menu('menu_access', view_menu_name)
        if not pv:
            pv = self.add_permission_view_menu('menu_access', view_menu_name)
            role_admin = self.find_role(self.auth_role_admin)
            self.add_permission_role(role_admin, pv)

    def security_cleanup(self, baseviews, menus):
        """
            Will cleanup all unused permissions from the database

            :param baseviews: A list of BaseViews class
            :param menus: Menu class
        """
        viewsmenus = self.get_all_view_menu()
        roles = self.get_all_roles()
        for viewmenu in viewsmenus:
            found = False
            for baseview in baseviews:
                if viewmenu.name == baseview.__class__.__name__:
                    found = True
                    break
            if menus.find(viewmenu.name):
                found = True
            if not found:
                permissions = self.find_permissions_view_menu(viewmenu)
                for permission in permissions:
                    for role in roles:
                        self.del_permission_role(role, permission)
                    self.del_permission_view_menu(permission.permission.name,
                                                  viewmenu.name)
                self.del_view_menu(viewmenu.name)

    """
     ---------------------------
     INTERFACE ABSTRACT METHODS
     ---------------------------

     ---------------------
     PRIMITIVES FOR USERS
    ----------------------
    """

    def find_register_user(self, registration_hash):
        """
            Generic function to return user registration
        """
        raise NotImplementedError

    def add_register_user(self,
                          username,
                          first_name,
                          last_name,
                          email,
                          password='',
                          hashed_password=''):
        """
            Generic function to add user registration
        """
        raise NotImplementedError

    def del_register_user(self, register_user):
        """
            Generic function to delete user registration
        """
        raise NotImplementedError

    def get_user_by_id(self, pk):
        """
            Generic function to return user by it's id (pk)
        """
        raise NotImplementedError

    def find_user(self, username=None, email=None):
        """
            Generic function find a user by it's username or email
        """
        raise NotImplementedError

    def get_all_users(self):
        """
            Generic function that returns all exsiting users
        """
        raise NotImplementedError

    def add_user(self,
                 username,
                 first_name,
                 last_name,
                 email,
                 role,
                 password=''):
        """
            Generic function to create user
        """
        raise NotImplementedError

    def update_user(self, user):
        """
            Generic function to update user

            :param user: User model to update to database
        """
        raise NotImplementedError

    def count_users(self):
        """
            Generic function to count the existing users
        """
        raise NotImplementedError

    """
    ----------------------
     PRIMITIVES FOR ROLES
    ----------------------
    """

    def find_role(self, name):
        raise NotImplementedError

    def add_role(self, name):
        raise NotImplementedError

    def get_all_roles(self):
        raise NotImplementedError

    """
    ----------------------------
     PRIMITIVES FOR PERMISSIONS
    ----------------------------
    """

    def get_public_permissions(self):
        """
            returns all permissions from public role
        """
        raise NotImplementedError

    def find_permission(self, name):
        """
            Finds and returns a Permission by name
        """
        raise NotImplementedError

    def add_permission(self, name):
        """
            Adds a permission to the backend, model permission

            :param name:
                name of the permission: 'can_add','can_edit' etc...
        """
        raise NotImplementedError

    def del_permission(self, name):
        """
            Deletes a permission from the backend, model permission

            :param name:
                name of the permission: 'can_add','can_edit' etc...
        """
        raise NotImplementedError

    """
    ----------------------
     PRIMITIVES VIEW MENU
    ----------------------
    """

    def find_view_menu(self, name):
        """
            Finds and returns a ViewMenu by name
        """
        raise NotImplementedError

    def get_all_view_menu(self):
        raise NotImplementedError

    def add_view_menu(self, name):
        """
            Adds a view or menu to the backend, model view_menu
            param name:
                name of the view menu to add
        """
        raise NotImplementedError

    def del_view_menu(self, name):
        """
            Deletes a ViewMenu from the backend

            :param name:
                name of the ViewMenu
        """
        raise NotImplementedError

    """
    ----------------------
     PERMISSION VIEW MENU
    ----------------------
    """

    def find_permission_view_menu(self, permission_name, view_menu_name):
        """
            Finds and returns a PermissionView by names
        """
        raise NotImplementedError

    def find_permissions_view_menu(self, view_menu):
        """
            Finds all permissions from ViewMenu, returns list of PermissionView

            :param view_menu: ViewMenu object
            :return: list of PermissionView objects
        """
        raise NotImplementedError

    def add_permission_view_menu(self, permission_name, view_menu_name):
        """
            Adds a permission on a view or menu to the backend

            :param permission_name:
                name of the permission to add: 'can_add','can_edit' etc...
            :param view_menu_name:
                name of the view menu to add
        """
        raise NotImplementedError

    def del_permission_view_menu(self, permission_name, view_menu_name):
        raise NotImplementedError

    def exist_permission_on_views(self, lst, item):
        raise NotImplementedError

    def exist_permission_on_view(self, lst, permission, view_menu):
        raise NotImplementedError

    def add_permission_role(self, role, perm_view):
        """
            Add permission-ViewMenu object to Role

            :param role:
                The role object
            :param perm_view:
                The PermissionViewMenu object
        """
        raise NotImplementedError

    def del_permission_role(self, role, perm_view):
        """
            Remove permission-ViewMenu object to Role

            :param role:
                The role object
            :param perm_view:
                The PermissionViewMenu object
        """
        raise NotImplementedError

    def load_user(self, pk):
        return self.get_user_by_id(int(pk))

    @staticmethod
    def before_request():
        g.user = current_user
示例#46
0
import os
from flask import g  #this can hold variables globally inside the whole app
from flask_oauthlib.client import OAuth
from dotenv import load_dotenv
load_dotenv()

oauth = OAuth()

client_id = os.getenv("CLIENT_ID")
client_secret = os.getenv("CILENT_SECRET")
#print(client_id,client_secret)

github = oauth.remote_app(
    'github',
    consumer_key=client_id,
    consumer_secret=client_secret,
    request_token_params={"scope": "user:email"},
    base_url="https://api.github.com/",
    request_token_url=None,
    access_token_method="POST",
    access_token_url="https://github.com/login/oauth/access_token",
    authorize_url="https://github.com/login/oauth/authorize")


#pass the access token to the github user object
@github.tokengetter
def get_github_token():
    if "access_token" in g:
        return g.access_token
示例#47
0
import logging
import os

from flask import Flask

app = Flask("SN2", template_folder='templates')
app.config.from_pyfile('config.cfg')
logging.basicConfig(filename='output/app.log',
                    level=app.config['LOGGING_LEVEL'])

from flask_oauthlib.client import OAuth

oauth = OAuth()
twitter = oauth.remote_app(
    'twitter',
    base_url='https://api.twitter.com/1/',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authenticate',
    consumer_key=app.config['TWITTER_CONSUMER_KEY'],
    consumer_secret=app.config['TWITTER_CONSUMER_SECRET'],
)


@twitter.tokengetter
def get_twitter_token():
    return session.get('twitter_token')


from views import *
from processing.scripts import *
示例#48
0
import logging
import requests
from flask import redirect, url_for, Blueprint, flash, request, session
from flask_oauthlib.client import OAuth

from redash import models, settings
from redash.authentication import create_and_login_user, logout_and_redirect_to_index, get_next_path
from redash.authentication.org_resolving import current_org

logger = logging.getLogger('google_oauth')

oauth = OAuth()
blueprint = Blueprint('google_oauth', __name__)


def google_remote_app():
    if 'google' not in oauth.remote_apps:
        oauth.remote_app(
            'google',
            base_url='https://www.google.com/accounts/',
            authorize_url=
            'https://accounts.google.com/o/oauth2/auth?prompt=select_account+consent',
            request_token_url=None,
            request_token_params={
                'scope':
                'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',
            },
            access_token_url='https://accounts.google.com/o/oauth2/token',
            access_token_method='POST',
            consumer_key=settings.GOOGLE_CLIENT_ID,
            consumer_secret=settings.GOOGLE_CLIENT_SECRET)
示例#49
0
FACEBOOK_APP_ID = 'd'
FACEBOOK_APP_SECRET = 'd'

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {'db': 'aetherguilds'}
app.secret_key = 'secret!'
app.config['DEBUG'] = True
db = MongoEngine(app)

app._static_folder = 'public'
app.register_blueprint(user_bp, url_prefix='/users')
app.register_blueprint(scroll_bp, url_prefix='/scrolls')
app.register_blueprint(inventory_bp, url_prefix="/inventories")
app.register_blueprint(domain_bp, url_prefix="/domains")
oauth = OAuth(app)
sslify = SSLify(app)

facebook = oauth.remote_app(
    'facebook',
    consumer_key=FACEBOOK_APP_ID,
    consumer_secret=FACEBOOK_APP_SECRET,
    request_token_params={'scope': 'email'},
    base_url='https://graph.facebook.com',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth')


@app.route('/')
def index():
示例#50
0
# Format error response and append status code.
class AuthError(Exception):
    def __init__(self, error, status_code):
        self.error = error
        self.status_code = status_code


@APP.errorhandler(AuthError)
def handle_auth_error(ex):
    response = jsonify(ex.error)
    response.status_code = ex.status_code
    return response


# Initializer
oauth = OAuth(APP)
auth0 = oauth.remote_app(
    'auth0',
    consumer_key=ENV_PARAM["AUTH0_CLIENT_ID"],
    consumer_secret=ENV_PARAM["AUTH0_CLIENT_SECRET"],
    request_token_params={
        'scope': 'openid profile',
        'audience': 'https://' + ENV_PARAM["AUTH0_DOMAIN"] + '/userinfo'
    },
    base_url='https://%s' % ENV_PARAM["AUTH0_DOMAIN"],
    access_token_method='POST',
    access_token_url='/oauth/token',
    authorize_url='/authorize',
)
view_manager._initializer(auth0, ENV_PARAM)
示例#51
0
from datetime import datetime
from random import choice
from json import loads
from flask import render_template, flash, redirect, url_for, request, session, g
from forms import EditUserForm, PostForm, SearchForm, EditPostForm
from app import app, db, lm
from models import User, Post
from flask_oauthlib.client import OAuth
from flask.ext.login import login_user, logout_user, current_user, login_required
from flask.ext.misaka import markdown

@lm.user_loader
def load_user(id):
    return User.query.get(int(id))

oauth = OAuth()
fb_oauth = oauth.remote_app('facebook',
        base_url='https://graph.facebook.com/',
        request_token_url=None,
        access_token_url='/oauth/access_token',
        authorize_url='https://www.facebook.com/dialog/oauth',
        consumer_key=app.config['OAUTH_CREDENTIALS']['facebook']['id'],
        consumer_secret=app.config['OAUTH_CREDENTIALS']['facebook']['secret'],
        request_token_params={'scope': 'email, public_profile'})

tw_oauth = oauth.remote_app('twitter',
    base_url='https://api.twitter.com/1/',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    consumer_key=app.config['OAUTH_CREDENTIALS']['twitter']['id'],
示例#52
0
from flask.ext.security import login_required
from flask.views import MethodView
from flask_oauthlib.client import OAuth
import os
from core.util import append_container, DEFAULT_SECURITY, get_context_for_scope
from flask import current_app
from core.oauth.base import state_token_required, OauthV1Base, OauthV2Base
from flask.ext.restful import Resource, Api
from flask.ext.restful import reqparse
from flask_restful_swagger import swagger

oauth_views = Blueprint('oauth_views',
                        __name__,
                        template_folder=os.path.join(
                            current_app.config['REPO_PATH'], 'templates'))
oauth = OAuth(oauth_views)
api = swagger.docs(Api(oauth_views),
                   api_spec_url=current_app.config['API_SPEC_URL'])

oauth_handlers = current_app.config['OAUTH_CONFIG'].keys()
oauth_secrets = current_app.config.get("OAUTH_SECRETS", {})

handlers = {}
login_urls = {}

for handler in oauth_handlers:
    mod = __import__("core.oauth.{0}".format(handler))
    if handler not in oauth_secrets:
        continue

    handler_settings = dict(