-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
331 lines (257 loc) · 10.6 KB
/
app.py
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
from flask import Flask
from flask import render_template, flash, request, redirect, url_for, session
from werkzeug.utils import secure_filename
from passlib.hash import pbkdf2_sha512
from functools import wraps
import datetime
import paramiko
import os
from bson.objectid import ObjectId
from dbconnect import connection
import config
app = Flask(__name__)
app.secret_key = config.secret_key
# File upload configuration
UPLOAD_FOLDER = "/app/uploads"
ALLOWED_EXTENSIONS = set(["html", "css", "jpg", "png"])
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024 # 5 MB
uploadingFiles = dict()
def allowed_file(filename):
return "." in filename and \
filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if "logged_in" in session:
return f(*args, **kwargs)
else:
flash("Du musst dich anmelden!")
return redirect(url_for("index"))
return wrap
def admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if "admin" in session:
return f(*args, **kwargs)
else:
flash("Du bist kein admin!")
return redirect(url_for("index"))
return wrap
@app.route("/", methods=["GET", "POST"])
def index():
error = None
# If user is logged in, redirect him to dashboard
if "logged_in" in session:
return redirect(url_for("dashboard"))
try:
client, db = connection()
if request.method == "POST":
# Get form values
attempted_username = request.form["username"].lower()
attempted_password = request.form["password"]
data = db.users.find_one({"username": attempted_username})
if data:
# Get data from db
database_password = data["password"]
uid = str(data["_id"])
username = data["username"]
rank = data["rank"]
# If no password has been set
if database_password == False:
password_hashed = pbkdf2_sha512.hash(attempted_password)
db.users.update({"_id": ObjectId(uid)},
{"$set": {
"password": password_hashed
}})
flash("Dein Passwort wurde erfolgreich gesetzt! Melde dich bitte erneut an!")
return redirect(url_for("index"))
# Check hash
if pbkdf2_sha512.verify(attempted_password, database_password):
flash("Hallo, " + username + " Du hast dich erfolgreich angemeldet!")
session["logged_in"] = True
session["username"] = username
session["uid"] = uid
# Check admin
if rank == "admin":
session["admin"] = True
flash("Du bist ein Admin!")
return redirect(url_for("admin"))
return redirect(url_for("dashboard"))
# Wrong username or password
else:
error = "Falscher Benutzername oder falsches Passwort!"
except Exception as e:
error = e
return render_template("index.html", error=error, title="Login")
@app.route("/logout")
@login_required
def logout():
# Delete all variables from user session
session.clear()
flash("You logged out successfully!")
return redirect(url_for("index"))
###
# DASHBOARD
###
@app.route("/dashboard", methods=["GET", "POST"])
@login_required
def dashboard():
error = None
client, db = connection()
domains = [domain for domain in db.domains.find({"uid": str(session["uid"])})]
# User wants to create a new domain
if request.method == "POST":
# Get form value
domainname = request.form["domainname"]
# Check for special characters
characters = [".", ",", "-", "/", ":", ";", "_", "!", "=", "?", "*", "#", "+", "~", "ä", "ö", "ü"]
for character in characters:
if character in domainname:
error = "Verwende keine Sonderzeichen in deinem Domainname!"
return render_template("dashboard.html", title="Dashboard", error=error, domains=domains)
else:
pass
# Check whether domainname is already taken
check_domain = db.domains.find_one({"name": domainname})
if check_domain:
error = "Diese Domain gibst es schon! Wähle eine andere."
return render_template("dashboard.html", title="Dashboard", error=error, domains=domains)
# Insert it in the database
domain = {
"name": domainname,
"registration_date": datetime.datetime.now().strftime("%Y-%m-%d"),
"uid": str(session["uid"]),
"activated": False
}
db.domains.insert_one(domain)
# Get the domains again, so the new domain is in the list
domains = [domain for domain in db.domains.find({"uid": str(session["uid"])})]
flash("Deine Domain " + domainname + ".moit.ml wird erstellt. Nun musst Du einige Zeit warten, bis deine Domain online ist!")
return render_template("dashboard.html", title="Dashboard", error=error, domains=domains)
@app.route("/dashboard/folder/<string:domainname>", methods=["GET", "POST"])
@app.route("/dashboard/folder/<string:domainname>/<path:path>", methods=["GET", "POST"])
@login_required
def dashboardFolder(domainname, path=None):
client, db = connection()
domain = db.domains.find_one({"name": domainname, "uid": str(session["uid"]), "activated": {"$ne": False}})
# If domain doesn't exist or user has no permission
if not domain:
flash("Du hast keine Berechtigung, diese Domain zu bearbeiten!")
return redirect(url_for("dashboard"))
# Connect to FTP-Server
transport = paramiko.Transport((config.ftp_host, config.ftp_port))
transport.connect(username=config.ftp_username, password=config.ftp_password)
# Upload file
if request.method == "POST":
# Check if the post request has the file part
if "file" not in request.files:
flash("Du hast keine Datei ausgewählt!")
return redirect(request.url)
file = request.files["file"]
if file.filename == "":
flash("Du hast keine Datei ausgewählt!")
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config["UPLOAD_FOLDER"], str(session["uid"]) + "_" + filename))
# Upload file to FTP-Server
ok = False
while not ok:
try:
sftp = paramiko.SFTPClient.from_transport(transport)
path_on_server = "uploads/" + str(session["uid"]) + "_" + filename
if path:
sftp.put(path_on_server, "public_html/" + domainname + "/" + path + "/" + filename)
else:
sftp.put(path_on_server, "public_html/" + domainname + "/" + filename)
# Remove file from server
os.remove(path_on_server)
ok = True
except Exception as e:
print(e)
flash("Deine Datei " + filename + " wird hochgeladen")
else:
flash("Diese Datei darfst Du nicht hochladen!")
ok = False
while not ok:
try:
sftp = paramiko.SFTPClient.from_transport(transport)
if path:
sftp.chdir("public_html/" + domainname + "/" + path)
else:
sftp.chdir("public_html/" + domainname)
foldercontent = sftp.listdir_attr()
pwd = sftp.getcwd()
sftp.close()
ok = True
except Exception as e:
print(e)
# Create list with files
files = list()
for i in foldercontent:
i = str(i)
# Get type (directory or file)
if i[0] == "d":
filetype = "d"
else:
filetype = "f"
splittedFile = i.split(" ")
# Don't show hidden files
if splittedFile[-1][0] != ".":
# Append dict ("filename": "file.py", "type": "f") to list
files.append({"filename": splittedFile[-1], "filetype": filetype})
# Remove folder cgi-bin
files = [file for file in files if file["filename"] != "cgi-bin"]
# TODO: Order files
# Remove exact pwd (/home/moit/...)
cleaned_pwd = pwd[22:]
return render_template("dashboard-folder.html", title="Config " + domainname, domainname=domainname, files=files, pwd=cleaned_pwd, path=path)
###
# ADMIN
###
@app.route("/admin", methods=["GET", "POST"])
@admin_required
def admin():
error = None
client, db = connection()
# Get all infos from db
not_activated_domains = [domain for domain in db.domains.find({"activated": False})]
domains = [domain for domain in db.domains.find({"activated": {"$ne": False}})]
users = [user for user in db.users.find()]
# Add username to list
for domain in not_activated_domains:
uid = domain["uid"]
username = db.users.find_one({"_id": ObjectId(uid)})
domain["username"] = username["username"]
for domain in domains:
uid = domain["uid"]
username = db.users.find_one({"_id": ObjectId(uid)})
domain["username"] = username["username"]
# Create new user
if request.method == "POST":
username = request.form["username"].lower()
user = {
"username": username,
"password": False,
"rank": "user",
"registration_date": datetime.datetime.now().strftime("%Y-%m-%d")
}
db.users.insert_one(user)
flash("User " + username + " wurde hinzugefügt!")
# Redirect to this page, so new user will be in list
return redirect(url_for("admin"))
return render_template("admin.html", title="Admin", error=error, users=users,
not_activated_domains=not_activated_domains, domains=domains)
@admin_required
@app.route("/admin/done/<string:domainname>")
def adminDone(domainname):
client, db = connection()
# Set a domainname as created
db.domains.update({"name": domainname},
{"$set": {
"activated": session["username"]
}})
flash("Domain " + domainname + ".moit.ml wurde als aktiviert festgelegt.")
return redirect(url_for("admin"))
if __name__ == "__main__":
app.run(debug=config.debug)