#!/usr/bin/env python3 import os from flask import Flask, Response, render_template, send_file, request from . import file from . import config from . import auth app = Flask( __name__, template_folder="../templates", static_folder="../static", ) app.jinja_env.globals.update( config=config, path_join=os.path.join, ) @app.route('/', defaults={'path': ''}) @app.route('/') @auth.requires_auth def index(path): internal_path = os.path.join(config.get('base_path'), path) path = '/' + path # Checks ################################################### if '..' in path: return 'Path cannot contain double dots, i.e. "..".' if not os.path.exists(internal_path): return ( render_template( "error.html", code=404, msg=f'The path "{path}" does not exist.', ), 404, ) # Actual serving ########################################### if os.path.isdir(internal_path): _, dirs, files = next(os.walk(internal_path)) files = sorted(filter(lambda x: not x.startswith("."), files)) dirs = sorted(filter(lambda x: not x.startswith("."), dirs)) return ( render_template( "directory.html", path=path, dirs=dirs, files=files, ), 200, ) # Path exists, not a folder, must be a file, send return send_file(internal_path) @app.route('/search') @auth.requires_auth def search(): q = request.args.get('q', '') if q == '': return ( render_template( "error.html", code=400, msg='No search string provided.', ), 400, ) ret = file.search(q) return ( render_template( "search.html", list=ret, q=q, ), 200, ) @app.route('/auth', methods=['POST']) def auth_handle(): expected_pass = config.get('password') if expected_pass is None: return "You shouldn't be here.", 405 if request.form.get("pass", None) != expected_pass: return render_template( 'auth.html', path=request.form.get("location", "/"), error_msg="Incorrect password", ), 403 return Response( "Redirecting...", 303, { 'Location': request.form.get("location", "/"), 'Set-Cookie': 'film_session=To be changed', } )