2nd pass on oauth, making more generic

This commit is contained in:
Matthew Scragg 2015-10-14 23:08:56 -05:00
parent 2eaf09dc78
commit 838eb3cb06
2 changed files with 27 additions and 37 deletions

View file

@ -5,38 +5,28 @@ from ..models import BaseUser
oauth = OAuth()
users = {}
class OAuthUser(BaseUser):
# OAuth remote app
remote_app = None
class TwitterUser(OAuthUser):
def __init__(self, id_, username, email=None):
self.id = id_
self.username = username
self.email = email
@classmethod
def app(cls):
if cls.remote_app:
return cls.remote_app
cls.remote_app = oauth.remote_app(
'twitter',
providers = {
'twitter': {
'oauth': dict(
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=config.OAUTH['twitter']['key'],
consumer_secret=config.OAUTH['twitter']['secret'])
return cls.remote_app
authorize_url='https://api.twitter.com/oauth/authenticate')
}
}
@staticmethod
def load_user(*args, **kwargs):
return TwitterUser(args[0])
class User(BaseUser):
@classmethod
def get_app(cls, provider):
return oauth.remote_app(provider,
consumer_key=config.OAUTH.get(provider, {}).get('key'),
consumer_secret=config.OAUTH.get(provider, {}).get('secret'),
**providers[provider]['oauth'])
@staticmethod
def login_form():
return render_template('auth/oauth/twitter.html')
pass

View file

@ -1,5 +1,5 @@
from flask import Blueprint, url_for, request, flash, redirect, session
from .models import TwitterUser
from .models import User
blueprint = Blueprint('auth.oauth', __name__)
@ -8,23 +8,23 @@ def oauth_failed(next_url):
flash('You denied the request to sign in.')
return redirect(next_url)
@blueprint.route("/login/twitter")
def login_twitter():
return TwitterUser.app().authorize(callback=url_for('twitter_callback',
@blueprint.route("/login/oauth/<provider>")
def oauth_login(provider):
return User.get_app(provider).authorize(callback=url_for('oauth_callback', provider=provider,
next=request.args.get('next') or request.referrer or None))
@blueprint.route('/login/twitter/callback')
def twitter_callback():
@blueprint.route('/login/oauth/<provider>/callback')
def oauth_callback(provider):
next_url = request.args.get('next') or url_for('index')
resp = TwitterUser.app().authorized_response()
resp = User.get_app(provider).authorized_response()
if resp is None:
return oauth_failed(next_url)
session['twitter_token'] = (
session[provider + '_token'] = (
resp['oauth_token'],
resp['oauth_token_secret']
)
session['twitter_user'] = resp['screen_name']
flash('You were signed in as %s' % resp['screen_name'])
return redirect(next_url)