-
Notifications
You must be signed in to change notification settings - Fork 1
/
views.py
866 lines (776 loc) · 27 KB
/
views.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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
import sys
import pathlib
sys.path.append(str(pathlib.Path().absolute()))
from app import app, login_manager
from flask import request, render_template, redirect, url_for, jsonify, flash
import json
from models import *
from flask_login import login_required, logout_user, current_user, login_user
from datetime import date, datetime, timedelta
@app.route("/login/", methods=["GET", "POST"])
def login():
if current_user.is_authenticated:
return redirect(url_for("devices"))
if request.method == "POST":
email = request.form["email"].lower()
password = request.form["password"]
user = User.query.filter_by(email=email).first()
if user and user.check_password(password=password):
login_user(user)
next_page = request.args.get("next")
return redirect(next_page or url_for("devices"))
return render_template("login.html", error="Incorrect password or email")
return render_template("login.html")
@app.route("/logout/")
@login_required
def logout():
logout_user()
return redirect(url_for("login"))
@login_manager.user_loader
def load_user(user_id):
if user_id is not None:
return User.query.get(user_id)
return None
@login_manager.unauthorized_handler
def unauthorized():
return redirect(url_for("login"))
@app.route("/users/new/", methods=["GET", "POST"])
@login_required
def new_user():
title = "New | Users"
if request.method == "POST":
new_user = User(name=request.form["name"], email=request.form["email"],)
new_user.set_password(request.form["email"])
new_user.create()
return redirect(url_for("devices"))
else:
return render_template(
"users/new.html", user=User(), title=title, current_user=current_user,
)
"""
DEVICES VIEWS
"""
@app.route("/")
@app.route("/devices/", methods=["GET"])
@app.route("/devices/<id>", methods=["GET"])
@login_required
def devices(id=None):
if id:
feedback = (
request.args.get("feedback") if request.args.get("feedback") else None
)
device = Device.query.get(int(id))
title = "%r | Devices " % device.name
return render_template(
"devices/show.html",
title=title,
device=device,
feedback=feedback,
current_user=current_user,
)
else:
title = "Devices"
return render_template(
"devices/index.html",
title=title,
devices=Device.query.all(),
current_user=current_user,
)
@app.route("/devices/<id>/config", methods=["GET"])
@login_required
def device_running_config(id=None):
if id:
device = Device.query.get(id)
title = "%r | Devices | Running Config " % device.name
connection = Connection(
host=device.host,
username=device.ssh_username,
password=device.ssh_password,
)
running_config = connection.running_config()
return render_template(
"devices/show_config.html",
title=title,
device=device,
running_config=running_config.split("\n"),
current_user=current_user,
)
else:
title = "Devices"
return render_template(
"devices/index.html",
title=title,
devices=Device.query.all(),
current_user=current_user,
)
@app.route("/devices/<id>/logs", methods=["GET"])
@login_required
def device_logs(id=None):
if id:
device = Device.query.get(id)
logs = device.logs
title = "%r | Devices | Logs " % device.name
return render_template(
"devices/logs.html",
title=title,
device=device,
logs=logs,
current_user=current_user,
)
else:
title = "Devices"
return render_template(
"devices/index.html",
title=title,
devices=Device.query.all(),
current_user=current_user,
)
@app.route("/logs/<id>", methods=["GET"])
@login_required
def logs(id=None):
if id:
log = Log.query.get(id)
device = log.device
title = "%r | Devices | Logs " % device.name
return render_template(
"devices/show_logs.html",
title=title,
device=device,
log=log,
commands=log.commands.split("\n"),
current_user=current_user,
)
else:
title = "Devices"
return render_template(
"devices/index.html",
title=title,
devices=Device.query.all(),
current_user=current_user,
)
@app.route("/devices/new/", methods=["GET", "POST"])
@login_required
def new_device():
try:
title = "New | Devices"
if request.method == "POST":
new_device = Device(
name=request.form["deviceName"],
description=request.form["deviceDescription"],
host=request.form["deviceHost"].replace(" ", ""),
ssh_username=request.form["deviceUser"].replace(" ", ""),
ssh_password=request.form["devicePassword"],
)
error = new_device.validate()
if error:
return render_template(
"devices/new.html",
device=new_device,
error=error,
title=title,
current_user=current_user,
)
else:
new_device.create()
return redirect(url_for("devices", id=new_device.id))
else:
return render_template(
"devices/new.html",
device=Device(),
title=title,
current_user=current_user,
)
except:
error = "An issue was raised, IP entered might belong to an existing device"
return render_template(
"devices/new.html",
device=new_device,
error=error,
title=title,
current_user=current_user,
)
@app.route("/devices/<id>/update", methods=["GET", "POST"])
@login_required
def update_device(id=None):
try:
device = Device.query.get(id)
title = "Update | %r | Devices" % device.name
if request.method == "POST":
device.name = (
request.form["deviceName"]
if request.form["deviceName"]
else device.name
)
device.description = (
request.form["deviceDescription"]
if request.form["deviceName"]
else device.description
)
device.host = (
request.form["deviceHost"].replace(" ", "")
if request.form["deviceName"]
else device.host
)
device.ssh_username = (
request.form["deviceUser"].replace(" ", "")
if request.form["deviceName"]
else device.ssh_username
)
device.ssh_password = (
request.form["devicePassword"]
if request.form["deviceName"]
else device.ssh_password
)
error = device.validate()
if error:
return render_template(
"devices/edit.html",
device=device,
error=error,
title=title,
current_user=current_user,
)
else:
device.update()
return redirect(url_for("devices", id=device.id))
else:
return render_template(
"devices/edit.html",
device=device,
title=title,
current_user=current_user,
)
except:
error = "An issue was raised, IP entered might belong to an existing device"
return render_template(
"devices/edit.html",
device=device,
error=error,
title=title,
current_user=current_user,
)
@app.route("/devices/<id>/delete", methods=["POST"])
@login_required
def delete_device(id=None):
device = Device.query.get(id)
if device:
device.delete()
return redirect(url_for("devices"))
else:
return None
@app.route("/devices/update_interfaces", methods=["POST"])
@login_required
def update_device_interfaces():
return Device.query.get(request.get_json()["id"]).update_interfaces()
@app.route("/devices/test_connection", methods=["POST"])
def test_device_connection():
credentials = request.get_json()
if credentials:
connection = Connection(
host=credentials["host"].replace(" ", ""),
username=credentials["ssh_username"],
password=credentials["ssh_password"],
)
connection_status = connection.try_connection()
return connection_status
else:
return None
"""
DEVICE INTERFACES
"""
@app.route("/interfaces/<id>", methods=["GET"])
@login_required
def interfaces(id=None):
if id:
interface = Interface.query.get(int(id))
title = "%r | %r" % (interface.name, interface.device.name)
return render_template(
"interfaces/show.html",
title=title,
interface=interface,
current_user=current_user,
)
@app.route("/interfaces/<id>/update", methods=["GET", "POST"])
@login_required
def update_interface(id=None):
interface = Interface.query.get(id)
title = "Update | %r | %r" % (interface.name, interface.device.name)
if request.method == "POST":
interface.set(
description=request.form["description"], bandwidth=request.form["bandwidth"]
)
policy = Policy.query.get(int(request.form["policy_id"]))
if policy:
interface.policy = policy
error = interface.validate()
error_check_policy = interface.validate_policy_setting(policy)
if error:
return render_template(
"interfaces/edit.html",
interface=interface,
error=error,
title=title,
current_user=current_user,
)
elif error_check_policy:
return render_template(
"interfaces/edit.html",
interface=interface,
error=error_check_policy,
title=title,
current_user=current_user,
)
else:
connection = Connection(
host=interface.device.host,
username=interface.device.ssh_username,
password=interface.device.ssh_password,
)
connection.generate_policy_to_int(interface.policy, interface)
if (
connection.check_policy_interface(interface.name, interface.policy.name)
== True
):
interface.update()
return redirect(url_for("interfaces", id=interface.id))
else:
return render_template(
"interfaces/edit.html",
interface=interface,
error="This policy is INCOMPATIBLE with this interface. Check your policy and interface settings then try again.",
title=title,
current_user=current_user,
)
else:
return render_template(
"interfaces/edit.html",
interface=interface,
title=title,
policies=Policy.query.all(),
current_user=current_user,
)
@app.route("/interface/<id>/delete", methods=["POST"])
@login_required
def delete_interface(id=None):
interface = Interface.query.get(id)
if interface:
interface.delete()
return redirect(url_for("devices", id=interface.device.id))
else:
return None
"""
SERVICES VIEWS
"""
@app.route("/services/", methods=["GET"])
@app.route("/services/<id>", methods=["GET"])
@login_required
def services(id=None):
if id:
feedback = (
request.args.get("feedback") if request.args.get("feedback") else None
)
service = Service.query.get(int(id))
title = "%r | Services" % service.name
return render_template(
"services/show.html",
title=title,
service=service,
feedback=feedback,
current_user=current_user,
)
else:
title = "Services"
return render_template(
"services/index.html",
title=title,
services=Service.query.all(),
current_user=current_user,
)
@app.route("/services/new/", methods=["GET", "POST"])
@login_required
def new_service():
title = "New | Services"
if request.method == "POST":
new_service = Service(
name=request.form["serviceName"] if request.form["serviceName"] else None,
description=request.form["serviceDescription"]
if request.form["serviceDescription"]
else None,
match_ips=request.form["serviceIps"].replace(" ", "")
if request.form["serviceIps"]
else None,
match_tcp_ports=request.form["serviceTCPPorts"].replace(" ", "")
if request.form["serviceTCPPorts"]
else None,
match_udp_ports=request.form["serviceUDPPorts"].replace(" ", "")
if request.form["serviceUDPPorts"]
else None,
match_dscp=request.form["serviceDSCPsValues"].replace(" ", "")
if request.form["serviceDSCPsValues"]
else None,
match_protocol=request.form["protocol"].replace(" ", "")
if request.form["protocol"]
else None,
)
error = new_service.validate()
if error:
return render_template(
"services/new.html",
service=new_service,
error=error,
title=title,
current_user=current_user,
)
else:
new_service.create()
return redirect(url_for("services", id=new_service.id))
else:
return render_template(
"services/new.html",
service=Service(),
title=title,
current_user=current_user,
)
@app.route("/services/<id>/update", methods=["GET", "POST"])
@login_required
def update_service(id=None):
service = Service.query.get(id)
title = "Update | %r | Services" % service.name
if request.method == "POST":
service.name = (
request.form["serviceName"] if request.form["serviceName"] else service.name
)
service.description = (
request.form["serviceDescription"]
if request.form["serviceDescription"]
else service.description
)
service.match_ips = (
request.form["serviceIps"].replace(" ", "")
if request.form["serviceIps"]
else service.match_ips
)
service.match_tcp_ports = (
request.form["serviceTCPPorts"].replace(" ", "")
if request.form["serviceTCPPorts"]
else service.match_tcp_ports
)
service.match_udp_ports = (
request.form["serviceUDPPorts"].replace(" ", "")
if request.form["serviceUDPPorts"]
else service.match_udp_ports
)
service.match_dscp = (
request.form["serviceDSCPsValues"].replace(" ", "")
if request.form["serviceDSCPsValues"]
else service.match_dscp
)
service.match_protocol = (
request.form["protocol"].replace(" ", "")
if request.form["protocol"]
else service.match_protocol
)
error = service.validate()
if error:
return render_template(
"services/edit.html",
service=service,
error=error,
title=title,
current_user=current_user,
)
else:
service.update()
return redirect(url_for("services", id=service.id))
else:
return render_template(
"services/edit.html",
service=service,
title=title,
current_user=current_user,
)
@app.route("/services/<id>/delete", methods=["POST"])
@login_required
def delete_service(id=None):
service = Service.query.get(id)
if service:
service.delete()
return redirect(url_for("services"))
else:
return None
"""
POLICY VIEWS
"""
@app.route("/policies/", methods=["GET"])
@app.route("/policies/<id>", methods=["GET"])
@login_required
def policies(id=None):
if id:
feedback = (
request.args.get("feedback") if request.args.get("feedback") else None
)
policy = Policy.query.get(int(id))
title = "%r | Policies" % policy.name
return render_template(
"policies/show.html",
title=title,
policy=policy,
feedback=feedback,
current_user=current_user,
)
else:
title = "Policies"
return render_template(
"policies/index.html",
title=title,
policies=Policy.query.all(),
current_user=current_user,
)
@app.route("/policies/new/", methods=["GET", "POST"])
@login_required
def new_policy():
title = "New | Policies"
if request.method == "POST":
policy = request.get_json()
new_policy = Policy(
name=policy["name"] if policy["name"] else None,
description=policy["description"] if policy["description"] else None,
)
error = new_policy.validate()
if error:
return render_template(
"policies/new.html",
policy=new_policy,
error=error,
title=title,
current_user=current_user,
)
else:
new_policy.create()
for service in policy["services"]:
service_policy_settings = ServicePolicySettings(
policy_id=new_policy.id,
service_id=service["service_id"],
min_bandwidth=service["min_bandwidth"],
max_bandwidth=service["max_bandwidth"],
mark_dscp=service["mark_dscp"],
)
service_policy_settings.create()
return redirect(url_for("policies", id=new_policy.id))
else:
return render_template(
"policies/new.html", policy=Policy(), title=title, current_user=current_user
)
@app.route("/policies/<id>/update", methods=["GET", "POST"])
@login_required
def update_policy(id=None):
policy = Policy.query.get(id)
title = "Update | %r | Policies" % policy.name
if request.method == "POST":
policy_data = request.get_json()
policy.name = policy_data["name"] if policy_data["name"] else policy.name
policy.description = (
policy_data["description"]
if policy_data["description"]
else policy.description
)
error = policy.validate()
if error:
return render_template(
"policies/edit.html",
policy=policy,
error=error,
title=title,
current_user=current_user,
)
else:
policy.delete_services_settings()
for service_settings in policy_data["services"]:
service_policy_settings = ServicePolicySettings(
policy_id=policy.id,
service_id=service_settings["service_id"],
min_bandwidth=service_settings["min_bandwidth"],
max_bandwidth=service_settings["max_bandwidth"],
mark_dscp=service_settings["mark_dscp"],
)
service_policy_settings.create()
policy.changed = True
policy.update()
return redirect(url_for("policies", id=policy.id))
else:
return render_template(
"policies/edit.html", policy=policy, title=title, current_user=current_user
)
@app.route("/policies/<id>/delete", methods=["POST"])
@login_required
def delete_policy(id=None):
policy = Policy.query.get(id)
if policy:
policy.delete()
return redirect(url_for("policies"))
else:
return None
"""USERS VIEWS"""
@app.route("/users/", methods=["GET"])
@app.route("/users/<id>", methods=["GET"])
@login_required
def users(id=None):
if id:
user = User.query.get(int(id))
title = "{}".format(user.name)
return render_template("users/show.html", title=title, user=user,)
else:
return None
"""API"""
@app.route("/api/interfaces", methods=["GET"])
@app.route("/api/interfaces/<id>", methods=["GET"])
def get_interfaces(id=None):
if Interface.query.get(id):
interface = Interface.query.get(id)
class_names = []
since = datetime.now() - timedelta(hours=1)
for stat in (
Stat.query.filter(
Stat.created_on >= since, Stat.interface_id == interface.id
)
.group_by(Stat.class_name)
.all()
):
class_names.append(stat.class_name)
data = {}
for class_name in class_names:
stats = (
Stat.query.filter(
Stat.created_on >= since,
Stat.interface_id == interface.id,
Stat.class_name == class_name,
)
.order_by(-Stat.id)
.limit(50)
.all()
)
stats.reverse()
data[class_name] = {}
data[class_name]["dates"] = []
data[class_name]["offered_rates"] = []
data[class_name]["drop_rates"] = []
for stat in stats:
data[class_name]["dates"].append(stat.created_on)
data[class_name]["offered_rates"].append(stat.offered_rate)
data[class_name]["drop_rates"].append(stat.drop_rate)
return jsonify({"id": interface.id, "name": interface.name, "data": data})
elif id:
return jsonify({"error": "404", "response": "Interface not found"})
else:
interfaces_list = []
for interface in Interface.query.all():
interfaces_list.append({"id": interface.id, "name": interface.name})
return jsonify(interfaces)
@app.route("/api/services", methods=["GET"])
@app.route("/api/services/<id>", methods=["GET"])
def get_services(id=None):
if Service.query.get(id):
service = Service.query.get(id)
return jsonify({"id": service.id, "name": service.name})
elif id:
return jsonify({"error": "404", "response": "Service not found"})
else:
services_list = []
for service in Service.query.all():
services_list.append({"id": service.id, "name": service.name})
return jsonify(services_list)
@app.route("/api/devices/state", methods=["GET"])
@app.route("/api/devices/<id>/state", methods=["GET"])
def get_devices_state(id=None):
if Device.query.get(id):
device = Device.query.get(id)
return jsonify({"id": device.id, "state": device.state})
elif id:
return jsonify({"error": "404", "response": "Device not found"})
else:
devices_state_list = []
for device in Device.query.all():
devices_state_list.append({"id": device.id, "state": device.state})
return jsonify(devices_state_list)
@app.route("/api/policies", methods=["GET"])
@app.route("/api/policies/<id>", methods=["GET"])
def get_policies(id=None):
if Policy.query.get(id):
policy = Policy.query.get(id)
return jsonify({"id": policy.id, "name": policy.name})
elif id:
return jsonify({"error": "404", "response": "Service not found"})
else:
policies_list = []
for policy in Policy.query.all():
policies_list.append({"id": policy.id, "name": policy.name})
return jsonify(policies_list)
@app.route("/api/interfaces/<id>/update", methods=["POST"])
def api_update_interface(id=None):
try:
payload = request.get_json()
interface = Interface.query.get(id)
if interface.policy_schedules:
for old_policy_schedule in interface.policy_schedules:
old_policy_schedule.delete()
if payload["policy_schedules"]:
for schedule in payload["policy_schedules"]:
new = InterfacePolicySchedule(
policy_id=schedule["policy_id"],
interface_id=interface.id,
time=datetime.strptime(schedule["time"], "%H:%M").time()
if schedule["time"]
else None,
day=schedule["day"] if schedule["day"] else None,
)
new.create()
policy = Policy.query.get(int(payload["policy_id"]))
interface.policy = policy if policy else interface.policy
interface.set(description=payload["description"], bandwidth=int(payload["bandwidth"]))
error_check_policy = interface.validate_policy_setting(policy)
error = interface.validate()
if error:
return jsonify(
{
"status": "error",
"response": "Validation failed, check the new bandwidth or description",
}
)
elif error_check_policy:
return jsonify({"status": "error", "response": error_check_policy,})
else:
interface.update()
connection = Connection(
host=interface.device.host,
username=interface.device.ssh_username,
password=interface.device.ssh_password,
)
commands = connection.generate_policy_to_int(interface.policy, interface)
was_succesful = connection.check_policy_interface(
interface.name, interface.policy.name
)
if commands and was_succesful == True:
return jsonify(
{
"status": "success",
"response": "The policy was applied successfuly",
"commands": commands,
}
)
elif commands:
return jsonify(
{
"status": "error",
"response": "This policy and interface are incompatible. Check your interface and policy settings then try again",
"commands": commands,
}
)
else:
return jsonify(
{
"status": "error",
"response": "The connection to the router was lost.",
}
)
except Exception as error:
return jsonify({"status": "error", "response": "{}".format(error)})