#!/usr/bin/env python
import os
import urllib
import requests
import json
import redis
from flask import Flask, g, request, redirect, url_for, render_template, session, jsonify

application = Flask(__name__)

REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379")
API_ROOT = 'https://bbs.net9.org:8080'

application.secret_key = os.urandom(24)


@application.before_request
def before_request():
    g.db = redis.from_url(REDIS_URL)


@application.route('/auth')
def auth():
    params = {'redirect_uri': url_for('auth', _external=True),
              'grant_type': 'authorization_code',
              'code': request.args['code'],
              'client_id': g.db.hget('config', 'client_id'),
              'client_secret': g.db.hget('config', 'client_secret')}
    r = requests.get(API_ROOT + '/auth/token', params=params)
    token_json = r.json()
    params = {'session': token_json['access_token']}
    r = requests.get(API_ROOT + '/user/detail', params=params)
    user_id = r.json().get("userid")
    if user_id:
        g.db.hset("user_token", user_id, json.dumps(token_json))
        session['logged_in'] = True
        session['user_id'] = user_id
        return redirect(url_for('index'))
    return jsonify(r.text)


@application.route('/', methods=['GET', 'POST'])
def index():
    error = None
    if g.db.hexists('config', 'client_id') and g.db.hexists('config', 'client_secret'):
        if not session.get("logged_in"):
            query = [("redirect_uri", url_for('auth', _external=True)),
                     ("response_type", "code"),
                     ("client_id", g.db.hget('config', 'client_id'))]
            return redirect(API_ROOT + '/auth/auth?' + urllib.urlencode(query))
        user_id = session['user_id']
        if request.method == 'POST':
            g.db.hset('user_maker_key', user_id, request.form['maker_key'])
        maker_key = g.db.hget('user_maker_key', user_id)
        return render_template("index.html", error=error, user_id=user_id, maker_key=maker_key)
    else:
        return redirect(url_for('config'))


@application.route('/config', methods=['GET', 'POST'])
def config():
    error = None
    if request.method == 'POST':
        g.db.hsetnx("config", "client_id", request.form['client_id'])
        g.db.hsetnx("config", "client_secret", request.form['client_secret'])
        return redirect(url_for('index'))
    else:
        return render_template('config.html', error=error)


if __name__ == '__main__':
    application.debug = True
    application.run()

@@ -80,16 +80,28 @@
 t redis%0A
+import uuid%0A
 from fla
@@ -168,17 +168,8 @@
 ate,
- session,
  jso
@@ -1098,72 +1098,127 @@
     
-session%5B'logged_in'%5D = True%0A        session%5B'user_id'%5D =
+c_uuid = uuid.uuid4()%0A        resp = redirect(url_for('index'))%0A        g.db.setex(%22c_uuid_%22 + c_uuid, 2592000,
  user_id
 %0A   
@@ -1213,16 +1213,17 @@
  user_id
+)
 %0A       
@@ -1229,39 +1229,59 @@
   re
-turn redirect(url_for('index'))
+sp.set_cookie(%22c_uuid%22, c_uuid)%0A        return resp
 %0A   
@@ -1485,39 +1485,162 @@
     
-if not session.get(%22logged_in%22)
+user_id = None%0A        c_uuid = request.cookies.get(%22c_uuid%22)%0A        if c_uuid:%0A            user_id = g.db.get(%22c_uuid_%22 + c_uuid)%0A        if not user_id
 :%0A  
@@ -1827,16 +1827,16 @@
 _id'))%5D%0A
+
         
@@ -1911,45 +1911,8 @@
 y))%0A
-        user_id = session%5B'user_id'%5D%0A
     

replace session with cookie