Ejemplo n.º 1
0

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


@APP.errorhandler(Exception)
def handle_auth_error(ex):
    response = jsonify(ex)
    return response


oauth = OAuth(APP)

auth0 = oauth.remote_app(
    'auth0',
    consumer_key=AUTH0_CLIENT_ID,
    consumer_secret=AUTH0_CLIENT_SECRET,
    request_token_params={
        'scope': 'openid profile',
        'audience': API_AUDIENCE
    },
    base_url='https://%s' % AUTH0_DOMAIN,
    access_token_method='POST',
    access_token_url='/oauth/token',
    authorize_url='/authorize',
)
Ejemplo n.º 2
0
    SCHEDULER_API_ENABLED = True
    SCHEDULER_TIMEZONE = 'Europe/London'


app = Flask('AlarmManager')
app.logger.addHandler(ch)
app.secret_key = 'development'
app.config.update(
    {'SQLALCHEMY_DATABASE_URI': 'sqlite:///oauth_alarm_manager.sqlite'})
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
# as provider
oauth = OAuth2Provider(app)
# as client
oauth_client = OAuth(app)
api = Api(app)
app.config.from_object(Config())

conn = pymysql.connect(host='172.18.0.25',
                       port=3306,
                       user='******',
                       passwd='alarm',
                       db='alarm_db')
DEGREE_DIFFERENCE = 3

JWT = None
CREDENTIALS = {}


def build_remote_app(consumer_key, consumer_secret, request_token_params,
Ejemplo n.º 3
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_SEARCH", "")
            app.config.setdefault("AUTH_LDAP_SEARCH_FILTER", "")
            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

        # Setup Flask-Login
        self.lm = self.create_login_manager(app)

        # Setup Flask-Jwt-Extended
        self.jwt_manager = self.create_jwt_manager(app)
Ejemplo n.º 4
0
from flask_oauthlib.client import OAuth
from flask import current_app, url_for, session, request

oauth = OAuth(current_app)


class OAuthSignIn(object):
    """Parent OAuth class"""
    providers = None

    def __init__(self, provider_name):
        self.provider_name = provider_name
        credentials = current_app.config['OAUTH_CREDENTIALS'][provider_name]
        self.consumer_id = credentials['id']
        self.consumer_secret = credentials['secret']

    def authorize(self, callback=False):
        pass

    def callback(self):
        pass

    def get_callback_url(self):
        return url_for('auth_routes.oauth_callback',
                       provider=self.provider_name,
                       _external=True)

    @classmethod
    def get_provider(self, provider_name):
        if self.providers is None:
            self.providers = {}
Ejemplo n.º 5
0
from flask import Flask, g, request
from sqlalchemy import or_, func
from sqlalchemy.orm import Session, sessionmaker
from datetime import datetime, timedelta, timezone
from flask_oauthlib.client import OAuth, OAuthException

app = Flask(__name__)
app.config.from_json("config.json")

engine = sqlalchemy.create_engine(
    "postgresql://{username}:{password}@localhost/{dbname}".format(
        username=app.config["DB_USER"],
        password=app.config["DB_PASS"],
        dbname=app.config["DB_NAME"]))  # type: sqlalchemy.engine.base.Engine

oauth = OAuth()
shardbound = oauth.remote_app(
    'shardbound',
    base_url='https://st-george.spiritwalkgames.com/',
    request_token_url=None,
    access_token_url='oauth/token',
    authorize_url='oauth/authorize',
    consumer_key=app.config["OAUTH_ID"],
    consumer_secret=app.config["OAUTH_SECRET"],
    request_token_params={'scope': 'public'})


@shardbound.tokengetter
def get_shardbound_oauth_token():
    return flask.session.get('shardbound_token')
Ejemplo n.º 6
0
def instance(app):
    """:rtype: OAuth"""
    oauth = OAuth()
    oauth.remote_app('github', app_key='GITHUB_OAUTH')
    oauth.init_app(app)
    return oauth
Ejemplo n.º 7
0
from flask import (Flask, request, jsonify, render_template, abort, Response,
                   redirect, url_for, session)

config = ConfigParser.ConfigParser()
config.read('/etc/shuttleofx/client.cfg')

g_app = Flask(__name__)

g_app.config['GOOGLE_ID'] = config.get('OAUTH_CONFIG', 'googleId')
g_app.config['GOOGLE_SECRET'] = config.get('OAUTH_CONFIG', 'googleSecret')
g_app.config['GITHUB_ID'] = config.get('OAUTH_CONFIG', 'githubId')
g_app.config['GITHUB_SECRET'] = config.get('OAUTH_CONFIG', 'githubSecret')
g_app.debug = True
g_app.secret_key = 'development'

oauth = OAuth(g_app)

google = oauth.remote_app(
    'google',
    consumer_key=g_app.config.get('GOOGLE_ID'),
    consumer_secret=g_app.config.get('GOOGLE_SECRET'),
    request_token_params={
        'scope': 'https://www.googleapis.com/auth/userinfo.profile'
    },
    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',
)
Ejemplo n.º 8
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_SEARCH', '')
            app.config.setdefault('AUTH_LDAP_SEARCH_FILTER', '')
            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)
Ejemplo n.º 9
0
# some bits of text for the page.
header_text = '''
    <html>\n<head> <title>EB Flask Test with websocket </title> </head>\n<body>'''
instructions = '''
    There is an endpoint of websocket (staged) 
    \n'''
