-
Notifications
You must be signed in to change notification settings - Fork 21
/
views.py
1761 lines (1507 loc) · 74.7 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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, JsonResponse
# from django.core.urlresolvers import reverse
from django.urls import reverse
from django.views import generic
from django.core import serializers
from django.db.models import Avg, When, Sum, Case, FloatField, Count
from django.db import models as django_models
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.cache import patch_cache_control, cache_control
from django.utils.decorators import method_decorator
from django.conf import settings as conf_settings
from datetime import datetime, date, timedelta, time, timezone
import pandas as pd
import pytz
import json
import arrow
from email.errors import HeaderParseError
from smtplib import SMTPException
from django.db import transaction, IntegrityError
from django.core.mail import send_mail
from .const import ConfirmationEmail, ChangePasswordEmail, StrErrors, Msg, POOL, std_response
import redis
conn = redis.Redis(connection_pool=POOL)
from rest_framework.status import (
HTTP_201_CREATED,
HTTP_400_BAD_REQUEST,
HTTP_401_UNAUTHORIZED,
HTTP_403_FORBIDDEN,
HTTP_404_NOT_FOUND,
HTTP_410_GONE,
HTTP_409_CONFLICT,
HTTP_200_OK,
HTTP_202_ACCEPTED
)
from .models import ASN, Country, Delay, Forwarding, Delay_alarms, Forwarding_alarms, Disco_events, Disco_probes, Hegemony, HegemonyCone, Atlas_delay, Atlas_location, Atlas_delay_alarms, Hegemony_alarms, Hegemony_country, Hegemony_prefix, Metis_atlas_selection, Metis_atlas_deployment, TR_hegemony
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import generics
from rest_framework.exceptions import ParseError
from .serializers import *
from django_filters import rest_framework as filters
import django_filters
from django.db.models import Q, F
from rest_framework.views import APIView
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from .models import IHRUser, Country, ASN, Atlas_location,IHRUser_Channel
from rest_framework.authtoken.models import Token
# by default shows only one week of data
LAST_DEFAULT = 6
HEGE_GRANULARITY = 15
DEFAULT_MAX_RANGE = 7
########## Get help_text from model ###############
class HelpfulFilterSet(filters.FilterSet):
@classmethod
def filter_for_field(cls, f, name, lookup_expr):
filter = super(HelpfulFilterSet, cls).filter_for_field(f, name, lookup_expr)
filter.extra['help_text'] = f.help_text
return filter
########### Custom Pagination ##########
from rest_framework.pagination import PageNumberPagination
class StandardResultsSetPagination(PageNumberPagination):
page_size_query_param = 'limit'
############ API ##########
def check_timebin(query_params, max_range=DEFAULT_MAX_RANGE):
""" Check if the query contain timebin parameters"""
# check if it contains only the timebin field
timebin = query_params.get('timebin', None)
if timebin is not None:
return True
timebin_gte = query_params.get('timebin__gte', None)
timebin_lte = query_params.get('timebin__lte', None)
# check if it contains any of the timebin fields
if timebin_gte is None and timebin_lte is None:
raise ParseError("No timebin parameter. Please provide a timebin value or a range of values with timebin__lte and timebin__gte.")
# check if the range is complete
if timebin_gte is None or timebin_lte is None:
raise ParseError("Invalid timebin range. Please provide both timebin__lte and timebin__gte.")
# check if the range is longer than max_range
try:
start = arrow.get(timebin_gte)
end = arrow.get(timebin_lte)
except:
raise ParseError("Could not parse the timebin parameters.")
if (end-start).days > max_range:
raise ParseError("The given timebin range is too large. Should be less than {} days.".format(max_range))
return True
def check_or_fields(query_params, fields):
""" Check if the query contain any of the given fields"""
# check if it contains any of the fields
checks = [query_params.get(f, None) is not None for f in fields]
if not any(checks):
raise ParseError("Required parameter missing. Please provide one of the following parameter: {}".format(fields))
return True
### Filters:
# Generic filter for a list of values:
class ListFilter(django_filters.CharFilter):
def sanitize(self, value_list):
"""
remove empty items and parse them
"""
return [self.customize(v) for v in value_list if v!=""]
def customize(self, value):
return value
def filter(self, qs, value):
multiple_vals = self.sanitize(value.split(","))
if len(multiple_vals) > 0:
par = {self.field_name + "__in": multiple_vals}
qs = qs.filter(**par)
return qs
class ListIntegerFilter(ListFilter):
def customize(self, value):
return int(value)
class ListStringFilter(ListFilter):
def filter(self, qs, value):
multiple_vals = self.sanitize(value.split("|"))
if len(multiple_vals) > 0:
par = {self.field_name + "__in": multiple_vals}
qs = qs.filter(**par)
return qs
class ListNetworkKeyFilter(ListFilter):
def filter(self, qs, value):
queries = None
multiple_vals = self.sanitize(value.split("|"))
if len(multiple_vals) > 0:
first_key = multiple_vals[0]
queries = Q(
**{
self.field_name+'__type': first_key[:2],
self.field_name+'__af': int(first_key[2]),
self.field_name+'__name': first_key[3:]
})
# For each given keys
for key in multiple_vals[1:]:
queries |= Q(
**{
self.field_name+'__type': key[:2],
self.field_name+'__af': int(key[2]),
self.field_name+'__name': key[3:]
})
qs = qs.filter(queries)
return qs
class SameASNAndOrigin(django_filters.CharFilter):
def filter(self, qs, value):
if value in ['true', 'True', '1']:
qs = qs.filter(originasn_id=F('asn_id'))
return qs
class NetworkDelayFilter(HelpfulFilterSet):
startpoint_name = ListStringFilter(field_name='startpoint__name', help_text="Starting location name. It can be a single value or a list of values separated by the pipe character (i.e. | ). The meaning of values dependend on the location type: <ul><li>type=AS: ASN</li><li>type=CT: city name, region name, country code</li><li>type=PB: Atlas Probe ID</li><li>type=IP: IP version (4 or 6)</li></ul> ")
endpoint_name = ListStringFilter(field_name='endpoint__name', help_text="Ending location name. It can be a single value or a list of values separated by the pipe character (i.e. | ). The meaning of values dependend on the location type: <ul><li>type=AS: ASN</li><li>type=CT: city name, region name, country code</li><li>type=PB: Atlas Probe ID</li><li>type=IP: IP version (4 or 6)</li></ul> ")
startpoint_type= django_filters.CharFilter(field_name='startpoint__type', help_text="Type of starting location. Possible values are: <ul><li>AS: Autonomous System</li><li>CT: City</li><li>PB: Atlas Probe</li><li>IP: Whole IP space</li></ul>")
endpoint_type= django_filters.CharFilter(field_name='endpoint__type', help_text="Type of ending location. Possible values are: <ul><li>AS: Autonomous System</li><li>CT: City</li><li>PB: Atlas Probe</li><li>IP: Whole IP space</li></ul>")
startpoint_af= django_filters.NumberFilter(field_name='startpoint__af', help_text="Address Family (IP version), values are either 4 or 6.")
endpoint_af= django_filters.NumberFilter(field_name='endpoint__af', help_text="Address Family (IP version), values are either 4 or 6.")
startpoint_key = ListNetworkKeyFilter(field_name='startpoint', help_text="List of starting location key, separated by the pip character (i.e. | ). A location key is a concatenation of a type, af, and name. For example, CT4New York City, New York, US|AS4174 (yes, the last key corresponds to AS174!).")
endpoint_key = ListNetworkKeyFilter(field_name='endpoint', help_text="List of ending location key, separated by the pip character (i.e. | ). A location key is a concatenation of a type, af, and name. For example, CT4New York City, New York, US|AS4174 (yes, the last key corresponds to AS174!).")
class Meta:
model = Atlas_delay
fields = {
'timebin': ['exact', 'lte', 'gte'],
'startpoint_name': ['exact'],
'endpoint_name': ['exact'],
'startpoint_type': ['exact'],
'endpoint_type': ['exact'],
'startpoint_af': ['exact'],
'endpoint_af': ['exact'],
'startpoint_key': ['exact'],
'endpoint_key': ['exact'],
'median': ['exact', 'lte', 'gte'],
}
ordering_fields = ('timebin', 'startpoint_name', 'endpoint_name')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class NetworkDelayAlarmsFilter(HelpfulFilterSet):
startpoint_name = ListStringFilter(field_name='startpoint__name', help_text="Starting location name. It can be a single value or a list of values separated by the pipe character (i.e. | ). The meaning of values dependend on the location type: <ul><li>type=AS: ASN</li><li>type=CT: city name, region name, country code</li><li>type=PB: Atlas Probe ID</li><li>type=IP: IP version (4 or 6)</li></ul> ")
endpoint_name = ListStringFilter(field_name='endpoint__name', help_text="Ending location name. It can be a single value or a list of values separated by the pipe character (i.e. | ). The meaning of values dependend on the location type: <ul><li>type=AS: ASN</li><li>type=CT: city name, region name, country code</li><li>type=PB: Atlas Probe ID</li><li>type=IP: IP version (4 or 6)</li></ul> ")
startpoint_type= django_filters.CharFilter(field_name='startpoint__type', help_text="Type of starting location. Possible values are: <ul><li>AS: Autonomous System</li><li>CT: City</li><li>PB: Atlas Probe</li><li>IP: Whole IP space</li></ul>")
endpoint_type= django_filters.CharFilter(field_name='endpoint__type', help_text="Type of ending location. Possible values are: <ul><li>AS: Autonomous System</li><li>CT: City</li><li>PB: Atlas Probe</li><li>IP: Whole IP space</li></ul>")
startpoint_af= django_filters.NumberFilter(field_name='startpoint__af', help_text="Address Family (IP version), values are either 4 or 6.")
endpoint_af= django_filters.NumberFilter(field_name='endpoint__af', help_text="Address Family (IP version), values are either 4 or 6.")
startpoint_key = ListNetworkKeyFilter(field_name='startpoint', help_text="List of starting location key, separated by the pip character (i.e. | ). A location key is a concatenation of a type, af, and name. For example, CT4New York City, New York, US|AS4174 (yes, the last key corresponds to AS174!).")
endpoint_key = ListNetworkKeyFilter(field_name='endpoint', help_text="List of ending location key, separated by the pip character (i.e. | ). A location key is a concatenation of a type, af, and name. For example, CT4New York City, New York, US|AS4174 (yes, the last key corresponds to AS174!).")
class Meta:
model = Atlas_delay_alarms
fields = {
'timebin': ['exact', 'lte', 'gte'],
'startpoint_name': ['exact'],
'endpoint_name': ['exact'],
'startpoint_type': ['exact'],
'endpoint_type': ['exact'],
'startpoint_af': ['exact'],
'endpoint_af': ['exact'],
'startpoint_key': ['exact'],
'endpoint_key': ['exact'],
'deviation': ['lte', 'gte'],
}
ordering_fields = ('timebin', 'startpoint_name', 'endpoint_name')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class HegemonyFilter(HelpfulFilterSet):
asn = ListIntegerFilter(help_text="Dependency. Transit network commonly seen in BGP paths towards originasn. Can be a single value or a list of comma separated values. ")
originasn = ListIntegerFilter(help_text="Dependent network, it can be any public ASN. Can be a single value or a list of comma separated values. Retrieve all dependencies of a network by setting a single value and a timebin.")
class Meta:
model = Hegemony
fields = {
'timebin': ['exact', 'lte', 'gte'],
'hege': ['exact', 'lte', 'gte'],
'af': ['exact'],
}
ordering_fields = ('timebin', 'originasn', 'hege', 'af')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class HegemonyAlarmsFilter(HelpfulFilterSet):
asn = ListIntegerFilter(help_text="ASN of the anomalous dependency (transit network). Can be a single value or a list of comma separated values.")
originasn = ListIntegerFilter(help_text="ASN of the reported dependent network. Can be a single value or a list of comma separated values.")
class Meta:
model = Hegemony_alarms
fields = {
'timebin': ['exact', 'lte', 'gte'],
'af': ['exact'],
'deviation': ['lte', 'gte'],
}
ordering_fields = ('timebin', 'originasn', 'deviation', 'af')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class HegemonyCountryFilter(HelpfulFilterSet):
asn = ListIntegerFilter(help_text="Dependency. Network commonly seen in BGP paths towards monitored country. Can be a single value or a list of comma separated values.")
country = ListFilter(help_text="Monitored country or region (e.g. EU and AP) as defined by its set of ASes registered in registeries delegated files. Can be a single value or a list of comma separated values. Retrieve all dependencies of a country by setting a single value and a timebin.")
weightscheme = django_filters.CharFilter(help_text="Scheme used to aggregate AS Hegemony scores. 'as' gives equal weight to each AS, 'eyeball' put emphasis on large eyeball networks.")
transitonly = django_filters.BooleanFilter(help_text="True means that the last AS (origin AS) in BGP paths is ignored, thus focusing only on transit ASes.")
class Meta:
model = Hegemony_country
fields = {
'timebin': ['exact', 'lte', 'gte'],
'hege': ['exact', 'lte', 'gte'],
'af': ['exact'],
}
ordering_fields = ('timebin', 'country', 'hege', 'af')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class HegemonyPrefixFilter(HelpfulFilterSet):
prefix = ListFilter(help_text="Monitored prefix, it can be any globally reachable prefix. Can be a single value or a list of comma separated values.")
originasn = ListIntegerFilter(help_text="Origin network, it can be any public ASN. Can be a single value or a list of comma separated values.")
asn = ListIntegerFilter(help_text="Dependency. Network commonly seen in BGP paths towards monitored prefix. Can be a single value or a list of comma separated values.")
country = ListFilter(help_text="Country code for prefixes as reported by Maxmind's Geolite2 geolocation database. Can be a single value or a list of comma separated values. Retrieve all dependencies of a country by setting a single value and a timebin.")
rpki_status = django_filters.CharFilter(lookup_expr='contains', help_text="Route origin validation state for the monitored prefix and origin AS using RPKI.")
irr_status = django_filters.CharFilter(lookup_expr='contains', help_text="Route origin validation state for the monitored prefix and origin AS using IRR.")
delegated_prefix_status = django_filters.CharFilter(lookup_expr='contains', help_text="Status of the monitored prefix in the RIR's delegated stats. Status other than 'assigned' are usually considered as bogons.")
delegated_asn_status = django_filters.CharFilter(lookup_expr='contains', help_text="Status of the origin ASN in the RIR's delegated stats. Status other than 'assigned' are usually considered as bogons.")
origin_only = SameASNAndOrigin(help_text="Filter out dependency results and provide only prefix/origin ASN results")
class Meta:
model = Hegemony_prefix
fields = {
'timebin': ['exact', 'lte', 'gte'],
'hege': ['exact', 'lte', 'gte'],
'af': ['exact'],
}
ordering_fields = ('timebin', 'prefix', 'hege', 'af')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class NetworkDelayLocationsFilter(HelpfulFilterSet):
name = django_filters.CharFilter(lookup_expr='icontains', help_text="Location identifier, can be searched by substring. The meaning of these values dependend on the location type: <ul><li>type=AS: ASN</li><li>type=CT: city name, region name, country code</li><li>type=PB: Atlas Probe ID</li><li>type=IP: IP version (4 or 6)</li></ul>")
type = django_filters.CharFilter(help_text="Type of location. Possible values are: <ul><li>AS: Autonomous System</li><li>CT: City</li><li>PB: Atlas Probe</li><li>IP: Whole IP space</li></ul>")
af = django_filters.NumberFilter(help_text="Address Family (IP version), values are either 4 or 6.")
class Meta:
model = Atlas_location
fields = ["type", "name", "af"]
ordering_fields = ("name",)
class NetworkFilter(HelpfulFilterSet):
name = django_filters.CharFilter(lookup_expr='icontains', help_text='Search for a substring in networks name.')
number = ListIntegerFilter(help_text='Search by ASN or IXP ID. It can be either a single value (e.g. 2497) or a list of comma separated values (e.g. 2497,2500,2501)')
search = django_filters.CharFilter(method='asn_or_number', help_text='Search for both ASN/IXPID and substring in names.')
def asn_or_number(self, queryset, name, value):
if value.startswith("AS") or value.startswith("IX"):
try:
tmp = int(value[2:])
value = value[2:]
except ValueError:
pass
return queryset.filter(
Q(number__contains=value) | Q(name__icontains=value)
)
class Meta:
model = ASN
fields = {
"name": ['exact'],
"number": ['exact', 'lte', 'gte'],
}
ordering_fields = ('number',)
class CountryFilter(HelpfulFilterSet):
name = django_filters.CharFilter(lookup_expr='icontains', help_text='Search for a substring in countries name.')
code = django_filters.CharFilter(help_text='Search by country code.')
class Meta:
model = Country
fields = ["name", "code"]
ordering_fields = ("code",)
class DelayFilter(HelpfulFilterSet):
"""
Explain delay filter here
"""
asn = ListIntegerFilter(help_text="ASN or IXP ID of the monitored network (see number in /network/). Can be a single value or a list of comma separated values.")
class Meta:
model = Delay
fields = {
'timebin': ['exact', 'lte', 'gte'],
'magnitude': ['exact'],
}
ordering_fields = ('timebin', 'magnitude')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class ForwardingFilter(HelpfulFilterSet):
asn = ListIntegerFilter(help_text="ASN or IXP ID of the monitored network (see number in /network/). Can be a single value or a list of comma separated values.")
class Meta:
model = Forwarding
fields = {
'timebin': ['exact', 'lte', 'gte'],
'magnitude': ['exact'],
}
ordering_fields = ('timebin', 'magnitude')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class DelayAlarmsFilter(HelpfulFilterSet):
asn = ListIntegerFilter(help_text="ASN or IXP ID of the monitored network (see number in /network/). Can be a single value or a list of comma separated values.")
class Meta:
model = Delay_alarms
fields = {
'timebin': ['exact', 'lte', 'gte'],
'deviation': ['exact', 'lte', 'gte'],
'diffmedian': ['exact', 'lte', 'gte'],
'medianrtt': ['exact', 'lte', 'gte'],
'nbprobes': ['exact', 'lte', 'gte'],
'link': ['exact', 'contains'],
}
ordering_fields = ('timebin', 'deviation', 'nbprobes', 'diffmedian', 'medianrtt')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class ForwardingAlarmsFilter(HelpfulFilterSet):
asn = ListIntegerFilter(help_text="ASN or IXP ID of the monitored network (see number in /network/). Can be a single value or a list of comma separated values.")
class Meta:
model = Forwarding_alarms
fields = {
'timebin': ['exact', 'lte', 'gte'],
'correlation': ['exact', 'lte', 'gte'],
'responsibility': ['exact', 'lte', 'gte'],
'ip': ['exact', 'contains'],
'previoushop': ['exact', 'contains'],
}
ordering_fields = ('timebin', 'responsibility', 'correlation', 'ip', 'previoushop')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class DiscoEventsFilter(HelpfulFilterSet):
class Meta:
model = Disco_events
fields = {
'streamname': ['exact'],
'streamtype': ['exact'],
'starttime': ['exact', 'lte', 'gte'],
'endtime': ['exact', 'lte', 'gte'],
'avglevel': ['exact', 'lte', 'gte'],
'nbdiscoprobes': ['exact', 'lte', 'gte'],
'totalprobes': ['exact', 'lte', 'gte'],
'ongoing': ['exact'],
}
ordering_fields = ('starttime', 'endtime', 'avglevel', 'nbdiscoprobes')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class HegemonyConeFilter(HelpfulFilterSet):
asn = ListIntegerFilter(help_text="Autonomous System Number (ASN). Can be a single value or a list of comma separated values.")
class Meta:
model = HegemonyCone
fields = {
'timebin': ['exact', 'lte', 'gte'],
'af': ['exact'],
}
ordering_fields = ('timebin', 'asn', 'af')
filter_overrides = {
django_models.DateTimeField: {
'filter_class': filters.IsoDateTimeFilter
},
}
class DiscoProbesFilter(HelpfulFilterSet):
probe_id = ListIntegerFilter(help_text="List of probe ids separated by commas.")
event = ListIntegerFilter(help_text="List of event ids separated by commas.")
class Meta:
model = Disco_probes
fields = {}
ordering_fields = ('starttime', 'endtime', 'level')
class UserLoginView(APIView):
@swagger_auto_schema(
operation_description="apiview post description override",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['email', "password"],
properties={
'email': openapi.Schema(type=openapi.TYPE_STRING),
'password': openapi.Schema(type=openapi.TYPE_STRING)
},
),
security=[]
)
def post(self, request, *args, **kwargs):
ret = {}
print("################")
try:
serializer = UserLoginSerializer(data=request.data)
if serializer.is_valid():
print("request.data:", request.data)
email = serializer.validated_data['email']
password = serializer.validated_data['password']
obj = IHRUser.objects.filter(email=email).first()
if not obj:
ret['code'] = HTTP_202_ACCEPTED
ret['msg'] = Msg.USER_NOT_EXIST
return JsonResponse(ret, status=HTTP_202_ACCEPTED)
else:
UserModel = get_user_model()
user = UserModel.objects.get(email=email)
if user.check_password(password):
ret['code'] = HTTP_200_OK
ret['msg'] = Msg.LOGIN_SUCCEEDED
try:
token,_ = Token.objects.get_or_create(user=obj)
ret['token'] = token.key
conn.set(f"Login_{email}", token.key)
return JsonResponse(ret, status=HTTP_200_OK)
except (KeyError, IHRUser.DoesNotExist) as e:
return std_response(StrErrors.WRONG_DATA, HTTP_400_BAD_REQUEST)
else:
ret['code'] = HTTP_202_ACCEPTED
ret['msg'] = Msg.LOGIN_FAILED
return JsonResponse(ret, status=HTTP_202_ACCEPTED)
else:
ret['code'] = HTTP_401_UNAUTHORIZED
ret['msg'] = Msg.INVALID_DATA
return JsonResponse(ret, status=HTTP_401_UNAUTHORIZED)
except Exception as e:
print(e)
ret['code'] = HTTP_404_NOT_FOUND
ret['msg'] = Msg.REQUEST_EXCEPTION
return JsonResponse(ret)
class UserShowView(APIView):
@swagger_auto_schema(
operation_description="apiview post description override",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=[]
),
security=[]
)
def post(self, request, *args, **kwargs):
ret = {}
try:
token = Token.objects.get(key=request.META.get("HTTP_AUTHORIZATION").split('=')[-1])
user_login = conn.get(f"Login_{token.user}")
if user_login:
user = IHRUser.objects.get(email=token.user)
serializer = UserSerializer(user)
ret['code'] = HTTP_200_OK
ret['msg'] = Msg.LOGIN_SUCCEEDED
ret['data'] = serializer.data
return JsonResponse(ret, status=HTTP_200_OK)
else:
ret['code'] = HTTP_401_UNAUTHORIZED
ret['msg'] = Msg.LOGIN_FAILED
return JsonResponse(ret, status=HTTP_401_UNAUTHORIZED)
except Exception as e:
print(e)
ret['code'] = HTTP_404_NOT_FOUND
ret['msg'] = Msg.REQUEST_EXCEPTION
return JsonResponse(ret)
class UserLogoutView(APIView):
@swagger_auto_schema(
operation_description="apiview post description override",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=[]
),
security=[]
)
def post(self, request, *args, **kwargs):
ret = {}
try:
token = Token.objects.get(key=request.META.get("HTTP_AUTHORIZATION").split('=')[-1])
conn.delete(f"Login_{token.user}")
user_login = conn.get(f"Login_{token.user}")
#print(user_login)
#request.user.auth_token.delete()
ret['code'] = HTTP_200_OK
ret['msg'] = Msg.LOGOUT_SUCCEEDED
return JsonResponse(ret, status=HTTP_202_ACCEPTED)
except Exception as e:
print(e)
ret['code'] = HTTP_404_NOT_FOUND
ret['msg'] = Msg.REQUEST_EXCEPTION
return JsonResponse(ret, status=HTTP_404_NOT_FOUND)
class UserChangePasswordView(APIView):
@swagger_auto_schema(
operation_description="apiview post description override",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['email', "password", "new_password"],
properties={
'email': openapi.Schema(type=openapi.TYPE_STRING),
'password': openapi.Schema(type=openapi.TYPE_STRING),
'new_password': openapi.Schema(type=openapi.TYPE_STRING)
},
),
security=[]
)
def post(self, request, *args, **kwargs):
ret = {}
try:
serializer = UserChangePasswordSerializer(data=request.data)
if serializer.is_valid():
print("request.data:", request.data)
email = serializer.validated_data['email']
password = serializer.validated_data['password']
new_password = serializer.validated_data['new_password']
obj = IHRUser.objects.filter(email=email).first()
if not obj:
ret['code'] = HTTP_202_ACCEPTED
ret['msg'] = Msg.USER_NOT_EXIST
return JsonResponse(ret, status=HTTP_202_ACCEPTED)
else:
UserModel = get_user_model()
user = UserModel.objects.get(email=email)
if user.check_password(password):
ret['code'] = HTTP_200_OK
ret['msg'] = Msg.CHANGE_PASSWORD_SUCCEEDED
try:
obj.password = new_password
obj.save()
return JsonResponse(ret)
except (KeyError, IHRUser.DoesNotExist) as e:
return std_response(StrErrors.WRONG_DATA, HTTP_400_BAD_REQUEST)
else:
ret['code'] = HTTP_202_ACCEPTED
ret['msg'] = Msg.LOGIN_FAILED
return JsonResponse(ret, status=HTTP_202_ACCEPTED)
else:
ret['code'] = HTTP_400_BAD_REQUEST
ret['msg'] = Msg.INVALID_DATA
return JsonResponse(ret, status=HTTP_400_BAD_REQUEST)
except Exception as e:
print(e)
ret['code'] = HTTP_404_NOT_FOUND
ret['msg'] = Msg.REQUEST_EXCEPTION
return JsonResponse(ret)
class UserForgetPasswordView(APIView):
@swagger_auto_schema(
operation_description="apiview post description override",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['email', "new_password", "code"],
properties={
'email': openapi.Schema(type=openapi.TYPE_STRING),
'new_password': openapi.Schema(type=openapi.TYPE_STRING),
'code': openapi.Schema(type=openapi.TYPE_STRING)
},
),
security=[]
)
def post(self, request, *args, **kwargs):
ret = {}
try:
serializer = UserForgetPasswordSerializer(data=request.data)
print("request.data:", request.data)
if serializer.is_valid():
email = serializer.validated_data['email']
new_password = serializer.validated_data['new_password']
code = serializer.validated_data['code']
user_code = conn.get(f"ChangePassword_{email}")
if code == user_code:
obj = IHRUser.objects.filter(email=email).first()
if obj:
obj.set_password(new_password)
obj.save()
ret['code'] = HTTP_200_OK
ret['msg'] = Msg.CHANGE_PASSWORD_SUCCEEDED
return JsonResponse(ret, status=HTTP_200_OK)
else:
ret['code'] = HTTP_202_ACCEPTED
ret['msg'] = Msg.USER_NOT_EXIST
return JsonResponse(ret, status=HTTP_202_ACCEPTED)
else:
ret['code'] = HTTP_202_ACCEPTED
ret['msg'] = Msg.CODE_ERROR
return JsonResponse(ret, status=HTTP_202_ACCEPTED)
else:
ret['code'] = HTTP_400_BAD_REQUEST
ret['msg'] = Msg.INVALID_DATA
return JsonResponse(ret, status=HTTP_400_BAD_REQUEST)
except Exception as e:
print(e)
ret['code'] = HTTP_404_NOT_FOUND
ret['msg'] = Msg.REQUEST_EXCEPTION
return JsonResponse(ret)
class UserRegisterView(APIView):
queryset = IHRUser.objects.all()
serializer_class = UserRegisterSerializer
@swagger_auto_schema(
operation_description="apiview post description override",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['email', "password", "code"],
properties={
'email': openapi.Schema(type=openapi.TYPE_STRING),
'password': openapi.Schema(type=openapi.TYPE_STRING),
'code': openapi.Schema(type=openapi.TYPE_STRING)
},
),
security=[]
)
def post(self, request, *args, **kwargs):
ret = {}
try:
serializer = UserRegisterSerializer(data=request.data)
print("request.data:", serializer.initial_data)
if serializer.is_valid():
email = serializer.validated_data['email']
password = serializer.validated_data['password']
code = serializer.validated_data['code']
print("code:", code)
user_code = conn.get(f"Confirmation_{email}")
if code == user_code:
obj = IHRUser.objects.filter(email=email).first()
if obj:
ret['code'] = HTTP_200_OK
ret['msg'] = Msg.USER_ALREADY_REGISTERED
return JsonResponse(ret, status=HTTP_200_OK)
else:
obj = IHRUser.objects.create_user(email=email, password=password)
ret['code'] = HTTP_201_CREATED
ret['msg'] = Msg.REGISTER_SUCCEEDED
return JsonResponse(ret, status=HTTP_201_CREATED)
else:
ret['code'] = HTTP_400_BAD_REQUEST
ret['msg'] = Msg.CODE_ERROR
return JsonResponse(ret, status=HTTP_400_BAD_REQUEST)
ret['code'] = HTTP_202_ACCEPTED
ret['msg'] = Msg.CODE_ERROR
return JsonResponse(ret, status=HTTP_202_ACCEPTED)
else:
ret['code'] = HTTP_400_BAD_REQUEST
ret['msg'] = Msg.INVALID_DATA
return JsonResponse(ret, status=HTTP_400_BAD_REQUEST)
except Exception as e:
print(e)
ret['code'] = HTTP_404_NOT_FOUND
ret['msg'] = Msg.REQUEST_EXCEPTION
return JsonResponse(ret, status=HTTP_404_NOT_FOUND)
class UserSendEmailView(APIView):
@swagger_auto_schema(
operation_description="apiview post description override",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['email'],
properties={
'email': openapi.Schema(type=openapi.TYPE_STRING)
},
),
security=[]
)
def post(self, request, *args, **kwargs):
ret = {}
try:
serializer = UserEmailSerializer(data=request.data)
print("request.data:", request.data)
if serializer.is_valid():
email = serializer.validated_data['email']
confirmation_email = ConfirmationEmail(email)
print(confirmation_email.PLAIN)
send_mail(
'Account activation',
confirmation_email.PLAIN,
conf_settings.EMAIL_HOST_USER, #TO DO
[email],
fail_silently=False,
)
else:
# mohhamedfathyy@gmail.com
ret['code'] = HTTP_400_BAD_REQUEST
ret['msg'] = Msg.INVALID_DATA
return JsonResponse(ret, status=HTTP_400_BAD_REQUEST)
except IntegrityError as e:
return std_response(StrErrors.DUPLICATED, HTTP_409_CONFLICT)
except (ValueError, SMTPException, HeaderParseError, KeyError) as e:
print(e)
return std_response(StrErrors.WRONG_DATA, HTTP_400_BAD_REQUEST)
ret['code'] = HTTP_200_OK
ret['msg'] = Msg.CODE_SENT
return JsonResponse(ret, status=HTTP_200_OK)
class UserSendForgetPasswordEmailView(APIView):
@swagger_auto_schema(
operation_description="apiview post description override",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['email'],
properties={
'email': openapi.Schema(type=openapi.TYPE_STRING)
},
),
security=[]
)
def post(self, request, *args, **kwargs):
ret = {}
try:
serializer = UserEmailSerializer(data=request.data)
if serializer.is_valid():
email = serializer.validated_data['email']
confirmation_email = ChangePasswordEmail(email)
send_mail(
'Account activation',
confirmation_email.PLAIN,
'1347143378@qq.com',
[email],
fail_silently=False,
)
else:
ret['code'] = HTTP_400_BAD_REQUEST
ret['msg'] = Msg.INVALID_DATA
return JsonResponse(ret, status=HTTP_400_BAD_REQUEST)
except IntegrityError as e:
return std_response(StrErrors.DUPLICATED, HTTP_409_CONFLICT)
except (ValueError, SMTPException, HeaderParseError, KeyError) as e:
print(e)
return std_response(StrErrors.WRONG_DATA, HTTP_400_BAD_REQUEST)
ret['code'] = HTTP_200_OK
ret['msg'] = Msg.CODE_SENT
return JsonResponse(ret, status=HTTP_200_OK)
# class UserSearchChannelView(APIView):
# @swagger_auto_schema(
# operation_description="apiview post description override",
# request_body=openapi.Schema(
# type=openapi.TYPE_OBJECT,
# required=['type', "content"],
# properties={
# 'type': openapi.Schema(type=openapi.TYPE_STRING),
# 'content': openapi.Schema(type=openapi.TYPE_STRING)
# },
# ),
# security=[]
# )
# def post(self, request, *args, **kwargs):
# ret = {}
# try:
# print("request.data:", request.data)
# type = request.data.get('type')
# content = request.data.get('content')
# # Country, ASN, Atlas_location
# if type == "country":
# if content == '':
# obj_group = ["Japan", "France", "United States", "Brazil", "Germany", "China", "Singapore", "Canada", "Netherlands", "United Kingdom", "Russia", "Australia"]
# ret['code'] = HTTP_200_OK
# ret['msg'] = Msg.SEARCH_SUCCEEDED
# ret['data'] = obj_group
# return JsonResponse(ret)
# else:
# obj = Country.objects.filter(name__icontains=content)[:30]
# elif type == "network":
# if content == '':
# obj_group = ["AS3356 - Lumen", "AS2914 - NTT","AS6939 - HE","AS1299 - Telia","AS174 - Cogent","AS15169 - Google","AS20940 - Akamai","AS16509 - Amazon","AS13335 - Cloudflare","AS32934 - Facebook","AS7922 - Comcast","AS8075 - Microsoft"]
# ret['code'] = HTTP_200_OK
# ret['msg'] = Msg.SEARCH_SUCCEEDED
# ret['data'] = obj_group
# return JsonResponse(ret)
# else:
# obj = ASN.objects.filter(name__icontains=content)[:30]
# elif type == "city":
# if content == '':
# obj_group = ["Amsterdam North Holland NL", "Ashburn Virginia US","London England GB","Singapore Central Singapore, SG","Hong Kong Central and Western HK","Frankfurt am Main Hesse DE","Paris Île-de-France FR","Los Angeles California US","Tokyo Tokyo JP","Sydney New South Wales AU","New York City New York US","Toronto Ontario CA"]
# ret['msg'] = Msg.SEARCH_SUCCEEDED
# ret['data'] = obj_group
# return JsonResponse(ret)
# else:
# obj = Atlas_location.objects.filter(name__icontains=content, type = "CT")[:30]
# obj_group = []
# for temp in obj:
# if type == "city":
# obj_group.append(str(temp).replace(",", "")[5:].strip())
# else:
# obj_group.append(str(temp))
# print(obj_group)
# ret['code'] = HTTP_200_OK
# ret['msg'] = Msg.SEARCH_SUCCEEDED
# ret['data'] = obj_group
# return JsonResponse(ret)
# except Exception as e:
# print(e)
# ret['code'] = HTTP_404_NOT_FOUND
# ret['msg'] = Msg.REQUEST_EXCEPTION
# return JsonResponse(ret)
# class UserSearchChannelPrefixView(APIView):
# @swagger_auto_schema(
# operation_description="apiview post description override",
# request_body=openapi.Schema(
# type=openapi.TYPE_OBJECT,
# required=['type', "content"],
# properties={
# 'type': openapi.Schema(type=openapi.TYPE_STRING),
# 'content': openapi.Schema(type=openapi.TYPE_STRING)
# },
# ),
# security=[]
# )
# def post(self, request, *args, **kwargs):
# ret = {}
# try:
# print("request.data:", request.data)
# type = request.data.get('type')
# content = request.data.get('content')
# # Country, ASN, Atlas_location
# if type == "country":
# obj = Country.objects.filter(name__icontains=content)[:5]
# elif type == "network":
# obj = ASN.objects.filter(name__icontains=content)[:5]
# elif type == "city":
# obj = Atlas_location.objects.filter(name__icontains=content, type = "CT")[:5]
# obj_group = []
# for temp in obj:
# if type == "city":
# for str_temo in str(temp).replace(",", "")[5:].strip().split(" "):
# if content in str_temo:
# obj_group.append(str_temo)
# else:
# for str_temo in str(temp).replace(",", "").strip().split(" "):
# if content in str_temo:
# obj_group.append(str_temo)
# print(list(set(obj_group)))
# print(list(set(obj_group))[:5])
# ret['code'] = HTTP_200_OK