Skip to content

Instantly share code, notes, and snippets.

@tance77
Last active January 17, 2017 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tance77/73629bb73a37cabbbfa4662ecd95617a to your computer and use it in GitHub Desktop.
Save tance77/73629bb73a37cabbbfa4662ecd95617a to your computer and use it in GitHub Desktop.
This is my attempt of authenticating a user with twitch and making a request on their behalf
from flask import Flask, render_template, request, redirect, session, json, url_for, jsonify
from flask_oauthlib.client import OAuth
from config import Config
app = Flask(__name__)
# Debug info
app.debug = True
f = file('config.json')
cfg = Config(f)
app.secret_key = cfg.config.app.secret
# OAuth Config
oauth = OAuth(app)
twitch = oauth.remote_app('twitch',
base_url='https://api.twitch.tv/kraken/',
request_token_url=None,
access_token_method='POST',
access_token_url='oauth2/token/',
authorize_url='oauth2/authorize/',
consumer_key=cfg.config.twitch.dev_client_id,
consumer_secret=cfg.config.twitch.dev_secret_key,
request_token_params={'scope': [
'user_read',
'channel_subscriptions',
'channel_editor',
'channel_commercial'
]},
)
def change_twitch_header(uri, headers, body):
auth = headers.get('Authorization')
if auth:
auth = auth.replace('Bearer', 'OAuth2')
headers['Authorization'] = auth
if app.debug:
headers['Client-ID'] = cfg.config.twitch.dev_client_id
else:
headers['Client-ID'] = cfg.config.twitch.client_id
return uri, headers, body
twitch.pre_request = change_twitch_header
@app.route("/login/")
def login():
from app import twitch
return twitch.authorize(callback=url_for('user.authorized', _external=True))
@app.route("/login/authorized/")
def authorized():
from app import twitch, cfg, mongo
from flask_oauthlib.client import OAuthException
resp = twitch.authorized_response()
if resp is None:
return 'Access denied: reason=%s error=%s' % (
request.args['error'],
request.args['error_description']
)
if isinstance(resp, OAuthException):
return 'Access denied: %s' % resp.message
session['twitch_token'] = (resp['access_token'], '')
me = twitch.get('channel/')
session['twitch_name'] = (me.data['name'])
return redirect(url_for('dashboard_page.dashboard', username=me.data['name']))
@app.route("/logout/")
def logout():
session.pop('twitch_token', None)
session.pop('twitch_name')
resp = make_response(redirect(url_for('landing_page.index')))
resp.set_cookie('twitch_name', '', expires=0)
return resp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment