Eos/eosweb/redditauth/main.py

75 lines
2.5 KiB
Python

# Eos - Verifiable elections
# Copyright © 2017-18 RunasSudo (Yingtong Li)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from authlib.integrations.flask_client import OAuth
import flask
from eos.redditauth.election import *
import base64
import uuid
blueprint = flask.Blueprint('eosweb.redditauth', __name__)
app = None
oauth = None
@blueprint.record
def reddit_register(setup_state):
global app, oauth
app = setup_state.app
oauth = OAuth(app)
oauth.register('reddit',
#request_token_url=None,
authorize_url='https://www.reddit.com/api/v1/authorize.compact',
authorize_params={'duration': 'temporary', 'scope': 'identity'},
access_token_url='https://www.reddit.com/api/v1/access_token',
access_token_method='POST',
access_token_headers={
'Authorization': 'Basic ' + base64.b64encode('{}:{}'.format(app.config['REDDIT_OAUTH_CLIENT_ID'], app.config['REDDIT_OAUTH_CLIENT_SECRET']).encode('ascii')).decode('ascii'),
'User-Agent': app.config['REDDIT_USER_AGENT']
},
client_id=app.config['REDDIT_OAUTH_CLIENT_ID'],
client_secret=app.config['REDDIT_OAUTH_CLIENT_SECRET'],
fetch_token=lambda: flask.session.get('user').oauth_token
)
@blueprint.route('/auth/reddit/login')
def reddit_login():
return oauth.reddit.authorize_redirect(redirect_uri=app.config['BASE_URI'] + flask.url_for('eosweb.redditauth.reddit_oauth_authorized'), state=str(uuid.uuid4()))
@blueprint.route('/auth/reddit/oauth_callback')
def reddit_oauth_authorized():
try:
token = oauth.reddit.authorize_access_token()
except:
# Request denied
return flask.redirect(flask.url_for('login_cancelled'))
user = RedditUser()
user.oauth_token = token
flask.session['user'] = user
me = oauth.reddit.get('https://oauth.reddit.com/api/v1/me', headers={
'User-Agent': app.config['REDDIT_USER_AGENT']
})
user.username = me.json()['name']
return flask.redirect(flask.url_for('login_complete'))