sipp11 10 years ago
parent
commit
f550b9a6b0
  1. 25
      auth.py
  2. 48
      flasky.py
  3. 1
      settings.py
  4. 1
      site.default.cfg

25
auth.py

@ -2,16 +2,25 @@ from functools import wraps
from flask import (
request, Response, session, flash, redirect, url_for, abort
)
from settings import app_password, app_user
from settings import app_password, app_user, app_secret
import random
import string
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
def csrf_token_generator(size=40, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def generate_auth_token(user, expiration=600):
s = Serializer(app_secret, expires_in=expiration)
return s.dumps({'id': 1})
def check_basic_auth(user, passwd):
'''
TODO: check token too -- password will be 'unused'
'''
if user != app_user or passwd != app_password:
return False
else:
@ -36,19 +45,15 @@ def requires_auth(f):
'''
@wraps(f)
def decorated(*args, **kwargs):
if request.json:
auth = request.headers.get('Authorization')
if auth.startswith('Basic'):
auth = session.get('logged_in')
if auth:
return f(*args, **kwargs)
basic_auth = request.authorization
if not check_basic_auth(basic_auth.username, basic_auth.password):
abort(401)
if not request.json:
return redirect(url_for('hello_world'))
else:
abort(401)
return f(*args, **kwargs)
auth = session.get('logged_in')
if not auth:
flash('You are not authorized')
return redirect(url_for('hello_world'))
return f(*args, **kwargs)
return decorated

48
flasky.py

@ -8,10 +8,10 @@ from pymongo import MongoClient, DESCENDING # ASCENDING
import datetime
import dateutil.parser
import bson
from settings import mongo_config, app_password, app_user
from settings import mongo_config, app_password, app_user, app_secret
from datetime import timedelta
from functools import update_wrapper
from auth import requires_auth, csrf_token_generator
from auth import requires_auth, csrf_token_generator, generate_auth_token
def crossdomain(origin=None, methods=None, headers=None,
@ -66,7 +66,7 @@ app = Flask(__name__)
# Load default config and override config from an environment variable
app.config.update(dict(
DEBUG=True,
SECRET_KEY='development key',
SECRET_KEY=app_secret,
USERNAME=app_user,
PASSWORD=app_password,
))
@ -81,16 +81,16 @@ miscObjHandler = lambda obj: (
else str(obj) if isinstance(obj, bson.objectid.ObjectId) else None)
@app.before_request
def csrf_protect():
'''
Skip CSRF-token for RESTful service
ref: http://flask.pocoo.org/snippets/3/
'''
if request.method == "POST" and not request.json:
token = session.pop('_csrf_token', None)
if not token or token != request.form.get('_csrf_token'):
abort(403)
# @app.before_request
# def csrf_protect():
# '''
# Skip CSRF-token for RESTful service
# ref: http://flask.pocoo.org/snippets/3/
# '''
# if request.method == "POST" and not request.json:
# token = session.pop('_csrf_token', None)
# if not token or token != request.form.get('_csrf_token'):
# abort(403)
@app.route('/')
@ -101,10 +101,10 @@ def hello_world():
return render_template('layout.html')
@app.route('/movies/', methods=['GET'], defaults={'option': 'nowshowing'})
@app.route('/movies/', methods=['GET'])
@app.route('/movies/<option>/', methods=['GET'])
@crossdomain(origin='*')
def movie_list(option):
def movie_list(option=''):
_opt = ('nowshowing', 'comingsoon', 'older')
option = option if option in _opt else 'nowshowing'
query = {}
@ -121,6 +121,10 @@ def movie_list(option):
for i in result:
if 'original' in i['title']:
i['original_title'] = i['title']['original']
## disable some heavy overload data
for j in ('tmdb', 'videos'):
if j in i:
del i[j]
# i['title'] = i['title'][lang]
# i['cast'] = i['cast'][lang]
# i['tagline'] = i['tagline'][lang]
@ -351,7 +355,21 @@ def check_basic_auth(user, passwd):
return True
@app.route('/api/token', methods=['GET'])
@crossdomain(origin='*')
def get_token():
auth = request.authorization
if not check_basic_auth(auth.username, auth.password):
abort(401)
token = generate_auth_token(app_user)
r = make_response(
dumps({'token': token.decode('ascii')}, default=miscObjHandler))
r.mimetype = 'application/json'
return r
@app.route('/login', methods=['GET', 'POST'])
@crossdomain(origin='*')
def login():
error = None
if request.method == 'POST':

1
settings.py

@ -13,6 +13,7 @@ port = conf.getint('app', 'port') if conf.has_option('app', 'port') else 8888
app_user = conf.get('app', 'user')
app_password = conf.get('app', 'password')
app_secret = conf.get('app', 'secret_key')
mongo_conf_data = {
'host': conf.get('mongo', 'host') if conf.has_option('mongo', 'host') else 'localhost',

1
site.default.cfg

@ -2,6 +2,7 @@
port=8989
user=foo
password=bar
secret_key=SECRET_KEY
[mongo]
host=localhost

Loading…
Cancel
Save