-
Notifications
You must be signed in to change notification settings - Fork 39
/
views.py
1620 lines (1314 loc) · 54.8 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
# stdlib imports
from functools import reduce
from pprint import pprint
import collections
import datetime
import json
import operator
import time
import urllib.parse
# django imports
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import UserPassesTestMixin
from django.db import transaction
from django.db.models import Q, Count, Max, Min
from django.forms import HiddenInput
from django.http import HttpResponse
from django.http import HttpResponseForbidden
from django.http import JsonResponse
from django.http.response import Http404
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.shortcuts import render
from django.urls import reverse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.text import slugify
from django.utils.text import smart_split
from django.views import View
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
# third-party imports
from django_countries import countries
from haystack.inputs import AutoQuery
from haystack.query import SearchQuerySet
from lxml import etree
import jwt
# project imports
from dbdb.core.forms import CreateUserForm, SystemForm, SystemVersionForm, SystemVersionMetadataForm, SystemFeaturesForm, \
SystemVersionEditForm
from dbdb.core.models import CitationUrl
from dbdb.core.models import Feature
from dbdb.core.models import FeatureOption
from dbdb.core.models import License
from dbdb.core.models import OperatingSystem
from dbdb.core.models import ProgrammingLanguage
from dbdb.core.models import ProjectType
from dbdb.core.models import System
from dbdb.core.models import SystemFeature
from dbdb.core.models import SystemRedirect
from dbdb.core.models import SystemVersion
from dbdb.core.models import SystemVersionMetadata
from dbdb.core.models import SystemACL
from dbdb.core.models import SystemVisit
from dbdb.core.models import SystemRecommendation
UserModel = get_user_model()
# constants
FILTERGROUP_VISIBLE_LENGTH = 3
SITEMPA_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9'
SITEMAP_PREFIX = '{%s}' % SITEMPA_NS
SITEMAP_NSMAP = { None : SITEMPA_NS }
# helper classes
FieldSet = collections.namedtuple('FieldSet', ['id','label','choices','description','citation'])
LetterPage = collections.namedtuple('LetterPage', ['id','letter','is_active','is_disabled'])
Stat = collections.namedtuple('Stat', ['label','items', 'search_field', 'systems', 'count'])
StatItem = collections.namedtuple('StatItem', ['label','value','slug'])
class FilterChoice( collections.namedtuple('FilterChoice', ['id','label','checked']) ):
is_hidden = False
@property
def sort_key(self):
return (
0 if self.checked else 1,
self.label,
)
pass
class FilterGroup( collections.namedtuple('FieldSet', ['id','label','choices']) ):
has_checked = False
has_more = False
def prepare(self):
#self.choices.sort(key=lambda fc: fc.sort_key)
for i,choice in enumerate(self.choices):
self.has_checked = self.has_checked or choice.checked
if i >= FILTERGROUP_VISIBLE_LENGTH and not choice.checked:
choice.is_hidden = True
self.has_more = True
pass
pass
return
pass
class SearchTag:
__slots__ = ['query','group_slug','group_name', 'tag_slug', 'tag_name']
def __init__(self, query, group_slug, group_name, tag_slug, tag_name):
self.query = query
self.group_slug = group_slug
self.group_name = group_name
self.tag_slug = tag_slug
self.tag_name = tag_name
return
def __repr__(self):
return repr( tuple( map(str, (self.group_slug, self.group_name, self.tag_slug, self.tag_name)) ) )
def get_removal_url(self):
query = []
for key,values in self.query.lists():
for value in values:
if key == self.group_slug and value == self.tag_slug:
continue
query.append((key, value))
return '?' + urllib.parse.urlencode(query, doseq=False)
pass
# helper functions
def staff_check(user):
return user.is_staff
def super_user_check(user):
return user.is_superuser
# class based views
# ==============================================
# EmptyFieldsView
# ==============================================
class EmptyFieldsView(View):
template_name = 'core/empty-fields.html'
def build_search_fields(include_citations=False):
import django.db.models.fields
IGNORE_TYPES = set([
django.db.models.fields.AutoField,
django.db.models.fields.related.ForeignKey,
#django.db.models.fields.related.ManyToManyField,
])
IGNORE_NAMES = set([
"ver",
"comment",
"features",
"created",
])
version_fields = [ ]
for f in SystemVersion._meta.get_fields():
if f.name.endswith("_citations") and not include_citations:
continue
if not type(f) in IGNORE_TYPES and \
not f.name in IGNORE_NAMES:
version_fields.append(f.name)
## FOR
meta_fields = [ ]
for f in SystemVersionMetadata._meta.get_fields():
if not type(f) in IGNORE_TYPES and \
not f.name in IGNORE_NAMES:
meta_fields.append(f.name)
return (version_fields, meta_fields)
## DEF
def get(self, request):
import django.db.models.fields
if not request.user.is_authenticated:
return redirect( settings.LOGIN_URL + '?next=' + reverse('fields') )
elif not request.user.is_superuser:
raise Http404()
version_fields, meta_fields = EmptyFieldsView.build_search_fields()
versions = SystemVersion.objects.filter(is_current=True)
search_field = request.GET.get('field')
search_reverse = request.GET.get('reverse', False)
if search_field:
query = None
field = None
if search_field in version_fields:
field = SystemVersion._meta.get_field(search_field)
field_name = search_field
if type(field) == django.db.models.fields.PositiveIntegerField:
query = Q(**{search_field: None})
else:
query = Q(**{search_field: ''})
elif search_field in meta_fields:
field = SystemVersionMetadata._meta.get_field(search_field)
field_name = "meta__" + search_field
if type(field) in (django.db.models.fields.PositiveIntegerField, django.db.models.fields.related.ManyToManyField):
query = Q(**{field_name: None})
else:
query = Q(**{field_name: ''})
else:
raise Exception("Invalid field '%s'" % search_field)
if search_reverse:
versions = versions.filter(~query)
else:
versions = versions.filter(query)
# convert query list to regular list
# and add href/url to each
versions = list( versions.order_by('system__name') )
for version in versions:
version.href = request.build_absolute_uri( version.system.get_absolute_url() )
if search_field in meta_fields:
if type(field) == django.db.models.fields.related.ManyToManyField:
method_handle = getattr(version.meta, search_field + "_str")
version.value = method_handle()
else:
version.value = getattr(version.meta, search_field, "XXX")
else:
version.value = getattr(version, field_name, None)
pass
## IF
num_systems = System.objects.all().count()
fields = sorted(version_fields + meta_fields)
return render(request, self.template_name, {
'activate': 'empty', # NAV-LINKS
'versions': versions,
'field': search_field,
'reverse': search_reverse,
'fields': fields,
'match_percent': "%.1f" % (100 * (len(versions) / num_systems)),
'num_systems': num_systems,
})
pass
## CLASS
# ==============================================
# DatabaseBrowseView
# ==============================================
class DatabaseBrowseView(View):
template_name = 'core/database-browse.html'
def build_filter_group_for_field(self, field, search_field, label, all_systems, querydict):
empty_set = set()
values = SystemVersionMetadata.objects \
.filter(systemversion__is_current=True) \
.filter(~Q(**{field: None})) \
.values_list(field)
#.distinct() \
#.order_by()
fg = FilterGroup(search_field, label, sorted([
FilterChoice(
all_systems[v[0]].slug,
all_systems[v[0]].name,
all_systems[v[0]].slug in querydict.getlist(search_field, empty_set)
)
for v in set(values)
#for sys in System.objects.values_list('id','slug','name', named=True)
], key=lambda x: x[1]))
return fg
def build_filter_groups(self, querydict):
empty_set = set()
def reduce_feature_options(mapping, option):
mapping[option.feature_id].choices.append(
FilterChoice(
option.slug,
option.value,
option.slug in querydict.getlist( option.feature__slug, empty_set )
)
)
return mapping
other_filtersgroups = []
# Countries
def reduce_countries(mapping, item):
countries = item.countries.split(',')
for c in countries:
if c: mapping[c] = mapping.get(c, 0) + 1
return mapping
system_countries = SystemVersion.objects \
.filter(is_current=True) \
.values_list('countries', named=True)
system_countries = reduce(reduce_countries, system_countries, {})
countries_map = dict(countries)
fg_country = FilterGroup('country', 'Country', sorted([
FilterChoice(
code,
countries_map[code], # name,
code in querydict.getlist( 'country', empty_set )
)
for code in system_countries.keys()
], key=lambda x: x[1]))
other_filtersgroups.append(fg_country)
all_systems = dict([
(sys.id, sys)
for sys in System.objects.values_list('id','slug','name', named=True)
])
# Compatible
other_filtersgroups.append(self.build_filter_group_for_field(\
'compatible_with', \
'compatible', \
'Compatible With', \
all_systems, \
querydict
))
# Embedded
other_filtersgroups.append(self.build_filter_group_for_field(\
'embedded', \
'embeds', \
'Embeds / Uses', \
all_systems, \
querydict
))
# Derived
other_filtersgroups.append(self.build_filter_group_for_field(\
'derived_from', \
'derived', \
'Derived From', \
all_systems, \
querydict
))
# Inspired
other_filtersgroups.append(self.build_filter_group_for_field(\
'inspired_by', \
'inspired', \
'Inspired By', \
all_systems, \
querydict
))
# add operating system
fg_os = FilterGroup('os', 'Operating System', [
FilterChoice(
os.slug,
os.name,
os.slug in querydict.getlist( 'os', empty_set )
)
for os in OperatingSystem.objects.values_list('id','slug','name', named=True)
])
other_filtersgroups.append(fg_os)
# add programming languages
fg_programming = FilterGroup('programming', 'Programming Languages', [
FilterChoice(
p.slug,
p.name,
p.slug in querydict.getlist( 'programming', empty_set )
)
for p in ProgrammingLanguage.objects.values_list('id','slug','name', named=True)
])
other_filtersgroups.append(fg_programming)
# add project types
fg_project_type = FilterGroup('type', 'Project Types', [
FilterChoice(
pt.slug,
pt.name,
pt.slug in querydict.getlist( 'type', empty_set )
)
for pt in ProjectType.objects.values_list('id','slug','name', named=True)
])
other_filtersgroups.append(fg_project_type)
# add licenses
fg_license = FilterGroup('license', 'Licenses', [
FilterChoice(
l.slug,
l.name,
l.slug in querydict.getlist( 'license', empty_set )
)
for l in License.objects.values_list('id','slug','name', named=True)
])
other_filtersgroups.append(fg_license)
# build from list of features (alphabetical order)
filtergroups = collections.OrderedDict(
(
f_id,
FilterGroup(f_slug, f_label, []),
)
for f_id,f_slug,f_label in Feature.objects.all().order_by('label').values_list('id','slug','label')
)
# add feature options to features
filtergroups = reduce(
reduce_feature_options,
FeatureOption.objects.all().order_by('value').values_list('feature_id','feature__slug','id','slug','value', named=True),
filtergroups
)
filtergroups = other_filtersgroups + list( filtergroups.values() )
for fg in filtergroups:
fg.prepare()
pass
return filtergroups
def build_pagination(self, letter):
letters_alphabet = set(
chr(i)
for i in range( ord('A') , ord('Z')+1 )
)
letters_available = set(
name.upper()[0]
for name in System.objects.all().values_list('name', flat=True)
)
letters_missing = letters_alphabet.difference( letters_available )
letters_all = letters_alphabet.union( letters_available )
pagination = list(
LetterPage(
l,
l,
l == letter,
l not in letters_available
)
for l in sorted(letters_all)
)
pagination.append(
LetterPage(
'ALL',
'All',
'ALL' == letter,
False
)
)
return pagination
def slug_to_system(self, slugs):
slugs = { s.strip() for s in slugs }
systems = System.objects.filter(slug__in=slugs)
return { s.slug : s for s in systems }
## DEF
def do_search(self, request):
has_search = False
countries_map = dict(countries)
# map feature slugs to ids
features_map = {
f_slug : f_id
for f_id,f_slug in Feature.objects.all().order_by().values_list('id','slug')
}
# map feature options slugs to ids
featuresoptions_map = {
(f_id,fo_slug) : fo_id
for f_id,fo_id,fo_slug in FeatureOption.objects.all().order_by().values_list('feature_id','id','slug')
}
# pull search criteria
search_q = request.GET.get('q', '').strip()
search_fg = {
features_map[k] : set( request.GET.getlist(k) )
for k in request.GET.keys()
if k in features_map
}
# define date filters
search_start_min = request.GET.get('start-min', '').strip()
search_start_max = request.GET.get('start-max', '').strip()
search_end_min = request.GET.get('end-min', '').strip()
search_end_max = request.GET.get('end-max', '').strip()
# define static filters
search_compatible = request.GET.getlist('compatible')
search_country = request.GET.getlist('country')
search_derived = request.GET.getlist('derived')
search_embeds = request.GET.getlist('embeds')
search_inspired = request.GET.getlist('inspired')
search_os = request.GET.getlist('os')
search_programming = request.GET.getlist('programming')
search_type = request.GET.getlist('type')
search_license = request.GET.getlist('license')
# collect filters
search_mapping = {
'query': search_q,
'start_min': search_start_min,
'start_max': search_start_max,
'end_min': search_end_min,
'end_max': search_end_max,
'compatible': search_compatible,
'country': search_country,
'derived': search_derived,
'embeds': search_embeds,
'inspired': search_inspired,
'os': search_os,
'programming': search_programming,
'type': search_type,
'license': search_license,
}
if not any(search_mapping.values()) and not any(search_fg):
return (None, { }, [])
search_tags = []
# create new search query
sqs = SearchQuerySet()
# apply keyword search to name (require all terms)
if search_q:
sqs = sqs.filter(content=AutoQuery(search_q))
# apply year limits
if all((search_start_min, search_start_max)):
search_start_min = int(search_start_min)
search_start_max = int(search_start_max)
sqs = sqs.filter(start_year__gte=search_start_min, start_year__lte=search_start_max)
pass
if all((search_end_min, search_end_max)):
search_end_min = int(search_end_min)
search_end_max = int(search_end_max)
sqs = sqs.filter(end_year__gte=search_end_min, end_year__lte=search_end_max)
pass
# search - compatible
if search_compatible:
sqs = sqs.filter(compatible_with__in=search_compatible)
systems = self.slug_to_system(search_compatible)
search_mapping['compatible'] = systems.values()
search_tags.extend( SearchTag(request.GET, 'compatible', 'Compatible With', k, v) for k,v in systems.items() )
pass
# search - country
if search_country:
sqs = sqs.filter(countries__in=search_country)
search_tags.extend( SearchTag(request.GET, 'country', 'Country', c, countries_map[c]) for c in search_country )
pass
# search - derived from
if search_derived:
sqs = sqs.filter(derived_from__in=search_derived)
systems = self.slug_to_system(search_derived)
search_mapping['derived'] = systems.values()
search_tags.extend( SearchTag(request.GET, 'derived', 'Derived From', k, v) for k,v in systems.items() )
pass
# search - embedded
if search_embeds:
sqs = sqs.filter(embedded__in=search_embeds)
systems = self.slug_to_system(search_embeds)
search_mapping['embeds'] = systems.values()
search_tags.extend( SearchTag(request.GET, 'embeds', 'Embeds / Uses', k, v) for k,v in systems.items() )
pass
# search - inspired by
if search_inspired:
sqs = sqs.filter(inspired_by__in=search_inspired)
systems = self.slug_to_system(search_inspired)
search_mapping['inspired'] = systems.values()
search_tags.extend( SearchTag(request.GET, 'inspired', 'Inspired By', k, v) for k,v in systems.items() )
pass
# search - operating systems
if search_os:
sqs = sqs.filter(oses__in=search_os)
oses = OperatingSystem.objects.filter(slug__in=search_os)
search_tags.extend( SearchTag(request.GET, 'os', 'Operating System', os.slug, os.name) for os in oses )
pass
# search - programming languages
if search_programming:
sqs = sqs.filter(written_langs__in=search_programming)
langs = ProgrammingLanguage.objects.filter(slug__in=search_programming)
search_tags.extend( SearchTag(request.GET, 'programming', 'Programming Languages', lang.slug, lang.name) for lang in langs )
pass
# search - project types
if search_type:
sqs = sqs.filter(project_types__in=search_type)
types = ProjectType.objects.filter(slug__in=search_type)
search_tags.extend( SearchTag(request.GET, 'type', 'Project Types', type.slug, type.name) for type in types )
pass
# search - licenses
if search_license:
sqs = sqs.filter(licenses__in=search_license)
licenses = License.objects.filter(slug__in=search_license)
search_tags.extend( SearchTag(request.GET, 'license', 'Licenses', license.slug, license.name) for license in licenses )
pass
# convert feature option slugs to IDs to do search by filtering
filter_option_ids = set()
for feature_id,option_slugs in search_fg.items():
option_ids = set( map(lambda option_slug: featuresoptions_map[(feature_id,option_slug)], option_slugs) )
filter_option_ids.update(option_ids)
pass
# if there are filter options to search for, apply filter
if filter_option_ids:
for option_id in filter_option_ids:
sqs = sqs.filter(feature_options__contains=option_id)
search_tags.extend(
SearchTag(request.GET, *row)
for row in FeatureOption.objects.filter(id__in=filter_option_ids).values_list('feature__slug','feature__label','slug','value')
)
for st in search_tags:
print('-', st)
return (sqs, search_mapping, search_tags)
def handle_old_urls(self, request):
query = []
# get mapping of feature options
featuresoptions_map = {
str(fo_id): (f_slug, fo_slug)
for fo_id,fo_slug,f_slug in FeatureOption.objects.all().order_by().values_list('id','slug','feature__slug')
}
for k in request.GET.keys():
for v in request.GET.getlist(k):
if k.startswith('fg'):
query.append( featuresoptions_map[v] )
pass
elif v:
query.append((k,v))
pass
pass
pass
return redirect( request.path + '?' + urllib.parse.urlencode(query) )
def get(self, request):
# handle older filter group urls
if any( filter(lambda k: k.startswith('fg'), request.GET.keys()) ):
return self.handle_old_urls(request)
# Perform the search and get back the versions along with a
# mapping with the search keys
results, search_keys, search_tags = self.do_search(request)
search_q = request.GET.get('q', '').strip()
# Search Letter
search_letter = request.GET.get('letter', '').strip().upper()
if results is not None:
pass
elif search_letter == 'ALL' or not search_letter:
results = SearchQuerySet()
search_letter = 'ALL'
pass
elif search_letter:
results = SearchQuerySet().filter(letter__exact=search_letter.lower()).filter(name__startswith=search_letter)
pass
# generate letter pagination
pagination = self.build_pagination(search_letter)
# convert query list to regular list
results = list( results.order_by('name') )
# check if there are results
has_results = len(results) > 0
# get year ranges
years_start = SystemVersion.objects.filter(is_current=True).filter(start_year__gt=0).aggregate(
min_start_year=Min('start_year'),
max_start_year=Max('start_year')
)
years_end = SystemVersion.objects.filter(is_current=True).filter(end_year__gt=0).aggregate(
min_end_year=Min('end_year'),
max_end_year=Max('end_year')
)
years = {}
years.update(years_start)
years.update(years_end)
return render(request, self.template_name, {
'activate': 'browse', # NAV-LINKS
'filtergroups': self.build_filter_groups(request.GET),
'has_results': has_results,
'pagination': pagination,
'query': search_q,
'results': results,
'years': years,
'has_search': len(search_keys) != 0,
'search': search_keys,
'tags': search_tags,
})
pass
# ==============================================
# CounterView
# ==============================================
@method_decorator(csrf_exempt, name='dispatch')
class CounterView(View):
@staticmethod
def build_token(origin, **kwargs):
payload = dict(kwargs)
payload.update( {
#'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=15), # +15 seconds ## disabled expatriation to allow caching
'iss': 'counter:{}'.format(origin),
'nbf': datetime.datetime.utcnow(),
})
s = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
s = s.decode('utf-8')
return s
def post(self, request):
token = request.POST.get('token')
if not token:
return JsonResponse({ 'status':'missing token'}, status=400)
try:
payload = jwt.decode(
token.encode('utf-8'),
settings.SECRET_KEY,
algorithms=['HS256']
)
iss = payload.get('iss')
if iss == 'counter:system':
pk = payload['pk']
# Skip bots
user_agent = request.META.get('HTTP_USER_AGENT', '')
if user_agent.lower().find("bot") != -1:
return JsonResponse({ 'status':'bot' })
## Update the system's counter
system = None
with transaction.atomic():
system = System.objects.select_for_update().get(pk=pk)
system.view_count += 1
system.save()
#pass
# And add a SystemVisit entry
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
system_visit = SystemVisit(system=system, ip_address=ip, user_agent=user_agent[:127])
system_visit.save()
else:
return JsonResponse({ 'status':('unrecognized counter: %r' % iss)}, status=400)
pass
except jwt.ExpiredSignatureError:
return JsonResponse({ 'status':'expired counter'}, status=400)
return JsonResponse({ 'status':'ok' })
pass
# ==============================================
# CreateUserView
# ==============================================
class CreateUserView(View):
TOKEN_QUERY_NAME = 'token'
template_name = 'registration/create_user.html'
def decode_token(self, request):
token = request.GET.get(CreateUserView.TOKEN_QUERY_NAME)
if not token:
return None
try:
payload = jwt.decode(
token.encode('utf-8'),
settings.SECRET_KEY,
algorithms=['HS256'],
verify=True
)
pass
except jwt.exceptions.ExpiredSignatureError:
payload = False
except:
payload = None
return payload
def get(self, request, *args, **kwargs):
expired_token = False
initial = { }
reg_info = self.decode_token(request)
if reg_info == False:
expired_token = True
pass
elif reg_info and 'sub' in reg_info:
initial['email'] = reg_info['sub']
form = CreateUserForm(auto_id='%s', initial=initial)
return render(request, self.template_name, {
'title': 'User Registration',
'expired_token': expired_token,
'form': form,
'recaptcha_key': getattr(settings, 'NORECAPTCHA_SITE_KEY'),
})
def post(self, request, *args, **kwargs):
expired_token = False
initial = { }
# check for a registration info
reg_info = self.decode_token(request)
# if the registration expired `False` then return to login page
if reg_info == False:
return redirect(settings.LOGIN_URL + '?status=failed')
pass
# if the registration included a subject, use as email address
elif reg_info and 'sub' in reg_info:
initial['email'] = reg_info['sub']
pass
# create form class (it handles enforcing initial email)
form = CreateUserForm(request.POST, auto_id='%s', initial=initial)
if form.is_valid():
with transaction.atomic():
# create user with provided info
user = UserModel.objects.create_user(
username=form.cleaned_data['username'],
email=form.cleaned_data['email'],
password=form.cleaned_data['password']
)
# associate the user with various systems if specified in registration info
if reg_info and 'systems' in reg_info:
system_ids = list( map(int, reg_info['systems']) )
# NOTE: if registration contained no longer valid system IDs, this will error out
SystemACL.objects.bulk_create([
SystemACL(
system_id=system_id,
user_id=user.id
)
for system_id in system_ids
])
pass
pass
# end successfully with a redirect to login page
return redirect(settings.LOGIN_URL + '?status=success')
return render(request, self.template_name, {
'form': form,
'recaptcha_key': getattr(settings, 'NORECAPTCHA_SITE_KEY'),
})
pass
# ==============================================
# DatabasesEditView
# ==============================================
class DatabasesEditView(LoginRequiredMixin, View):
template_name = 'core/databases-edit.html'
def build_features(self, feature_form):
features = Feature.objects.all()
features = collections.OrderedDict(
(
f.id,
{
'id': 'feature_{}'.format(f.id),
'label': f.label,
'choices': None,
'description': None,
'citation': None,
}
)
for f in features
)
for bf in feature_form:
name = bf.name.split('_')[-1]
feature_id = bf.field.feature_id
features[feature_id][name] = bf
pass
return features
@never_cache
def get(self, request, slug=None):
# If there is no slug, then they are trying to create a new database.
# Only superusers are allowed to do that.
if slug is None:
if not request.user.is_superuser:
raise Http404()
# Create a new empty system for the form
system = System()
system_version = SystemVersion(system=system, is_current=True)
system_meta = SystemVersionMetadata()
system_features = SystemFeature.objects.none()
pass
# If there is a slug, then check to see whether they have permission
# to edit this mofo
else:
# You always have to be logged in to edit an entry
if not request.user.is_authenticated:
return redirect( settings.LOGIN_URL + '?next=' + reverse('system', args=[slug]))
system = System.objects.get(slug=slug)
# Make sure this user has permissions to edit this page
if not request.user.is_superuser:
try:
system_acl = SystemACL.objects.get(system=system, user=request.user)
except SystemACL.DoesNotExist:
base_url = reverse('system', args=[slug])
query_string = urllib.parse.urlencode({'noperms': 1})
url = '{}?{}'.format(base_url, query_string)
return redirect(url)
## IF
# Load in what we need
system_version = SystemVersion.objects.get(system=system, is_current=True)
system_meta = system_version.meta
system_features = system_version.features.all()
pass
system_form = SystemForm(instance=system)
# Don't allow non-superusers from editting the system name
# This only really hides it from the UI.
if request.user.is_superuser:
system_form.fields['orig_name'].widget = HiddenInput()
else:
system_form.fields['name'].widget = HiddenInput()
system_form.fields['orig_name'].initial = system.name
feature_form = SystemFeaturesForm(features=system_features)
features = self.build_features(feature_form)