home_link = '<p><a href="/">Back</a></p>\n'
footer_text = '</body>\n</html>'

# EB looks for an 'application' callable by default.
application = Flask(__name__)
application.config['SECRET_KEY'] = 'secret!'
application.jinja_env.line_statement_prefix = '#'
socketio = SocketIO(application)
oauth = OAuth(application)

#linkedin
linkedin = oauth.remote_app(\
    'linkedin',\
    consumer_key=os.environ.get('linkedinappkey'),\
    consumer_secret=os.environ.get('linkedinappsecret'),\
    request_token_params={\
        'scope': ['r_basicprofile','r_emailaddress'],\
        'state': 'RandomString',\
    },\
    base_url='https://api.linkedin.com/v1/',\
    request_token_url=None,\
    access_token_method='POST',\
    access_token_url='https://www.linkedin.com/uas/oauth2/accessToken',\
    authorize_url='https://www.linkedin.com/uas/oauth2/authorization')
Ejemplo n.º 10
0
    http_auth = credentials.authorize(httplib2.Http())
    drive = discovery.build('drive', 'v3', http_auth)
    files = drive.files().list(q="'{0}' in parents and (mimeType='application/vnd.google-apps.spreadsheet' or mimeType='application/vnd.google-apps.folder')".format(id), orderBy="name").execute()['files']
    return render_template('charts_of_accounts.html', files = files, blueprint_name = blueprint.name)

@blueprint.route("/set_chart_of_accounts/<string:sheet_id>")
def set_chart_of_accounts(sheet_id):
    session['sheet_id'] = sheet_id
    return redirect(url_for("{0}.authorize_qbo".format(blueprint.name)))

# Step-3, authorize QBO

qbo = OAuth().remote_app(
    'qbo',
    request_token_url = 'https://oauth.intuit.com/oauth/v1/get_request_token',
    access_token_url  = 'https://oauth.intuit.com/oauth/v1/get_access_token',
    authorize_url     = 'https://appcenter.intuit.com/Connect/Begin',
    consumer_key      = app.config['QBO_CONSUMER_KEY'],
    consumer_secret   = app.config['QBO_CONSUMER_SECRET']
)

@blueprint.route("/authorize_qbo")
def authorize_qbo():
    return qbo.authorize(callback=url_for("{0}.qbo_authorized".format(blueprint.name)))

@blueprint.route("/qbo_authorized")
def qbo_authorized():
    qbo_tokens = qbo.authorized_response()
    session['qbo_tokens'] = qbo_tokens;
    qbo_company_id = request.args.get('realmId');
    session['qbo_company_id'] = qbo_company_id;
    models.store_qbo_authentication_tokens(qbo_tokens, qbo_company_id)
Ejemplo n.º 11
0
from app import site
from flask_oauthlib.client import OAuth, OAuthException

oauth = OAuth(site)

google = oauth.remote_app(
    'google',
    consumer_key=site.config.get('GOOGLE_KEY'),
    consumer_secret=site.config.get('GOOGLE_SECRET'),
    request_token_params={'scope': 'email profile'},
    base_url='https://www.googleapis.com/oauth2/v3/',
    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'
)

