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 ( from flask import (
request, Response, session, flash, redirect, url_for, abort 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 random
import string import string
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
def csrf_token_generator(size=40, chars=string.ascii_uppercase + string.digits): def csrf_token_generator(size=40, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size)) 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): def check_basic_auth(user, passwd):
'''
TODO: check token too -- password will be 'unused'
'''
if user != app_user or passwd != app_password: if user != app_user or passwd != app_password:
return False return False
else: else:
@ -36,19 +45,15 @@ def requires_auth(f):
''' '''
@wraps(f) @wraps(f)
def decorated(*args, **kwargs): def decorated(*args, **kwargs):
if request.json: auth = session.get('logged_in')
auth = request.headers.get('Authorization') if auth:
if auth.startswith('Basic'): return f(*args, **kwargs)
basic_auth = request.authorization basic_auth = request.authorization
if not check_basic_auth(basic_auth.username, basic_auth.password): if not check_basic_auth(basic_auth.username, basic_auth.password):
abort(401) if not request.json:
return redirect(url_for('hello_world'))
else: else:
abort(401) 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 f(*args, **kwargs)
return decorated return decorated

48
flasky.py

@ -8,10 +8,10 @@ from pymongo import MongoClient, DESCENDING # ASCENDING
import datetime import datetime
import dateutil.parser import dateutil.parser
import bson 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 datetime import timedelta
from functools import update_wrapper 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, 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 # Load default config and override config from an environment variable
app.config.update(dict( app.config.update(dict(
DEBUG=True, DEBUG=True,
SECRET_KEY='development key', SECRET_KEY=app_secret,
USERNAME=app_user, USERNAME=app_user,
PASSWORD=app_password, PASSWORD=app_password,
)) ))
@ -81,16 +81,16 @@ miscObjHandler = lambda obj: (
else str(obj) if isinstance(obj, bson.objectid.ObjectId) else None) else str(obj) if isinstance(obj, bson.objectid.ObjectId) else None)
@app.before_request # @app.before_request
def csrf_protect(): # def csrf_protect():
''' # '''
Skip CSRF-token for RESTful service # Skip CSRF-token for RESTful service
ref: http://flask.pocoo.org/snippets/3/ # ref: http://flask.pocoo.org/snippets/3/
''' # '''
if request.method == "POST" and not request.json: # if request.method == "POST" and not request.json:
token = session.pop('_csrf_token', None) # token = session.pop('_csrf_token', None)
if not token or token != request.form.get('_csrf_token'): # if not token or token != request.form.get('_csrf_token'):
abort(403) # abort(403)
@app.route('/') @app.route('/')
@ -101,10 +101,10 @@ def hello_world():
return render_template('layout.html') return render_template('layout.html')
@app.route('/movies/', methods=['GET'], defaults={'option': 'nowshowing'}) @app.route('/movies/', methods=['GET'])
@app.route('/movies/<option>/', methods=['GET']) @app.route('/movies/<option>/', methods=['GET'])
@crossdomain(origin='*') @crossdomain(origin='*')
def movie_list(option): def movie_list(option=''):
_opt = ('nowshowing', 'comingsoon', 'older') _opt = ('nowshowing', 'comingsoon', 'older')
option = option if option in _opt else 'nowshowing' option = option if option in _opt else 'nowshowing'
query = {} query = {}
@ -121,6 +121,10 @@ def movie_list(option):
for i in result: for i in result:
if 'original' in i['title']: if 'original' in i['title']:
i['original_title'] = i['title']['original'] 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['title'] = i['title'][lang]
# i['cast'] = i['cast'][lang] # i['cast'] = i['cast'][lang]
# i['tagline'] = i['tagline'][lang] # i['tagline'] = i['tagline'][lang]
@ -351,7 +355,21 @@ def check_basic_auth(user, passwd):
return True 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']) @app.route('/login', methods=['GET', 'POST'])
@crossdomain(origin='*')
def login(): def login():
error = None error = None
if request.method == 'POST': 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_user = conf.get('app', 'user')
app_password = conf.get('app', 'password') app_password = conf.get('app', 'password')
app_secret = conf.get('app', 'secret_key')
mongo_conf_data = { mongo_conf_data = {
'host': conf.get('mongo', 'host') if conf.has_option('mongo', 'host') else 'localhost', 'host': conf.get('mongo', 'host') if conf.has_option('mongo', 'host') else 'localhost',

1
site.default.cfg

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

Loading…
Cancel
Save