-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
546 lines (450 loc) · 18.5 KB
/
main.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
from flask import Flask, request, render_template, redirect, flash, jsonify, session
from flask_bcrypt import Bcrypt
from flask_login import login_user, LoginManager, login_required,current_user, logout_user
import base64
import os
from dotenv import load_dotenv
load_dotenv()
import re
import database_handler as db_handler
import notify as email_service
from photo_scan import initialize_photo_scan_app
from actions import get_action_manager
photo_path = "photo.jpg"
photo_scan_app=initialize_photo_scan_app()
# def test():
# photo_path ="https://s3.amazonaws.com/docs.thehive.ai/client_demo/moderation_image.png"
# photo_scan_app=initialize_photo_scan_app()
# analysis_results = photo_scan_app.scan_photo(photo_path)
# for analysis in analysis_results:
# print(analysis)
# test()
# Setting up Flask
app = Flask(__name__)
app.secret_key = 'your_secret_key'
bcrypt = Bcrypt(app)
# User Authentication
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = '/login'
# Initializing action manager
action_manager = None
def is_valid_email(email):
# Regular expression pattern for a more comprehensive email validation
pattern = r'^[\w\.-]+(\+[\w\.-]+)*@[\w\.-]+\.\w+$'
return re.match(pattern, email) is not None
@login_manager.user_loader
def load_user(user_id):
global action_manager
user = db_handler.get_user_by_id(user_id)
if(user):
action_manager = get_action_manager(reporter_name=user.name, reporter_email=user.email)
return user
# Index Route
@app.route('/')
@app.route('/index')
def index():
return render_template("home.html")
def show_dashboard(escalated=False):
plugins=db_handler.get_all_plugins()
images=db_handler.get_pending_images()
if images:
if escalated:
images=db_handler.get_escalated_images()
if images:
images=[image.to_dict() for image in images]
dashboard_name="Escalated images"
else:
images=[image.to_dict() for image in images]
dashboard_name="Submitted images"
else:
images = []
return render_template('dashboard.html',images=images,dashboard_name=dashboard_name, plugins=plugins, action_manager=action_manager)
@app.route('/dashboard')
@login_required
def dashbboard():
return show_dashboard()
@app.route('/filter_images', methods=['POST'])
@login_required
def filter_images():
# Retrieve filter data from the request
username = request.form.get('username')
date = request.form.get('date')
photodna_results = request.form.get('photodna_results') == 'true'
hiveai_results = request.form.get('hiveai_results') == 'true'
escalated = request.form.get('escalated') == 'true'
# Call the function to get filtered images
# Here
filtered_images = db_handler.get_filtered_images(username, date, photodna_results, hiveai_results, escalated)
images = [image.to_dict() for image in filtered_images]
return jsonify({'images': images})
@app.route('/perform_actions', methods=['POST'])
@login_required
def perform_actions():
actions=[]
selected_actions = request.json.get('selected_actions', [])
for action in selected_actions:
action_type, number = re.match(r'([a-zA-Z_]+)_(\d+)', action).groups()
actions.append(action_type)
image = db_handler.get_image_by_id(int(number))
# Iterate through selected actions and perform the desired action
for action_id in actions:
action_manager.perform_action(action_id, image)
return jsonify({'success': True}), 200, {'Content-Type': 'application/json'}
@app.route('/submitted_images')
@login_required
def submitted_images():
return redirect("/dashboard")
@app.route('/escalated_images')
@login_required
def escalated_images():
return show_dashboard(escalated=True)
@app.route('/plugins')
@login_required
def plugins():
plugins=db_handler.get_all_plugins()
active_plugins = [plugin for plugin in plugins if plugin.is_registered==True]
inactive_plugins = [plugin for plugin in plugins if plugin.is_registered==False]
active_plugins=[plugin.to_dict() for plugin in active_plugins ]
return render_template('plugins.html',active_plugins=active_plugins,inactive_plugins=inactive_plugins)
@app.route('/apis')
@login_required
def apis():
apis=db_handler.get_all_apis()
active_apis = [api for api in apis if api.is_registered==True]
inactive_apis = [api for api in apis if api.is_registered==False]
active_apis=[api.to_dict() for api in active_apis ]
return render_template('apis.html',active_apis=active_apis,inactive_apis=inactive_apis)
@app.route('/dismiss', methods=['POST'])
def dismiss_image():
image_id = request.form.get('image_id')
status="Dismissed"
response_data = {
"success": True,
"message": "Image dismissed successfully"
}
db_handler.update_image_status(image_id, status)
return jsonify(response_data)
@app.route('/approve', methods=['POST'])
def approve_image():
image_id = request.form.get('image_id')
status="Approved"
response_data = {
"success": True,
"message": "Image approved successfully"
}
db_handler.update_image_status(image_id, status)
return jsonify(response_data)
@app.route('/escalate', methods=['POST'])
def escalate_image():
image_id = request.form.get('image_id')
status="Escalate"
response_data = {
"success": True,
"message": "Image escalated successfully"
}
db_handler.update_image_status(image_id, status)
return jsonify(response_data)
@app.route('/invite', methods=['POST'])
@login_required
def invite():
if request.method == 'POST':
email = request.form.get('email')
if is_valid_email(email):
invitation_status="invitation sent successfully!"
invitation_id=db_handler.create_invitation(email, current_user.id)
email_service.welcome_new_user(email)
else:
invitation_status="email submitted invalid!"
users=db_handler.get_all_users()
users=[user.to_dict() for user in users]
return render_template('manage_users.html',
users=users,
invitation_status=invitation_status)
return "Invalid request method"
@app.route('/activate_api/<id>')
@login_required
def activate_api(id):
db_handler.update_api_status(id,"TRUE")
return redirect("/apis")
@app.route('/delete_api/<id>')
@login_required
def delete_api(id):
db_handler.update_api_status(id,"FALSE")
return redirect("/apis")
@app.route('/activate_plugin/<id>')
@login_required
def activate_plugin(id):
db_handler.update_plugin_status(plugin_id=id, is_registered=True)
return redirect("/plugins")
@app.route('/delete_plugin/<id>')
@login_required
def delete_plugins(id):
db_handler.update_plugin_status(plugin_id=id, is_registered=False)
return redirect("/plugins")
@app.route('/kick/<user_id>')
@login_required
def kick(user_id):
db_handler.delete_user(user_id)
users=db_handler.get_all_users()
users=[user.to_dict() for user in users]
return render_template('manage_users.html',users=users)
@app.route('/promote/<user_id>')
@login_required
def promote(user_id):
db_handler.promote_user(user_id)
users=db_handler.get_all_users()
users=[user.to_dict() for user in users]
return render_template('manage_users.html',users=users)
@app.route('/degrade/<user_id>')
@login_required
def degrade(user_id):
db_handler.degrade_user(user_id)
users=db_handler.get_all_users()
users=[user.to_dict() for user in users]
return render_template('manage_users.html',users=users)
@app.route('/manage_users')
@login_required
def manage_users():
users=db_handler.get_all_users()
users=[user.to_dict() for user in users]
return render_template('manage_users.html',users=users)
def token_valid(token):
if token != "123454676868":
return False
return True
@app.route('/scan')
@login_required
def scan():
images=db_handler.get_unscanned_images()
for image in images:
analysis_results=photo_scan_app.scan_photo("http://127.0.0.1:7000/static/img/"+image.image_url)
for result in analysis_results:
if result.plugin == 'HiveAI':
db_handler.update_image_hiveai_scan_results(image.id,result.result)
elif result.plugin == 'PhotoDNA':
db_handler.update_image_photodna_scan_results(image.id,result.result)
return redirect("dashboard")
@app.route('/status/<image_id>', methods=["GET"])
def get_image_status(image_id):
image = db_handler.get_image_by_id(image_id)
if image:
return jsonify({
"image_url": image.image_url,
"status": image.status,
"photodna_results": image.photodna_results,
"hiveai_results": image.hiveai_results
}),200
else:
return jsonify({"message": "No image with that id found."}), 404
def process_image(user_id, base64_image_data, metadata):
try:
scan_results = {"result": "none"}
status = "pending"
if base64_image_data and metadata:
image_decoded = base64.b64decode(base64_image_data)
file_extension = metadata.get("extension", "jpg")
file_name = f"{metadata['title'].replace(' ', '_')}.{file_extension}"
image_path = os.path.join("", file_name)
with open(image_path, "wb") as image_file:
image_file.write(image_decoded)
print(user_id, image_path, metadata, scan_results, status)
#image_id = db_handler.create_image(user_id, image_path, metadata, scan_results, status)
image_id="bla"
return {
'status': 'success',
'message': 'Image and metadata received',
'image_metadata': metadata,
'image_id': image_id
}
return {'status': 'error', 'message': 'Invalid or missing image data'}
except Exception as e:
return {'status': 'error', 'message': str(e)}
def get_user_from_token(token):
return db_handler.get_user_by_email("slepamacka@gmail.com")
@app.route('/upload', methods=['GET', 'POST'])
def upload():
try:
data = request.get_json()
email = data.get('Email')
password = data.get('Password')
print(email)
user = db_handler.get_user_by_email(email)
if not (user and bcrypt.check_password_hash(user.password, password)):
return jsonify({'status': 'error', 'message': "User not found"}), 400
base64_image_data = data.get("image")
metadata = data.get('metadata')
reportee_name=data.get("reportee_name")
reportee_ip_address=data.get("reportee_ip_address")
location=data.get("location")
if base64_image_data and metadata:
image_data = base64.b64decode(base64_image_data)
file_extension = metadata.get("extension", "jpg")
file_name = f"{metadata['title'].replace(' ', '_')}.{file_extension}"
image_path = os.path.join("static/img", file_name)
with open(image_path, "wb") as image_file:
image_file.write(image_data)
image_id=db_handler.create_image(user_id=user.id, image_url=image_path, status="pending",
incident_time=None, reportee_name=reportee_name, reportee_ip_address=reportee_ip_address,
username=user.name, location=location)
response = {
'status': 'success',
'message': 'Image and metadata received',
'image_metadata': metadata,
'image_id':image_id
}
return jsonify(response), 200
except Exception as e:
return jsonify({'status': 'error', 'message': str(e)}), 400
@app.route('/upload_images', methods=['POST'])
def upload_images():
#try:
data = request.get_json()
email = data.get('Email')
password = data.get('Password')
user = db_handler.get_user_by_email(email)
if not (user and bcrypt.check_password_hash(user.password, password)):
return jsonify({'status': 'error', 'message': "User not found"}), 400
if 'images' not in data or not isinstance(data['images'], list):
return jsonify({'status': 'error', 'message': 'Invalid or missing images data'}), 400
image_responses = []
for image_data in data['images']:
base64_image_data = image_data.get("image")
metadata = image_data.get('metadata')
if base64_image_data and metadata:
image_base64_data = base64.b64decode(base64_image_data)
else:
return jsonify({'status': 'error', 'message': "One of the images has no metadata or no base61_image_data present"}), 400
reportee_name =image_data.get("reportee_name")
reportee_ip_address =image_data.get("reportee_ip_address")
location =image_data.get("location")
file_extension = metadata.get("extension", "jpg")
file_name = f"{metadata['title'].replace(' ', '_')}.{file_extension}"
print(file_name)
image_path = os.path.join("static/img", file_name)
with open(image_path, "wb") as image_file:
image_file.write(image_base64_data)
image_id=db_handler.create_image(user_id=user.id, image_url=file_name, status="pending",
incident_time=None, reportee_name=reportee_name, reportee_ip_address=reportee_ip_address,
username=user.name, location=location)
response = {
'status': 'success',
'message': 'Image and metadata received',
'image_metadata': metadata,
'image_id':image_id
}
image_responses.append(response)
return jsonify({'images': image_responses}), 200
#except Exception as e:
# print(e)
# return jsonify({'status': 'error', 'message': str(e)}), 400
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404
@app.route('/login', methods=['GET', 'POST'])
def login():
return render_template('login.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
return render_template('register.html')
@app.route('/forgot_password')
def forgot_password():
return render_template('forgot_password.html')
@app.route('/logout_user', methods=['GET', 'POST'])
@login_required
def logout_users():
logout_user()
user_name = ""
session['user_name'] = user_name
return redirect('/login')
@app.route('/login_user', methods=['GET', 'POST'])
def login_users():
if request.method == 'POST':
email = request.form.get('exampleInputEmail')
password = request.form.get('exampleInputPassword')
user = db_handler.get_user_by_email(email)
if (user and bcrypt.check_password_hash(user.password, password)):
login_user(user)
user_name = f"{user.name} {user.lastname}"
session['user_name'] = user_name
return redirect('/dashboard')
elif (not user):
flash("No acount with this email registred! Please Sign Up!", "error")
return redirect('/login')
else:
flash("Wrong password! Please try again!", "error")
return redirect('/login')
return render_template('login.html')
@app.route('/register_user', methods=['GET', 'POST'])
def register_user():
if request.method == 'POST':
# Get form data
name = request.form.get('exampleFirstName')
lastname = request.form.get('exampleLastName')
email = request.form.get('exampleInputEmail')
if not db_handler.get_invitation_by_email(email):
if len(db_handler.get_all_users())!=0:
flash("Email is not invited, please ask for invite first.",
"error")
return redirect('/register')
password = request.form.get('exampleInputPassword')
repeat_password = request.form.get('exampleRepeatPassword')
# Check if password and repeat_password match
if password != repeat_password:
flash("Password and Repeat Password do not match. Please try again.",
"error")
return redirect('/register')
# Check if email is already registered
if db_handler.get_user_by_email(email):
flash("Email already registered. Please use a different email.", "error")
return redirect('/register')
# Hash the password using bcrypt
hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
# Add new user to the database
db_handler.create_user(name, lastname, email, hashed_password)
return redirect('/login')
return render_template('register.html')
# db_handler.add_column()
# Custom filter function
def add_strong_tag(text):
# Use regular expression to match any text before ":" until a new line character
# Not perfect because sometimes bot can make statements with ":"
formatted_text = re.sub(r'([^:\n]+:)', r'<br><strong>\1</strong>', text)
return formatted_text
# Add the filter to Jinja2 environment
app.jinja_env.filters['add_strong_tag'] = add_strong_tag
@app.route('/update_or_create_image', methods=['POST'])
def update_or_create_image():
try:
email = request.form.get('Email')
password = request.form.get('Password')
user = db_handler.get_user_by_email(email)
if not (user and bcrypt.check_password_hash(user.password, password)):
return jsonify({'status': 'error', 'message': "User not found"}), 400
data = request.json
image_id = data.get('image_id')
user_id = data.get('user_id')
image_url = data.get('image_url')
status = data.get('status')
incident_time = data.get('incident_time')
reportee_name = data.get('reportee_name')
reportee_ip_address = data.get('reportee_ip_address')
username = data.get('username')
location = data.get('location')
if image_id:
photodna_results = data.get('photodna_results')
hiveai_results=data.get("hiveai_results")
# If image_id is provided, update the existing image
db_handler.update_image(image_id, user_id, image_url,
photodna_results, hiveai_results, status, incident_time,
reportee_name, reportee_ip_address,username, location)
else:
image_id=db_handler.create_image(user_id=user_id, image_url=image_url, status="pending",
incident_time=None, reportee_name=reportee_name, reportee_ip_address=reportee_ip_address,
username=username, location=location)
return jsonify({'success': True, 'image_id': image_id})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
# Run the Flask app
if __name__ == '__main__':
app.run(host="0.0.0.0", port=7000)