github = oauth.remote_app(
    'github',
    consumer_key=site.config.get('GITHUB_KEY'),
    consumer_secret=site.config.get('GITHUB_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',
)

facebook = oauth.remote_app(
    'facebook',
Ejemplo n.º 12
0
def prepare_app(name):
	app = fk.Flask(name)
	app.config.from_pyfile('config.py', silent=True)

	# Check for required configuration variables
	required = [
		'SECRET_KEY',
		'MSAPI_CONSUMER_KEY',
		'MSAPI_CONSUMER_SECRET',
		'MSAPI_REDIRECT_URL',
	]

	absent = list(filter(lambda v: v not in app.config, required))
	if len(absent) > 0:
		absent = ', '.join(absent)
		raise LookupError(f'The following variables are needed to proceed: {absent}')

	# Set defaults for optional variables
	optional = {
		'MSAPI_ORIGIN_URL': 'https://graph.microsoft.com/v1.0/',
		'MSAPI_TOKEN_URL': 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
		'MSAPI_AUTHORIZE_URL': 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
		'GROOM_HOST': 'localhost',
		'GROOM_PORT': 4221,
	}

	for key, value in optional.items():
		app.config.setdefault(key, value)

	# Configure plugins
	limiter = Limiter(app, key_func=partial(get_limit_key, app))
	db = SQLAlchemy(app)
	class Attempt(db.Model):
		__tablename__ = 'attempt'

		id     = db.Column(db.Integer, primary_key=True)
		user   = db.Column(db.String(120))
		time   = db.Column(db.Integer)
		# XXX: Maybe we should use an enum instead.
		result = db.Column(db.Text)

		def __init__(self, user, result):
			self.user, self.result = user or 'unknown', result
			self.time = time.time()

	class User(db.Model):
		__tablename__ = 'user'

		id    = db.Column(db.Integer, primary_key=True)
		user  = db.Column(db.String(120), unique=True)
		# XXX: Maybe we should use an enum instead.
		level = db.Column(db.Integer)
		# Levels:
		# -1 : Disabled
		#  0 : Can open the door
		#  1 : Can view logs
		#  2 : Can ban/unban users from the service if level < theirs
		#  3 : Can promote/demote users

		def __init__(self, user, level):
			self.user, self.level = user, level

	msapi = OAuth(app).remote_app(
		'msapi',
		consumer_key=app.config['MSAPI_CONSUMER_KEY'],
		consumer_secret=app.config['MSAPI_CONSUMER_SECRET'],
		request_token_params={'scope': ['User.Read']},
		base_url=app.config['MSAPI_ORIGIN_URL'],
		access_token_method='POST',
		access_token_url=app.config['MSAPI_TOKEN_URL'],
		request_token_url=None,
		authorize_url=app.config['MSAPI_AUTHORIZE_URL']
	)

	@app.before_request
	def groom_export():
		fk.g.db = db
		fk.g.Attempt = Attempt
		fk.g.User = User
		fk.g.msapi = msapi

	@msapi.tokengetter
	def msapi_get_token():
		return fk.session.get('access_token'), ''

	return app, limiter, db, User, Attempt
Ejemplo n.º 13
0
def init(app):
    oauth = OAuth(app)

    twitch = oauth.remote_app(
        'twitch',
        consumer_key=app.bot_config['webtwitchapi']['client_id'],
        consumer_secret=app.bot_config['webtwitchapi']['client_secret'],
        request_token_params={
            'scope': 'user_read',
        },
        base_url='https://api.twitch.tv/kraken/',
        request_token_url=None,
        access_token_method='POST',
        access_token_url='https://api.twitch.tv/kraken/oauth2/token',
        authorize_url='https://api.twitch.tv/kraken/oauth2/authorize',
    )

    @app.route('/login')
    def login():
        callback_url = app.bot_config['webtwitchapi'][
            'redirect_uri'] if 'redirect_uri' in app.bot_config[
                'webtwitchapi'] else url_for('authorized', _external=True)
        state = request.args.get('n') or request.referrer or None
        return twitch.authorize(
            callback=callback_url,
            state=state,
        )

    @app.route('/login/error')
    def login_error():
        return render_template('login_error.html')

    @app.route('/login/authorized')
    def authorized():
        try:
            resp = twitch.authorized_response()
        except OAuthException:
            log.exception('An exception was caught while authorizing')
            next_url = get_next_url(request, 'state')
            return redirect(next_url)
        except:
            log.exception('Unhandled exception while authorizing')
            return render_template('login_error.html')

        print(resp)
        if resp is None:
            if 'error' in request.args and 'error_description' in request.args:
                log.warn('Access denied: reason={}, error={}'.format(
                    request.args['error'], request.args['error_description']))
            next_url = get_next_url(request, 'state')
            return redirect(next_url)
        elif type(resp) is OAuthException:
            log.warn(resp.message)
            log.warn(resp.data)
            log.warn(resp.type)
            next_url = get_next_url(request, 'state')
            return redirect(next_url)
        session['twitch_token'] = (resp['access_token'], )
        me = twitch.get('user')
        level = 100
        with DBManager.create_session_scope() as db_session:
            db_user = db_session.query(User).filter_by(
                username=me.data['name'].lower()).one_or_none()
            if db_user:
                level = db_user.level
        session['user'] = {
            'username': me.data['name'],
            'username_raw': me.data['display_name'],
            'level': level,
        }
        next_url = get_next_url(request, 'state')
        return redirect(next_url)

    def get_next_url(request, key='n'):
        next_url = request.args.get(key, '/')
        if next_url.startswith('//'):
            return '/'
        return next_url

    @app.route('/logout')
    def logout():
        session.pop('twitch_token', None)
        session.pop('user', None)
        next_url = get_next_url(request)
        if next_url.startswith('/admin'):
            next_url = '/'
        return redirect(next_url)

    @twitch.tokengetter
    def get_twitch_oauth_token():
        return session.get('twitch_token')

    def change_twitch_header(uri, headers, body):
        auth = headers.get('Authorization')
        if auth:
            auth = auth.replace('Bearer', 'OAuth')
            headers['Authorization'] = auth
        return uri, headers, body

    twitch.pre_request = change_twitch_header
Ejemplo n.º 14
0
from __future__ import absolute_import

from flask import url_for, session, request, jsonify, Blueprint, flash, current_app
from flask_oauthlib.client import OAuth

from keg.web import redirect

oauthlib = OAuth()


class OAuthError(Exception):
    pass


class Provider(object):
    def authorize(self, **kwargs):
        return self.remote_app.authorize(**kwargs)

    def get(self, *args):
        return self.remote_app.get(*args)


class Google(Provider):
    def __init__(self):
        self.remote_app = oauthlib.remote_app(
            'google',
            request_token_params={
                'scope': 'https://www.googleapis.com/auth/userinfo.email'
            },
            base_url='https://www.googleapis.com/oauth2/v1/',
            request_token_url=None,
Ejemplo n.º 15
0
from flask import Blueprint
from flask import redirect, url_for, session, request
from flask_oauthlib.client import OAuth, OAuthException
from config import Config

blueprint = Blueprint('spotify_controller', __name__, url_prefix='/')

oauth = OAuth(blueprint)

spotify = oauth.remote_app(
    'spotify',
    consumer_key=Config.SPOTIFY_APP_ID,
    consumer_secret=Config.SPOTIFY_APP_SECRET,
    request_token_params={
        'scope': ['user-read-email', 'playlist-read-private']
    },
    base_url='https://accounts.spotify.com',
    request_token_url=None,
    access_token_url='/api/token',
    authorize_url='https://accounts.spotify.com/authorize')


@blueprint.route('login')
def login():
    callback = url_for('spotify_controller.spotify_authorized', _external=True)
    return spotify.authorize(callback=callback)


@blueprint.route('login/authorized')
def spotify_authorized():
    resp = spotify.authorized_response()
Ejemplo n.º 16
0
def create_oauth_client(app):
    oauth = OAuth(app)
    app.secret_key = SECRET

    if not app.debug:
        app.config.update(
            SESSION_COOKIE_SECURE=True,
            SESSION_COOKIE_HTTPONLY=True,
            SESSION_COOKIE_SAMESITE='Lax',
        )

    remote = oauth.remote_app(
        "ok-server",  # Server Name
        consumer_key=CONSUMER_KEY,
        consumer_secret=SECRET,
        request_token_params={
            "scope": "email",
            "state": lambda: security.gen_salt(10)
        },
        base_url="https://okpy.org/api/v3/",
        request_token_url=None,
        access_token_method="POST",
        access_token_url="https://okpy.org/oauth/token",
        authorize_url="https://okpy.org/oauth/authorize",
    )

    def check_req(uri, headers, body):
        """ Add access_token to the URL Request. """
        if "access_token" not in uri and session.get("dev_token"):
            params = {"access_token": session.get("dev_token")[0]}
            url_parts = list(urllib.parse.urlparse(uri))
            query = dict(urllib.parse.parse_qsl(url_parts[4]))
            query.update(params)

            url_parts[4] = urllib.parse.urlencode(query)
            uri = urllib.parse.urlunparse(url_parts)
        return uri, headers, body

    remote.pre_request = check_req

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

    @app.route("/oauth/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 redirect("/")

    @app.route("/api/user", methods=["POST"])
    def client_method():
        if "dev_token" not in session:
            abort(401)
        token = session["dev_token"][0]
        r = requests.get(
            "https://okpy.org/api/v3/user/?access_token={}".format(token))
        if not r.ok:
            abort(401)
        return jsonify(r.json())

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

    app.remote = remote
Ejemplo n.º 17
0
def run_server(auction,
               mapping_expire_time,
               logger,
               timezone='Europe/Kiev',
               bids_form=BidsForm,
               bids_handler=BidsHandler,
               form_handler=form_handler,
               cookie_path=AUCTION_SUBPATH):
    app = initialize_application()
    add_url_rules(app)
    app.config.update(auction.worker_defaults)
    # Replace Flask custom logger
    app.logger_name = logger.name
    app._logger = logger
    app.config['timezone'] = tz(timezone)
    app.config['SESSION_COOKIE_PATH'] = '/{}/{}'.format(
        cookie_path, auction.context['auction_doc_id'])
    app.config['SESSION_COOKIE_NAME'] = 'auction_session'
    app.oauth = OAuth(app)
    app.gsm = getGlobalSiteManager()
    app.context = app.gsm.queryUtility(IContext)
    app.bids_form = bids_form
    app.bids_handler = bids_handler()
    app.form_handler = form_handler
    app.remote_oauth = app.oauth.remote_app(
        'remote',
        consumer_key=app.config['OAUTH_CLIENT_ID'],
        consumer_secret=app.config['OAUTH_CLIENT_SECRET'],
        request_token_params={'scope': 'email'},
        base_url=app.config['OAUTH_BASE_URL'],
        access_token_url=app.config['OAUTH_ACCESS_TOKEN_URL'],
        authorize_url=app.config['OAUTH_AUTHORIZE_URL'])

    @app.remote_oauth.tokengetter
    def get_oauth_token():
        return session.get('remote_oauth')

    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true'

    # Start server on unused port
    request_id = generate_request_id()

    listener = get_lisener(auction.worker_defaults["STARTS_PORT"],
                           host=auction.worker_defaults.get(
                               "WORKER_BIND_IP", ""))
    app.logger.info("Start server on {0}:{1}".format(*listener.getsockname()),
                    extra={"JOURNAL_REQUEST_ID": request_id})
    server = WSGIServer(listener,
                        app,
                        log=_LoggerStream(logger),
                        handler_class=AuctionsWSGIHandler)
    server.start()
    # Set mapping
    mapping_value = "http://{0}:{1}/".format(*listener.getsockname())
    create_mapping(auction.worker_defaults, auction.context['auction_doc_id'],
                   mapping_value)
    app.logger.info("Server mapping: {} -> {}".format(
        auction.context['auction_doc_id'], mapping_value, mapping_expire_time),
                    extra={"JOURNAL_REQUEST_ID": request_id})

    # Spawn events functionality
    spawn(
        push_timestamps_events,
        app,
    )
    spawn(
        check_clients,
        app,
    )
    return server
Ejemplo n.º 18
0
def create_oauth_client(
    app: flask.Flask,
    consumer_key,
    secret_key=None,
    success_callback=None,
    return_response=None,
):
    """Add Okpy OAuth for ``consumer_key`` to the current ``app``.

    Specifically, adds an endpoint ``/oauth/login`` that redirects to the Okpy
    login process, ``/oauth/authorized`` that receives the successful result
    of authentication, ``/api/user`` that acts as a test endpoint, and a
    :meth:`~flask_oauthlib.client.OAuthRemoteApp.tokengetter`.

    :param app: the app to add OAuth endpoints to
    :type app: ~flask.Flask

    :param consumer_key: the OAuth client consumer key
    :type consumer_key: str

    :param secret_key: the OAuth client secret, inferred using
        :func:`~common.rpc.secrets.get_secret` if omitted
    :type secret_key: str

    :param success_callback: an optional function to call upon login
    :type success_callback: func

    :param return_response: an optional function to send the OAuth response to
    :type return_response: func
    """
    oauth = OAuth(app)

    if os.getenv("ENV") == "prod":
        if secret_key is None:
            app.secret_key = get_secret(secret_name="OKPY_OAUTH_SECRET")
        else:
            app.secret_key = secret_key
    else:
        consumer_key = "local-dev-all"
        app.secret_key = "kmSPJYPzKJglOOOmr7q0irMfBVMRFXN"

    if not app.debug:
        app.config.update(
            SESSION_COOKIE_SECURE=True,
            SESSION_COOKIE_HTTPONLY=True,
            SESSION_COOKIE_SAMESITE="Lax",
        )

    remote = oauth.remote_app(
        "ok-server",  # Server Name
        consumer_key=consumer_key,
        consumer_secret=app.secret_key,
        request_token_params={
            "scope": "all",
            "state": lambda: security.gen_salt(10)
        },
        base_url="https://okpy.org/api/v3/",
        request_token_url=None,
        access_token_method="POST",
        access_token_url="https://okpy.org/oauth/token",
        authorize_url="https://okpy.org/oauth/authorize",
    )

    def check_req(uri, headers, body):
        """ Add access_token to the URL Request. """
        if "access_token" not in uri and session.get("access_token"):
            params = {"access_token": session.get("access_token")[0]}
            url_parts = list(urllib.parse.urlparse(uri))
            query = dict(urllib.parse.parse_qsl(url_parts[4]))
            query.update(params)

            url_parts[4] = urllib.parse.urlencode(query)
            uri = urllib.parse.urlunparse(url_parts)
        return uri, headers, body

    remote.pre_request = check_req

    @app.route("/oauth/login")
    def login():
        if app.debug:
            response = remote.authorize(
                callback=url_for("authorized", _external=True))
        else:
            response = remote.authorize(
                url_for("authorized", _external=True, _scheme="https"))
        return response

    @app.route("/oauth/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["access_token"] = (resp["access_token"], "")
            if return_response:
                return_response(resp)

        if success_callback:
            success_callback()

        target = session.get(REDIRECT_KEY)
        if target:
            session.pop(REDIRECT_KEY)
            return redirect(target)
        return redirect(url_for("index"))

    @app.route("/api/user", methods=["POST"])
    def client_method():
        if "access_token" not in session:
            abort(401)
        token = session["access_token"][0]
        r = requests.get(
            "https://okpy.org/api/v3/user/?access_token={}".format(token))
        if not r.ok:
            abort(401)
        return jsonify(r.json())

    @remote.tokengetter
    def get_oauth_token():
        return session.get("access_token")

    app.remote = remote
Ejemplo n.º 19
0
from flask import Flask, redirect, url_for, session, request, jsonify, Blueprint, flash
from flask_oauthlib.client import OAuth, OAuthException
import json
import kunjika

OA = Blueprint('oauth', __name__, template_folder='templates')

oauth = OAuth(kunjika)

google = oauth.remote_app(
    'google',
    consumer_key=kunjika.GOOGLE_ID,
    consumer_secret=kunjika.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',
)

facebook = oauth.remote_app(
    'facebook',
    consumer_key=kunjika.FACEBOOK_ID,
    consumer_secret=kunjika.FACEBOOK_SECRET,
    request_token_params={'scope': 'email'},
    base_url='https://graph.facebook.com',
    request_token_url=None,
    access_token_url='/oauth/access_token',
Ejemplo n.º 20
0
from __future__ import absolute_import

import os
import datetime
import flask
from gevent import pool
from flask_oauthlib.client import OAuth
from flask.ext import login

import twitter as twitter_api

from sirius.models import user as user_model
from sirius.models.db import db

blueprint = flask.Blueprint('twitter_oauth', __name__)
oauth_app = OAuth()

# TODO move the consumer_key/secret to flask configuration. The
# current key is a test app that redirects to 127.0.0.1:8000.
twitter = oauth_app.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=os.environ.get('TWITTER_CONSUMER_KEY',
                                'DdrpQ1uqKuQouwbCsC6OMA4oF'),
    consumer_secret=os.environ.get(
        'TWITTER_CONSUMER_SECRET',
        'S8XGuhptJ8QIJVmSuIk7k8wv3ULUfMiCh9x1b19PmKSsBh1VDM'),
)
Ejemplo n.º 21
0
def create_client(app):
    oauth = OAuth(app)

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

    @app.route('/')
    def index():
        if 'dev_token' in session:
            print(session.get('dev_token'))
            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():
        test = 'wushuyi'
        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
Ejemplo n.º 22
0
def init(api):
    if not has_streamlabs():
        log.info('Streamlabs support not set up')
        log.info(
            'Check out the install/config.example.ini and set up the client_id and client_secret under the [streamlabs] section'
        )
        return

    oauth = OAuth(api)

    streamlabs = oauth.remote_app(
        'streamlabs',
        consumer_key=app.bot_config['streamlabs']['client_id'],
        consumer_secret=app.bot_config['streamlabs']['client_secret'],
        base_url='https://streamlabs.com/api/v1.0/',
        request_token_params={
            'scope': [
                'donations.read',
                'donations.create',
            ],
        },
        request_token_url=None,
        access_token_headers={
            'User-agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
        },
        access_token_method='POST',
        access_token_url='https://streamlabs.com/api/v1.0/token',
        authorize_url='https://streamlabs.com/api/v1.0/authorize',
    )

    class StreamlabsIndex(Resource):
        def get(self):
            return redirect(url_for('streamlabslogin'))

    class StreamlabsLogin(Resource):
        def get(self):
            callback = url_for('streamlabsloginauthorized', _external=True)
            return streamlabs.authorize(callback=callback, state=uuid.uuid4())

    class StreamlabsLoginAuthorized(Resource):
        def __init__(self):
            super().__init__()

            self.parser = reqparse.RequestParser()
            self.parser.add_argument('error')
            self.parser.add_argument('error_description')

        def get(self):
            try:
                resp = streamlabs.authorized_response()
            except OAuthException:
                log.exception(
                    'Exception caught while authorizing with streamlabs')
                return 'error 1'
            except:
                log.exception(
                    'Unhandled exception caught while authorizing with streamlabs'
                )
                return 'error 2'

            args = self.parser.parse_args()

            if resp is None:
                log.warn('Access denied: reason={}, error={}'.format(
                    args['error'], args['error_description']))
                return args['error']

            if type(resp) is OAuthException:
                log.warn(resp.message)
                log.warn(resp.data)
                log.warn(resp.type)
                return 'error 3'

            session['streamlabs_token'] = (resp['access_token'], )

            me = streamlabs.get('user')

            log.info(me)
            log.info(me.data)
            log.info(me.data['twitch'])
            log.info(me.data['twitch']['name'])

            if me.data['twitch']['name'] in (
                    'pajlada', app.bot_config['main']['streamer']):
                password = pajbot.web.utils.create_pleblist_login(
                    app.bot_config)
                resp = flask.make_response(
                    flask.jsonify({'password': password}))
                resp.set_cookie('password', password)
                return resp

            return 'you can\'t use this pleblist'

    @streamlabs.tokengetter
    def get_streamlabs_oauth_token():
        return session.get('streamlabs_token')

    api.add_resource(StreamlabsIndex, '/streamlabs')
    api.add_resource(StreamlabsLogin, '/streamlabs/login')
    api.add_resource(StreamlabsLoginAuthorized, '/streamlabs/login/authorized')
Ejemplo n.º 23
0
import uuid

import flask
import requests
from flask import Flask
from flask_oauthlib.client import OAuth
import config
from rclone_client import Rclone

APP = Flask(__name__)

APP.debug = True
APP.secret_key = 'development'
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 hello_world():
    return 'Hello World!'

Ejemplo n.º 24
0
def create_oauth_client(app, name, **kwargs):
    """Helper function to create a OAuth2 client to test an OAuth2 provider."""
    blueprint = Blueprint('oauth2test', __name__, template_folder='templates')

    default = dict(
        consumer_key='confidential',
        consumer_secret='confidential',
        request_token_params={'scope': 'test:scope'},
        request_token_url=None,
        access_token_method='POST',
        access_token_url='/oauth/token',
        authorize_url='/oauth/authorize',
        content_type='application/json',
    )
    default.update(kwargs)

    oauth = OAuth(app)
    remote = oauth.remote_app(name, **default)

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

    @blueprint.route('/oauth2test/logout')
    def logout():
        session.pop('confidential_token', None)
        return "logout"

    @blueprint.route('/oauth2test/authorized')
    @remote.authorized_handler
    def authorized(resp):
        if resp is None:
            return 'Access denied: error=%s' % (request.args.get(
                'error', "unknown"))
        if isinstance(resp, dict) and 'access_token' in resp:
            session['confidential_token'] = (resp['access_token'], '')
            return jsonify(resp)
        return str(resp)

    def get_test(test_url):
        if 'confidential_token' not in session:
            abort(403)
        else:
            ret = remote.get(test_url)
            if ret.status != 200:
                return abort(ret.status)
            return ret.raw_data

    @blueprint.route('/oauth2test/test-ping')
    def test_ping():
        return get_test(url_for("invenio_oauth2server.ping"))

    @blueprint.route('/oauth2test/test-info')
    def test_info():
        return get_test(url_for('invenio_oauth2server.info'))

    @blueprint.route('/oauth2test/test-invalid')
    def test_invalid():
        return get_test(url_for('invenio_oauth2server.invalid'))

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

    app.register_blueprint(blueprint)

    return remote
Ejemplo n.º 25
0
def init(app):
    oauth = OAuth(app)

    # enables the usage of 127.0.0.1:7221 over http for OAuth purposes.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    twitch = oauth.remote_app(
        "twitch",
        consumer_key=app.bot_config["webtwitchapi"]["client_id"],
        consumer_secret=app.bot_config["webtwitchapi"]["client_secret"],
        request_token_params={"scope": "user_read"},
        base_url="{}/kraken/".format(os.environ.get("APIPROXY_HOST", "http://127.0.0.1:7221")),
        request_token_url=None,
        access_token_method="POST",
        access_token_url="https://id.twitch.tv/oauth2/token",
        authorize_url="https://id.twitch.tv/oauth2/authorize",
    )

    @app.route("/login")
    def login():
        callback_url = (
            app.bot_config["webtwitchapi"]["redirect_uri"]
            if "redirect_uri" in app.bot_config["webtwitchapi"]
            else url_for("authorized", _external=True)
        )
        state = request.args.get("n") or request.referrer or None
        return twitch.authorize(callback=callback_url, state=state)

    @app.route("/bot_login")
    def bot_login():
        callback_url = (
            app.bot_config["webtwitchapi"]["redirect_uri"]
            if "redirect_uri" in app.bot_config["webtwitchapi"]
            else url_for("authorized", _external=True)
        )
        state = request.args.get("n") or request.referrer or None
        return twitch.authorize(
            callback=callback_url,
            state=state,
            scope="user_read user:edit user:read:email channel:moderate chat:edit chat:read whispers:read whispers:edit",
            force_verify="true",
        )

    @app.route("/login/error")
    def login_error():
        return render_template("login_error.html")

    @app.route("/login/authorized")
    def authorized():
        try:
            resp = twitch.authorized_response()
        except OAuthException:
            log.exception("An exception was caught while authorizing")
            next_url = get_next_url(request, "state")
            return redirect(next_url)
        except:
            log.exception("Unhandled exception while authorizing")
            return render_template("login_error.html")

        if resp is None:
            if "error" in request.args and "error_description" in request.args:
                log.warning(
                    "Access denied: reason={}, error={}".format(
                        request.args["error"], request.args["error_description"]
                    )
                )
            next_url = get_next_url(request, "state")
            return redirect(next_url)
        elif type(resp) is OAuthException:
            log.warning(resp.message)
            log.warning(resp.data)
            log.warning(resp.type)
            next_url = get_next_url(request, "state")
            return redirect(next_url)
        session["twitch_token"] = (resp["access_token"],)
        me = twitch.get("user")
        level = 100
        with DBManager.create_session_scope() as db_session:
            db_user = db_session.query(User).filter_by(username=me.data["name"].lower()).one_or_none()
            if db_user:
                level = db_user.level
        session["user"] = {"username": me.data["name"], "username_raw": me.data["display_name"], "level": level}

        if me.data["name"].lower() == app.bot_config["main"]["nickname"].lower():
            redis = RedisManager.get()
            redis.set("{}:token".format(app.bot_config["main"]["nickname"]), json.dumps(resp))

        next_url = get_next_url(request, "state")
        return redirect(next_url)

    def get_next_url(request, key="n"):
        next_url = request.args.get(key, "/")
        if next_url.startswith("//"):
            return "/"
        return next_url

    @app.route("/logout")
    def logout():
        session.pop("twitch_token", None)
        session.pop("user", None)
        next_url = get_next_url(request)
        if next_url.startswith("/admin"):
            next_url = "/"
        return redirect(next_url)

    @twitch.tokengetter
    def get_twitch_oauth_token():
        return session.get("twitch_token")

    def change_twitch_header(uri, headers, body):
        auth = headers.get("Authorization")
        if auth:
            auth = auth.replace("Bearer", "OAuth")
            headers["Authorization"] = auth
        return uri, headers, body

    twitch.pre_request = change_twitch_header
Ejemplo n.º 26
0
import app.controllers.ajax_login_controller
import app.controllers.crowdsourcing_controller
import app.models.point
import app.models.powerline
import app.models.user
import app.permissions
from app import GisApp
from app.controllers.admin.transnset_logs_controller import TransnetLogsController
from app.controllers.admin.transnset_users_controller import TransnetUsersController
from app.controllers.contribution_controller import ContributionController

login_manager = LoginManager()
login_manager.init_app(GisApp)
login_manager.login_view = "/admin/login"

oauth = OAuth(GisApp)

google = oauth.remote_app(
    'google',
    consumer_key=GisApp.config.get('GOOGLE_CLIENT_ID'),
    consumer_secret=GisApp.config.get('GOOGLE_CLIENT_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',
)
Ejemplo n.º 27
0
def test_raise_app():
    app = Flask(__name__)
    oauth = OAuth(app)
    client = app.extensions['oauthlib.client']
    assert client.demo.name == 'dev'
Ejemplo n.º 28
0
def init(app):
    oauth = OAuth(app)

    twitch = oauth.remote_app(
        "twitch",
        consumer_key=app.bot_config["twitchapi"]["client_id"],
        consumer_secret=app.bot_config["twitchapi"]["client_secret"],
        request_token_params={"scope": "user_read"},
        base_url="https://api.twitch.tv/kraken/",
        request_token_url=None,
        access_token_method="POST",
        access_token_url="https://id.twitch.tv/oauth2/token",
        authorize_url="https://id.twitch.tv/oauth2/authorize",
    )

    @app.route("/login")
    def login():
        callback_url = (app.bot_config["twitchapi"]["redirect_uri"]
                        if "redirect_uri" in app.bot_config["twitchapi"] else
                        url_for("authorized", _external=True))
        state = request.args.get("n") or request.referrer or None
        return twitch.authorize(callback=callback_url, state=state)

    @app.route("/bot_login")
    def bot_login():
        callback_url = (app.bot_config["twitchapi"]["redirect_uri"]
                        if "redirect_uri" in app.bot_config["twitchapi"] else
                        url_for("authorized", _external=True))
        state = request.args.get("n") or request.referrer or None
        return twitch.authorize(
            callback=callback_url,
            state=state,
            scope=
            ("user_read user:edit user:read:email channel:moderate chat:edit "
             + "chat:read whispers:read whispers:edit channel_editor"),
            force_verify="true",
        )

    streamer_scopes = ["user_read", "channel:read:subscriptions"]
    """Request these scopes on /streamer_login"""

    @app.route("/streamer_login")
    def streamer_login():
        callback_url = (app.bot_config["twitchapi"]["redirect_uri"]
                        if "redirect_uri" in app.bot_config["twitchapi"] else
                        url_for("authorized", _external=True))
        state = request.args.get("n") or request.referrer or None
        return twitch.authorize(callback=callback_url,
                                state=state,
                                scope=" ".join(streamer_scopes),
                                force_verify="true")

    @app.route("/login/error")
    def login_error():
        return render_template("login_error.html")

    @app.route("/login/authorized")
    def authorized():
        try:
            resp = twitch.authorized_response()
        except OAuthException:
            log.exception("An exception was caught while authorizing")
            next_url = get_next_url(request, "state")
            return redirect(next_url)
        except:
            log.exception("Unhandled exception while authorizing")
            return render_template("login_error.html")

        if resp is None:
            if "error" in request.args and "error_description" in request.args:
                log.warning("Access denied: reason={}, error={}".format(
                    request.args["error"], request.args["error_description"]))
            next_url = get_next_url(request, "state")
            return redirect(next_url)
        elif type(resp) is OAuthException:
            log.warning(resp.message)
            log.warning(resp.data)
            log.warning(resp.type)
            next_url = get_next_url(request, "state")
            return redirect(next_url)
        session["twitch_token"] = (resp["access_token"], )
        me = twitch.get("user",
                        headers={"Accept": "application/vnd.twitchtv.v5+json"})
        level = 100
        with DBManager.create_session_scope() as db_session:
            db_user = db_session.query(User).filter_by(
                username=me.data["name"].lower()).one_or_none()
            if db_user:
                level = db_user.level
        session["user"] = {
            "username": me.data["name"],
            "username_raw": me.data["display_name"],
            "level": level
        }

        if me.data["name"].lower() == app.bot_config["main"]["nickname"].lower(
        ):
            redis = RedisManager.get()
            bot_id = me.data["_id"]
            token_json = UserAccessToken.from_api_response(resp).jsonify()
            redis.set("authentication:user-access-token:{}".format(bot_id),
                      json.dumps(token_json))
            log.info("Successfully updated bot token in redis")

        # streamer login
        if me.data["name"].lower() == app.bot_config["main"]["streamer"].lower(
        ):
            # there's a good chance the streamer will later log in using the normal login button.
            # we only update their access token if the returned scope containes the special scopes requested
            # in /streamer_login
            if set(resp["scope"]) != set(streamer_scopes):
                log.info(
                    "Streamer logged in but not all scopes present, will not update streamer token"
                )
            else:
                redis = RedisManager.get()
                streamer_id = me.data["_id"]
                token_json = UserAccessToken.from_api_response(resp).jsonify()
                redis.set(
                    "authentication:user-access-token:{}".format(streamer_id),
                    json.dumps(token_json))
                log.info("Successfully updated streamer token in redis")

        next_url = get_next_url(request, "state")
        return redirect(next_url)

    def get_next_url(request, key="n"):
        next_url = request.args.get(key, "/")
        if next_url.startswith("//"):
            return "/"
        return next_url

    @app.route("/logout")
    def logout():
        session.pop("twitch_token", None)
        session.pop("user", None)
        next_url = get_next_url(request)
        if next_url.startswith("/admin"):
            next_url = "/"
        return redirect(next_url)

    @twitch.tokengetter
    def get_twitch_oauth_token():
        return session.get("twitch_token")

    def change_twitch_header(uri, headers, body):
        auth = headers.get("Authorization")
        if auth:
            auth = auth.replace("Bearer", "OAuth")
            headers["Authorization"] = auth
        return uri, headers, body

    twitch.pre_request = change_twitch_header
Ejemplo n.º 29
0
from flask import request, url_for, redirect, session, jsonify
from flask_oauthlib.client import OAuth

from mindmap import app

oauth = OAuth(app)
weibo = oauth.remote_app(
    'weibo',
    consumer_key='909122383',
    consumer_secret='2cdc60e5e9e14398c1cbdf309f2ebd3a',
    request_token_params={'scope': 'email,statuses_to_me_read'},
    base_url='https://api.weibo.com/2/',
    authorize_url='https://api.weibo.com/oauth2/authorize',
    request_token_url=None,
    access_token_method='POST',
    access_token_url='https://api.weibo.com/oauth2/access_token',
    # since weibo's response is a shit, we need to force parse the content
    content_type='application/json',
)


@app.route('/')
def index():
    if 'oauth_token' in session:
        # access_token = session['oauth_token'][0]
        resp = weibo.get('statuses/home_timeline.json')
        return jsonify(resp.data)
    return redirect(url_for('login'))

Ejemplo n.º 30
0
# pylint: disable=R1714,C0121
import os
import json
from flask import render_template, request, session, url_for
from flask_oauthlib.client import OAuth, redirect
from gradGyde import app
from .db_helper import (add_aoc, assign_aoc, create_class, delete_aoc,
                        delete_class, delete_class_taken, delete_pref_aoc,
                        get_all_classes_json, get_all_requirements_json,
                        get_all_tags, get_aoc_by_id, get_aoc_json,
                        get_class_by_id, get_classes, get_classes_taken,
                        get_classes_taken_json, get_lacs_json, get_user,
                        make_user, search_aoc_json, search_classes_json,
                        take_class, take_lac_default, update_user)
from .models import UserType, SemesterType
OAUTH = OAuth()
GOOGLE = OAUTH.remote_app(
    'google',
    consumer_key=os.getenv('GOOGLE_CONS_KEY'),
    consumer_secret=os.getenv('GOOGLE_CONS_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_token():
    return session.get("google_token")