From 9c86da51d1618e056b1b0912d11b5d2614eaed77 Mon Sep 17 00:00:00 2001 From: Phillip Ferentinos Date: Tue, 4 Jul 2023 18:56:25 -0500 Subject: [PATCH] feat(twitter): update twitter auth to use oauth2 flow --- .dockerignore | 4 + .gitignore | 3 +- README.md | 9 +- pyproject.toml | 6 +- sirius/config.py | 40 +++++---- sirius/web/twitter.py | 185 ++++++++++++++++++++---------------------- 6 files changed, 127 insertions(+), 120 deletions(-) create mode 100644 .dockerignore diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e6f9255 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +.circleci +notes +docker-compose* +*.md diff --git a/.gitignore b/.gitignore index 4123d6a..efd80eb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # Custom venv/ -.env +.env* +!.env.example certs/ diff --git a/README.md b/README.md index 8fad313..97ec8d4 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ docker-compose -f docker-compose.yml -f docker-compose.development.yml up Or if you have your own database, you can configure the `DEV_DATABASE_URL` environment variable in `.env`, and then simply run: -``` +```sh docker-compose up ``` @@ -57,9 +57,10 @@ docker-compose up The server can be configured with the following variables: -``` -TWITTER_CONSUMER_KEY=... -TWITTER_CONSUMER_SECRET=... +```properties +TWITTER_OAUTH_CLIENT_KEY=... +TWITTER_OAUTH_CLIENT_SECRET=... +OAUTH_REDIRECT_URI=... FLASK_CONFIG=... DATABASE_URL=... ``` diff --git a/pyproject.toml b/pyproject.toml index b13751a..8c961d9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,6 @@ dependencies = [ "Flask==1.1.1", "Flask-Bootstrap==3.3.7.1", "Flask-Cors==3.0.8", - "Flask-Dance==2.2.0", "Flask-Login==0.4.1", "Flask-Migrate==2.5.2", "Flask-SQLAlchemy==2.4.0", @@ -35,13 +34,12 @@ dependencies = [ "httplib2==0.13.1", "itsdangerous==1.1.0", "nose==1.3.7", - "oauth2==1.9.0.post1", - "oauthlib==3.1.0", + "oauthlib==3.2.2", "psycopg2-binary==2.8.3", "pycrypto==2.6.1", "redis==3.3.8", "requests==2.22.0", - "requests-oauthlib==1.2.0", + "requests-oauthlib==1.3.1", "selenium==3.141.0", "six==1.12.0", "twitter==1.18.0", diff --git a/sirius/config.py b/sirius/config.py index 99ad23d..0b1d417 100755 --- a/sirius/config.py +++ b/sirius/config.py @@ -1,41 +1,52 @@ import os + basedir = os.path.abspath(os.path.dirname(__file__)) class Config: - SECRET_KEY = os.environ.get('SECRET_KEY') or 'this is the lp2 secret' + SECRET_KEY = os.environ.get("SECRET_KEY") or "this is the lp2 secret" SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_TRACK_MODIFICATIONS = False # printer not seen for 60 seconds: Mark offline. PRINTER_OFFLINE_CUTOFF_SECONDS = 60 + TWITTER_OAUTH_CLIENT_KEY = os.getenv("TWITTER_OAUTH_CLIENT_KEY") + TWITTER_OAUTH_CLIENT_SECRET = os.getenv("TWITTER_OAUTH_CLIENT_SECRET") + OAUTH_REDIRECT_URI = os.getenv("OAUTH_REDIRECT_URI") @staticmethod def init_app(app): pass + class TestConfig(Config): DEBUG = False - SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ - 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite') + SQLALCHEMY_DATABASE_URI = os.environ.get( + "DATABASE_URL" + ) or "sqlite:///" + os.path.join(basedir, "data-dev.sqlite") TESTING = True WTF_CSRF_ENABLED = False LOGIN_DISABLED = False + class DevelopmentConfig(Config): DEBUG = True - SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ - 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite') + SQLALCHEMY_DATABASE_URI = os.environ.get( + "DATABASE_URL" + ) or "sqlite:///" + os.path.join(basedir, "data-dev.sqlite") + class ProductionConfig(Config): - SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ - 'sqlite:///' + os.path.join(basedir, 'data.sqlite') + SQLALCHEMY_DATABASE_URI = os.environ.get( + "DATABASE_URL" + ) or "sqlite:///" + os.path.join(basedir, "data.sqlite") @classmethod def init_app(cls, app): Config.init_app(app) + class HerokuConfig(ProductionConfig): - SSL_DISABLE = bool(os.environ.get('SSL_DISABLE')) + SSL_DISABLE = bool(os.environ.get("SSL_DISABLE")) DEBUG = True @classmethod @@ -44,21 +55,22 @@ class HerokuConfig(ProductionConfig): # handle proxy server headers from werkzeug.contrib.fixers import ProxyFix + app.wsgi_app = ProxyFix(app.wsgi_app) # log to stderr import logging from logging import StreamHandler + file_handler = StreamHandler() file_handler.setLevel(logging.WARNING) app.logger.addHandler(file_handler) config = { - 'development': DevelopmentConfig, - 'production': ProductionConfig, - 'heroku': HerokuConfig, - 'test': TestConfig, - - 'default': DevelopmentConfig + "development": DevelopmentConfig, + "production": ProductionConfig, + "heroku": HerokuConfig, + "test": TestConfig, + "default": DevelopmentConfig, } diff --git a/sirius/web/twitter.py b/sirius/web/twitter.py index 5156e12..f144b64 100644 --- a/sirius/web/twitter.py +++ b/sirius/web/twitter.py @@ -1,51 +1,75 @@ -import os -import datetime -import flask import logging -from gevent import pool + +from requests_oauthlib import OAuth2Session +import requests +import flask import flask_login as login -from flask_dance.consumer import oauth_authorized, oauth_error -from flask_dance.contrib.twitter import make_twitter_blueprint, twitter -import twitter as twitter_api from sirius.models import user as user_model from sirius.models.db import db logger = logging.getLogger(__name__) -api_key=os.environ.get('TWITTER_CONSUMER_KEY', 'DdrpQ1uqKuQouwbCsC6OMA4oF') -api_secret=os.environ.get('TWITTER_CONSUMER_SECRET', 'S8XGuhptJ8QIJVmSuIk7k8wv3ULUfMiCh9x1b19PmKSsBh1VDM') +blueprint = flask.Blueprint("twitter", __name__) + +auth_url = "https://twitter.com/i/oauth2/authorize" +token_url = "https://api.twitter.com/2/oauth2/token" + +scopes = ["tweet.read", "users.read", "offline.access"] + +oauth_session: OAuth2Session +code_challenge: str +code_verifier: str -# TODO move the consumer_key/secret to flask configuration. The -# current key is a test app that redirects to 127.0.0.1:8000. -blueprint = make_twitter_blueprint( - api_key=api_key, - api_secret=api_secret, -) -# @blueprint.route('/twitter/login') -# def twitter_login(): -# # Clear token, see https://github.com/mitsuhiko/flask-oauth/issues/48: -# flask.session.pop('twitter_token', None) -# flask.session.pop('twitter_screen_name', None) +def make_token(): + global oauth_session + global code_verifier + global code_challenge + + client_id = flask.current_app.config.get("TWITTER_OAUTH_CLIENT_KEY") + redirect_uri = flask.current_app.config.get("OAUTH_REDIRECT_URI") + + oauth_session = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scopes) + code_verifier = oauth_session._client.create_code_verifier(43) + code_challenge = oauth_session._client.create_code_challenge( + code_verifier, code_challenge_method="S256" + ) + + +def get_self(): + access_token = flask.session.get("twitter_token").get("access_token") + resp = requests.get( + url="https://api.twitter.com/2/users/me", + headers={ + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + }, + ) + if not resp.ok: + rule = flask.request.url_rule + msg = f"Error from {rule.endpoint}!" + logger.debug(msg) + flask.flash(msg, category="error") + return flask.redirect("/") -# return twitter.authorize(callback=flask.url_for('twitter_oauth.oauth_authorized', -# next=flask.request.args.get('next') or flask.request.referrer or None)) + return resp.json().get("data") -@blueprint.route('/twitter/logout') + +@blueprint.route("/twitter/logout") def twitter_logout(): - flask.session.pop('user_id', None) - flask.flash('You were signed out') - return flask.redirect('/') + flask.session.pop("user_id", None) + flask.flash("You were signed out") + return flask.redirect("/") -def process_authorization(token, token_secret, screen_name, next_url): +def process_authorization(token, next_url): """Process the incoming twitter oauth data. Validation has already succeeded at this point and we're just doing the book-keeping.""" - flask.session['twitter_token'] = (token, token_secret) - flask.session['twitter_screen_name'] = screen_name - + flask.session["twitter_token"] = token + screen_name = get_self().get("username") + flask.session["twitter_screen_name"] = screen_name oauth = user_model.TwitterOAuth.query.filter_by( screen_name=screen_name, ).first() @@ -60,15 +84,10 @@ def process_authorization(token, token_secret, screen_name, next_url): oauth = user_model.TwitterOAuth( user=new_user, screen_name=screen_name, - token=token, - token_secret=token_secret, - last_friend_refresh=datetime.datetime.utcnow(), + token=token.get("access_token"), + token_secret=token.get("access_token"), ) - # Fetch friends list from twitter. TODO: error handling. - friends = get_friends(new_user) - oauth.friends = friends - db.session.add(new_user) db.session.add(oauth) db.session.commit() @@ -80,68 +99,40 @@ def process_authorization(token, token_secret, screen_name, next_url): return flask.redirect(next_url) -def get_friends(user): - return get_friends_using_tokens(oauth_token=user.twitter_oauth.token, oauth_token_secret=user.twitter_oauth.token_secret) - -def get_friends_using_tokens(oauth_token, oauth_token_secret): - api = twitter_api.Twitter(auth=twitter_api.OAuth( - oauth_token, - oauth_token_secret, - api_key, - api_secret, - )) - # Twitter allows lookup of 100 users at a time so we need to - # chunk: - chunk = lambda l, n: [l[x:x+n] for x in range(0, len(l), n)] - friend_ids = list(api.friends.ids()['ids']) - - greenpool = pool.Pool(4) - - # Look up in parallel. Note that twitter has pretty strict 15 - # requests/second rate limiting. - friends = [] - for result in greenpool.imap( - lambda ids: api.users.lookup(user_id=','.join(str(id) for id in ids)), - chunk(friend_ids, 100)): - for r in result: - friends.append(user_model.Friend( - screen_name=r['screen_name'], - name=r['name'], - profile_image_url=r['profile_image_url'], - )) - - return sorted(friends) - - -@oauth_authorized.connect_via(blueprint) -def twitter_logged_in(blueprint, token): - # TODO: I think this comes via sesstion these days? - next_url = flask.request.args.get('next') or '/' +@blueprint.route("/twitter") +def twitter_logged_in(): + make_token() - if token is None: - flask.flash("Twitter didn't authorize our sign-in request.", category="error") + authorization_url, state = oauth_session.authorization_url( + auth_url, code_challenge=code_challenge, code_challenge_method="S256" + ) + flask.session["oauth_state"] = state + return flask.redirect(authorization_url) + + +@blueprint.route("/twitter/authorized", methods=["GET"]) +def twitter_callback(): + client_secret = flask.current_app.config.get("TWITTER_OAUTH_CLIENT_SECRET") + next_url = "/" + code = flask.request.args.get("code") + error = flask.request.args.get("error") + if error is not None: + logger.debug("twitter_callback: we got a problem") + rule = flask.request.url_rule + msg = f"OAuth error from {rule.endpoint}! message={error}" + logger.debug(msg) + flask.flash(msg, category="error") return flask.redirect(next_url) - process_authorization( - token['oauth_token'], - token['oauth_token_secret'], - token['screen_name'], - next_url, + token = oauth_session.fetch_token( + token_url=token_url, + client_secret=client_secret, + code_verifier=code_verifier, + code=code, ) - return False - -# notify on OAuth provider error -@oauth_error.connect_via(blueprint) -def twitter_error(blueprint, message, response): - logger.debug("we got a problem") - msg = ( - "OAuth error from {name}! " - "message={message} response={response}" - ).format( - name=blueprint.name, - message=message, - response=response, - ) - logger.debug(msg) - flask.flash(msg, category="error") \ No newline at end of file + if token is None: + flask.flash("Twitter didn't authorize our sign-in request.", category="error") + return flask.redirect(next_url) + + return process_authorization(token, next_url) -- 2.47.3