|
|
|
from functools import wraps
|
|
|
|
from flask import (
|
|
|
|
request, Response, session, flash, redirect, url_for, abort
|
|
|
|
)
|
|
|
|
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:
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
def authenticate():
|
|
|
|
"""Sends a 401 response that enables basic auth"""
|
|
|
|
return Response(
|
|
|
|
'Could not verify your access level for that URL.\n'
|
|
|
|
'You have to login with proper credentials', 401,
|
|
|
|
{'WWW-Authenticate': 'Basic realm="Login Required"'}
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def requires_auth(f):
|
|
|
|
'''
|
|
|
|
REQUEST.json
|
|
|
|
only gets basic authentication
|
|
|
|
REQUEST.get
|
|
|
|
redirect to login page
|
|
|
|
'''
|
|
|
|
@wraps(f)
|
|
|
|
def decorated(*args, **kwargs):
|
|
|
|
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):
|
|
|
|
if not request.json:
|
|
|
|
return redirect(url_for('hello_world'))
|
|
|
|
else:
|
|
|
|
abort(401)
|
|
|
|
|
|
|
|
return f(*args, **kwargs)
|
|
|
|
return decorated
|