2015-10-21 01:18:43 +03:00
|
|
|
from flask import Blueprint, url_for, request, flash, redirect, session, current_app
|
2015-10-15 07:08:56 +03:00
|
|
|
from .models import User
|
2015-10-14 06:52:30 +03:00
|
|
|
|
|
|
|
blueprint = Blueprint('auth.oauth', __name__)
|
|
|
|
|
|
|
|
|
|
|
|
def oauth_failed(next_url):
|
2015-10-15 01:36:22 +03:00
|
|
|
flash('You denied the request to sign in.')
|
2015-10-14 06:52:30 +03:00
|
|
|
return redirect(next_url)
|
|
|
|
|
2015-10-15 07:08:56 +03:00
|
|
|
|
|
|
|
@blueprint.route("/login/oauth/<provider>")
|
2015-10-16 01:36:47 +03:00
|
|
|
def login(provider):
|
2015-10-26 23:47:32 +02:00
|
|
|
return User.get_app(provider).authorize(callback=url_for('auth.oauth.callback', provider=provider, _external=True))
|
2015-10-14 06:52:30 +03:00
|
|
|
|
2015-10-15 07:08:56 +03:00
|
|
|
|
|
|
|
@blueprint.route('/login/oauth/<provider>/callback')
|
2015-10-16 01:36:47 +03:00
|
|
|
def callback(provider):
|
2015-10-21 17:09:42 +03:00
|
|
|
next_url = request.args.get('next') or url_for(current_app.config['ROOT_ENDPOINT'])
|
2015-10-16 01:36:47 +03:00
|
|
|
try:
|
2015-11-13 01:19:26 +02:00
|
|
|
remote_app = User.get_app(provider)
|
|
|
|
resp = remote_app.authorized_response()
|
2015-10-16 01:36:47 +03:00
|
|
|
if resp is None:
|
|
|
|
flash('You denied the request to sign in.', 'error')
|
|
|
|
flash('Reason: ' + request.args['error_reason'] +
|
|
|
|
' ' + request.args['error_description'], 'error')
|
|
|
|
return redirect(next_url)
|
|
|
|
except Exception as e:
|
|
|
|
flash('Access denied: %s' % e.message)
|
|
|
|
return redirect(next_url)
|
2015-10-14 06:52:30 +03:00
|
|
|
|
2015-11-14 01:03:58 +02:00
|
|
|
oauth_token = resp.get(User.get_provider_value(provider, 'token_name'))
|
|
|
|
session[provider + "_token"] = (oauth_token, '')
|
2015-11-13 01:19:26 +02:00
|
|
|
profile = User.get_provider_value(provider, 'profile')
|
2015-11-14 01:25:55 +02:00
|
|
|
data = remote_app.get(profile).data if profile else resp
|
2015-10-14 06:52:30 +03:00
|
|
|
|
2015-11-14 01:03:58 +02:00
|
|
|
User.auth(provider, data, oauth_token)
|
2015-10-22 01:34:20 +03:00
|
|
|
|
2015-10-15 01:36:22 +03:00
|
|
|
return redirect(next_url)
|