from requests_oauthlib import OAuth1Session from flask import Blueprint, Response, current_app, request, jsonify from ayct_backend.twitter.models import * from ayct_backend.firebase import verify_token twitter = Blueprint('twitter', __name__) @twitter.route('/account', methods=['GET']) def get_twitter_accounts(): decoded_token = verify_token(request.headers) if not decoded_token: return "Not authorised!", 401 user_id = decoded_token['uid'] twitter_accounts = TwitterAccount.query.filter_by(user_id=user_id) accounts = [] for account in twitter_accounts: account_data = {} account_data['twitter_account_id'] = account.twitter_account_id account_data['username'] = account.username accounts.append(account_data) return jsonify({ "twitter_accounts": accounts }), 200 @twitter.route('/account', methods=['POST']) def add_twitter_account(): decoded_token = verify_token(request.headers) if not decoded_token: return "Not authorised!", 401 user_id = decoded_token['uid'] content_type = request.headers.get('Content-Type') if (content_type == 'application/json'): json = request.json if not json['veryfier'] or not json['oauth_token'] or not json['oauth_token_secret']: return "Invalid request!", 400 else: consumer_key = current_app.config["TWITTER_CONSUMER_KEY"] consumer_secret = current_app.config["TWITTER_CONSUMER_SECERT"] access_token_url = "https://api.twitter.com/oauth/access_token" oauth = OAuth1Session( consumer_key, client_secret=consumer_secret, resource_owner_key=json['oauth_token'], resource_owner_secret=json['oauth_token_secret'], verifier=json['veryfier'], ) oauth_tokens = oauth.fetch_access_token(access_token_url) new_twitter_account = TwitterAccount( user_id = user_id, twitter_account_id = oauth_tokens['user_id'], username = oauth_tokens['screen_name'], access_token = oauth_tokens['oauth_token'], access_token_secret = oauth_tokens['oauth_token_secret'] ) twitter_db.session.add(new_twitter_account) twitter_db.session.commit() return "Twitter account succesfully added.", 201 else: return "Content-type not supported!", 400