summaryrefslogtreecommitdiff
path: root/Filer.py
blob: e737047d881f7a3b6662f0b3a90983b61b2c21c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!venv/bin/python

import hashlib
import base64
import time
from os import unlink, path, getenv, listdir, mkdir, urandom
from shutil import rmtree
from threading import Thread
from random import randint
from sys import stderr, exit

from flask import Flask, render_template, jsonify, request, redirect, send_from_directory
from flask_dropzone import Dropzone
from argparse import ArgumentParser
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Silence is golden. Gerd Eist.'
#app.jinja_env.trim_blocks = True
#app.jinja_env.lstrip_blocks = True

app.config['PREFERRED_URL_SCHEME'] = 'https'
app.config['DROPZONE_SERVE_LOCAL'] = True
app.config['DROPZONE_MAX_FILE_SIZE'] = 128
app.config['DROPZONE_UPLOAD_MULTIPLE'] = True
app.config['DROPZONE_PARALLEL_UPLOADS'] = 10

app.config['DROPZONE_ALLOWED_FILE_CUSTOM'] = True
app.config['DROPZONE_ALLOWED_FILE_TYPE'] = ''

app.config['DROPZONE_DEFAULT_MESSAGE'] = 'Ziehe die Dateien hier hin, um sie hochzuladen oder klicken Sie zur Auswahl.'

dropzone = Dropzone(app)

basedir = getenv('FILER_BASEDIR', './Daten')
filettl = int(getenv('FILER_FILETTL', 10))

#### ADMIN FACING DIRECTORY LISTS ####
####
####
@app.route("/admin", methods=['GET'])
def admin():
    url_root = request.url_root.replace('http://', 'https://', 1)
    users = listdir(path.join(basedir, 'Mandanten'))
    return render_template('admin.html', users = users, tree = make_tree(basedir, 'Public'), url_root = url_root)

@app.route("/admin/Dokumente/<user>", methods=['GET'])
def admin_dokumente(user):
    return render_template('mandant.html', admin = 'admin/', user = user, tree = make_tree(basedir, path.join('Dokumente', user)))

@app.route("/admin/del-user/<user>", methods=['POST'])
def admin_deluser(user):
    method = request.form.get('_method', 'POST')
    if method == 'DELETE':
        rmtree(path.join(basedir, 'Dokumente', secure_filename(user)))
        unlink(path.join(basedir, 'Mandanten', secure_filename(user)))
    return redirect('/admin')

@app.route("/admin/new-user", methods=['POST'])
def admin_newuser():
    password = request.form.get('password', '')
    user = request.form.get('user', '')
    if not password or not user:
        return "Username or password missing", 400
    directory = secure_filename(user)

    salt = urandom(4)
    sha = hashlib.sha1(password.encode('utf-8'))
    sha.update(salt)

    digest_salt_b64 = base64.b64encode(sha.digest()+ salt)
    tagged_digest_salt = '{{SSHA}}{}'.format(digest_salt_b64.decode('ascii'))

    try:
        if not path.exists(path.join(basedir, 'Dokumente', directory)):
            mkdir(path.join(basedir, 'Dokumente', directory))
        with open(path.join(basedir, 'Mandanten', directory), 'w+', encoding='utf-8') as htpasswd:
            htpasswd.write("{}:{}\n".format(user, tagged_digest_salt))
    except OSError as error:
        return "Couldn't create user scope", 500
    return redirect('/admin')

#### USER FACING DIRECTORY LIST ####
####
####
@app.route("/Dokumente/<user>", methods=['GET'])
def mandant(user):
    return render_template('mandant.html', admin = '', user = user, tree = make_tree(basedir, path.join('Dokumente', user)))

#### UPLOAD FILE ROUTES ####
####
####
@app.route('/Dokumente/<user>', methods=['POST'])
@app.route('/admin/Dokumente/<user>', methods=['POST'])
def upload_mandant(user):
    for key, f in request.files.items():
        if key.startswith('file'):
            username = secure_filename(user)
            filename = secure_filename(f.filename)
            f.save(path.join(basedir, 'Dokumente', username, filename))
    return 'upload template'

@app.route('/admin', methods=['POST'])
def upload_admin():
    for key, f in request.files.items():
        if key.startswith('file'):
            filename = secure_filename(f.filename)
            f.save(path.join(basedir, 'Public', filename))
    return 'upload template'

#### DELETE FILE ROUTES ####
####
####
@app.route('/Dokumente/<user>/<path:filename>', methods=['POST'])
def delete_file_mandant(user, filename):
    method = request.form.get('_method', 'POST')
    if method == 'DELETE':
        unlink(path.join(basedir, 'Dokumente', secure_filename(user), secure_filename(filename)))
    return redirect('/Dokumente/'+user)

@app.route('/admin/Dokumente/<user>/<path:filename>', methods=['POST'])
def delete_file_mandant_admin(user, filename):
    method = request.form.get('_method', 'POST')
    if method == 'DELETE':
        unlink(path.join(basedir, 'Dokumente', secure_filename(user), secure_filename(filename)))
    return redirect('/admin/Dokumente/'+user)

@app.route('/admin/Public/<path:filename>', methods=['POST'])
def delete_file_admin(filename):
    method = request.form.get('_method', 'POST')
    if method == 'DELETE':
        unlink(path.join(basedir, 'Public', secure_filename(filename)))
    return redirect('/admin')

#### SERVE FILES RULES ####
####
####
@app.route('/admin/Dokumente/<user>/<path:filename>', methods=['GET'])
@app.route('/Dokumente/<user>/<path:filename>', methods=['GET'])
def custom_static(user, filename):
    return send_from_directory(path.join(basedir, 'Dokumente'), path.join(user, filename))

@app.route('/Public/<path:filename>')
def custom_static_public(filename):
    return send_from_directory(path.join(basedir, 'Public'), filename)

def make_tree(rel, pathname):
    tree = dict(name=pathname, download=path.basename(pathname), children=[])
    try: lst = listdir(path.join(rel,pathname))
    except OSError:
        pass #ignore errors
    else:
        for name in lst:
            fn = path.join(pathname, name)
            if path.isdir(path.join(rel,fn)):
                tree['children'].append(make_tree(rel, fn))
            else:
                ttl = filettl -  int((time.time() - path.getmtime(path.join(rel,fn))) / (24*3600))
                if ttl < 0:
                    unlink(path.join(rel,fn))
                else:
                    tree['children'].append(dict(name=fn, download=name, ttl = ttl))
    return tree

def cleaner_thread():
    while True:
        make_tree(basedir, 'Dokumente')
        # sleep for 6h plus jitter
        time.sleep(21600 + randint(1, 1800))

thread = Thread(target=cleaner_thread, args=())
thread.daemon = True
thread.start()

try:
    if not path.exists(path.join(basedir, 'Dokumente')):
        mkdir(path.join(basedir, 'Dokumente'))
    if not path.exists(path.join(basedir, 'Mandanten')):
        mkdir(path.join(basedir, 'Mandanten'))
    if not path.exists(path.join(basedir, 'Public')):
        mkdir(path.join(basedir, 'Public'))
except:
    stderr.write("Error: Basedir not accessible\n")
    exit(1)

if __name__ == "__main__":
    parser = ArgumentParser(description="Filer")
    parser.add_argument("-H", "--host", help="Hostname of the Flask app " + "[default %s]" % "127.0.0.1", default="127.0.0.1")
    parser.add_argument("-P", "--port", help="Port for the Flask app " + "[default %s]" % "5000", default="5000")

    args = parser.parse_args()

    app.run(host=args.host, port=int(args.port))