Created
December 5, 2016 10:46
-
-
Save yous/f8f3aba1e5f2659421b8b671a003d17b to your computer and use it in GitHub Desktop.
Simple multithreaded Flask file server with basic auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os.path | |
from functools import wraps | |
from flask import Flask, request, Response, redirect | |
from flask_autoindex import AutoIndex | |
fileroot = os.path.join(os.path.realpath(os.path.curdir), 'files') | |
app = Flask(__name__) | |
idx = AutoIndex(app, | |
browse_root=fileroot, | |
add_url_rules=False) | |
def check_auth(username, password): | |
""" This function is called to check if a username / password combination is | |
valid. | |
""" | |
return username == 'USERNAME' and password == 'PASSWORD' | |
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="Auth"'}) | |
def requires_auth(f): | |
@wraps(f) | |
def decorated(*args, **kwargs): | |
auth = request.authorization | |
if not auth or not check_auth(auth.username, auth.password): | |
return authenticate() | |
return f(*args, **kwargs) | |
return decorated | |
@app.route('/') | |
@app.route('/<path:path>') | |
@requires_auth | |
def autoindex(path='.'): | |
# For Windows | |
relpath = os.path.join(*path.split('%5C')) | |
normpath = os.path.normpath(relpath) | |
if normpath.startswith(os.path.pardir): | |
normpath = '/' | |
if normpath != path: | |
if normpath == '.': | |
return redirect('/') | |
return redirect(normpath) | |
return idx.render_autoindex(normpath) | |
if __name__ == '__main__': | |
app.run(threaded=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment