-
-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathmodels.py
More file actions
1683 lines (1553 loc) · 56.9 KB
/
models.py
File metadata and controls
1683 lines (1553 loc) · 56.9 KB
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
import csv
import ipaddress
import logging
import os
import string
from datetime import timedelta
from io import StringIO
import django
import phonenumbers
import swapper
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.mail import send_mail
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models, transaction
from django.db.models import JSONField, ProtectedError, Q
from django.utils import timezone
from django.utils.crypto import get_random_string
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from model_utils.fields import AutoLastModifiedField
from openwisp_notifications.signals import notify
from phonenumber_field.modelfields import PhoneNumberField
from private_storage.fields import PrivateFileField
from openwisp_radius.registration import (
REGISTRATION_METHOD_CHOICES,
get_registration_choices,
)
from openwisp_radius.tasks import process_radius_batch
from openwisp_users.mixins import OrgMixin
from openwisp_utils.base import KeyField, TimeStampedEditableModel, UUIDModel
from openwisp_utils.fields import (
FallbackBooleanChoiceField,
FallbackCharChoiceField,
FallbackCharField,
FallbackPositiveIntegerField,
FallbackTextField,
)
from .. import exceptions
from .. import settings as app_settings
from ..settings import (
BATCH_DEFAULT_PASSWORD_LENGTH,
BATCH_MAIL_MESSAGE,
BATCH_MAIL_SENDER,
BATCH_MAIL_SUBJECT,
DEFAULT_PASSWORD_RESET_URL,
)
from ..utils import (
SmsMessage,
decode_byte_data,
find_available_username,
generate_sms_token,
get_sms_default_valid_until,
load_model,
prefix_generate_users,
validate_csvfile,
)
from .validators import ipv6_network_validator, password_reset_url_validator
logger = logging.getLogger(__name__)
User = get_user_model()
OPTIONAL_FIELD_CHOICES = (
("disabled", _("Disabled")),
("allowed", _("Allowed")),
("mandatory", _("Mandatory")),
)
RADOP_CHECK_TYPES = (
("=", "="),
(":=", ":="),
("==", "=="),
("+=", "+="),
("!=", "!="),
(">", ">"),
(">=", ">="),
("<", "<"),
("<=", "<="),
("=~", "=~"),
("!~", "!~"),
("=*", "=*"),
("!*", "!*"),
)
RAD_NAS_TYPES = app_settings.EXTRA_NAS_TYPES + (
("Async", "Async"),
("Sync", "Sync"),
("ISDN Sync", "ISDN Sync"),
("ISDN Async V.120", "ISDN Async V.120"),
("ISDN Async V.110", "ISDN Async V.110"),
("Virtual", "Virtual"),
("PIAFS", "PIAFS"),
("HDLC Clear", "HDLC Clear"),
("Channel", "Channel"),
("X.25", "X.25"),
("X.75", "X.75"),
("G.3 Fax", "G.3 Fax"),
("SDSL", "SDSL - Symmetric DSL"),
("ADSL-CAP", "ADSL-CAP"),
("ADSL-DMT", "ADSL-DMT"),
("IDSL", "IDSL"),
("Ethernet", "Ethernet"),
("xDSL", "xDSL"),
("Cable", "Cable"),
("Wireless - Other", "Wireless - Other"),
("IEEE 802.11", "Wireless - IEEE 802.11"),
("Token-Ring", "Token-Ring"),
("FDDI", "FDDI"),
("Wireless - CDMA2000", "Wireless - CDMA2000"),
("Wireless - UMTS", "Wireless - UMTS"),
("Wireless - 1X-EV", "Wireless - 1X-EV"),
("IAPP", "IAPP"),
("FTTP", "FTTP"),
("IEEE 802.16", "Wireless - IEEE 802.16"),
("IEEE 802.20", "Wireless - IEEE 802.20"),
("IEEE 802.22", "Wireless - IEEE 802.22"),
("PPPoA", "PPPoA - PPP over ATM"),
("PPPoEoA", "PPPoEoA - PPP over Ethernet over ATM"),
("PPPoEoE", "PPPoEoE - PPP over Ethernet over Ethernet"),
("PPPoEoVLAN", "PPPoEoVLAN - PPP over Ethernet over VLAN"),
("PPPoEoQinQ", "PPPoEoQinQ - PPP over Ethernet over IEEE 802.1QinQ"),
("xPON", "xPON - Passive Optical Network"),
("Wireless - XGP", "Wireless - XGP"),
("WiMAX", " WiMAX Pre-Release 8 IWK Function"),
("WIMAX-WIFI-IWK", "WIMAX-WIFI-IWK: WiMAX WIFI Interworking"),
("WIMAX-SFF", "WIMAX-SFF: Signaling Forwarding Function for LTE/3GPP2"),
("WIMAX-HA-LMA", "WIMAX-HA-LMA: WiMAX HA and or LMA function"),
("WIMAX-DHCP", "WIMAX-DHCP: WIMAX DCHP service"),
("WIMAX-LBS", "WIMAX-LBS: WiMAX location based service"),
("WIMAX-WVS", "WIMAX-WVS: WiMAX voice service"),
("Other", "Other"),
)
RADOP_REPLY_TYPES = (("=", "="), (":=", ":="), ("+=", "+="))
_STRATEGIES = (("prefix", _("Generate from prefix")), ("csv", _("Import from CSV")))
_NOT_BLANK_MESSAGE = _("This field cannot be blank.")
_GET_IP_LIST_HELP_TEXT = _(
"Comma separated list of IP addresses allowed to access freeradius API"
)
_GET_MOBILE_PREFIX_HELP_TEXT = _(
"Comma separated list of international mobile prefixes "
"allowed to register via the user registration API."
)
_GET_OPTIONAL_FIELDS_HELP_TEXT = _(
"Whether this field should be disabled, allowed or mandatory "
"in the user registration API."
)
_REGISTRATION_ENABLED_HELP_TEXT = _(
"Whether the registration API endpoint should be enabled or not"
)
_SAML_REGISTRATION_ENABLED_HELP_TEXT = _(
"Whether the registration using SAML should be enabled or not"
)
_MAC_ADDR_ROAMING_ENABLED_HELP_TEXT = _(
"Whether the MAC address roaming should be enabled or not."
)
_SOCIAL_REGISTRATION_ENABLED_HELP_TEXT = _(
"Whether the registration using social applications should be enabled or not"
)
_SMS_VERIFICATION_HELP_TEXT = _(
"Whether users who sign up should be required to verify their mobile "
"phone number via SMS"
)
_ORGANIZATION_HELP_TEXT = _("The user is not a member of this organization")
_IDENTITY_VERIFICATION_ENABLED_HELP_TEXT = _(
"Whether identity verification is required at the time of user registration"
)
_COA_ENABLED_HELP_TEXT = _("Whether RADIUS Change Of Authoization (CoA) is enabled")
_LOGIN_URL_HELP_TEXT = _("Enter the URL where users can log in to the wifi service")
_STATUS_URL_HELP_TEXT = _("Enter the URL where users can log out from the wifi service")
_PASSWORD_RESET_URL_HELP_TEXT = _("Enter the URL where users can reset their password")
OPTIONAL_SETTINGS = app_settings.OPTIONAL_REGISTRATION_FIELDS
class AutoUsernameMixin(object):
def clean(self):
"""
automatically sets username
"""
if (
self.username
and User.objects.filter(username=self.username).exists()
and not self.user
):
self.user = User.objects.get(username=self.username)
if self.user:
self.username = self.user.username
if hasattr(self, "organization") and not self.user.is_member(
self.organization
):
raise ValidationError({"organization": _ORGANIZATION_HELP_TEXT})
elif not self.username:
raise ValidationError(
{"username": _NOT_BLANK_MESSAGE, "user": _NOT_BLANK_MESSAGE}
)
return super().clean()
class AutoGroupnameMixin(object):
def _set_groupname(self):
if self.group:
self.groupname = self.group.name
def clean(self):
"""
automatically sets groupname
"""
if self.group and not self.group.pk:
return
super().clean()
self._set_groupname()
if not self.group and not self.groupname:
raise ValidationError(
{"groupname": _NOT_BLANK_MESSAGE, "group": _NOT_BLANK_MESSAGE}
)
def save(self, *args, **kwargs):
self._set_groupname()
return super().save(*args, **kwargs)
class AttributeValidationMixin(object):
def _get_validation_queryset_kwargs(self):
raise NotImplementedError
def _get_error_message(self):
raise NotImplementedError
@property
def _object_name(self):
return (
type(self).__name__.lower().replace("radius", "").replace("group", "group ")
)
def clean(self):
"""
checks if the check or reply attribute is unique
"""
model = type(self).__name__
if (
load_model(model)
.objects.filter(**self._get_validation_queryset_kwargs())
.exclude(pk=self.pk)
.exists()
):
raise ValidationError({"attribute": self._get_error_message()})
return super().clean()
class UserAttributeValidationMixin(AttributeValidationMixin):
def _get_validation_queryset_kwargs(self):
kwargs = dict(user=self.user, attribute=self.attribute)
org = getattr(self, "organization", None)
# only add `organization` key if it exists
if org:
kwargs["organization"] = org
return kwargs
def _get_error_message(self):
return _(
"Another %(object_name)s for the same user and with "
"the same attribute already exists."
) % {"object_name": self._object_name}
class GroupAttributeValidationMixin(AttributeValidationMixin):
def _get_validation_queryset_kwargs(self):
return dict(group=self.group, attribute=self.attribute)
def _get_error_message(self):
return _(
"Another %(object_name)s for the same group and with "
"the same attribute already exists."
) % {"object_name": self._object_name}
class AbstractRadiusCheck(
OrgMixin, AutoUsernameMixin, UserAttributeValidationMixin, TimeStampedEditableModel
):
username = models.CharField(
verbose_name=_("username"),
max_length=64,
db_index=True,
# blank values are forbidden with custom validation
# because this field can left blank if the user
# foreign key is filled (it will be auto-filled)
blank=True,
)
value = models.CharField(verbose_name=_("value"), max_length=253)
op = models.CharField(
verbose_name=_("operator"),
max_length=2,
choices=RADOP_CHECK_TYPES,
default=":=",
)
attribute = models.CharField(
verbose_name=_("attribute"),
max_length=64,
)
# the foreign key is not part of the standard freeradius schema
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True
)
class Meta:
db_table = "radcheck"
verbose_name = _("check")
verbose_name_plural = _("checks")
abstract = True
def __str__(self):
return self.username
class AbstractRadiusReply(
OrgMixin, AutoUsernameMixin, UserAttributeValidationMixin, TimeStampedEditableModel
):
username = models.CharField(
verbose_name=_("username"),
max_length=64,
db_index=True,
# blank values are forbidden with custom validation
# because this field can left blank if the user
# foreign key is filled (it will be auto-filled)
blank=True,
)
value = models.CharField(verbose_name=_("value"), max_length=253)
op = models.CharField(
verbose_name=_("operator"), max_length=2, choices=RADOP_REPLY_TYPES, default="="
)
attribute = models.CharField(verbose_name=_("attribute"), max_length=64)
# the foreign key is not part of the standard freeradius schema
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True
)
class Meta:
db_table = "radreply"
verbose_name = _("reply")
verbose_name_plural = _("replies")
abstract = True
def __str__(self):
return self.username
class AbstractRadiusAccounting(OrgMixin, models.Model):
session_id = models.CharField(
verbose_name=_("session ID"),
max_length=64,
db_column="acctsessionid",
db_index=True,
)
unique_id = models.CharField(
verbose_name=_("accounting unique ID"),
max_length=32,
db_column="acctuniqueid",
unique=True,
primary_key=True,
)
username = models.CharField(
verbose_name=_("username"), max_length=64, db_index=True, null=True, blank=True
)
groupname = models.CharField(
verbose_name=_("group name"), max_length=64, null=True, blank=True
)
realm = models.CharField(
verbose_name=_("realm"), max_length=64, null=True, blank=True
)
nas_ip_address = models.GenericIPAddressField(
verbose_name=_("NAS IP address"), db_column="nasipaddress", db_index=True
)
nas_port_id = models.CharField(
verbose_name=_("NAS port ID"),
max_length=15,
db_column="nasportid",
null=True,
blank=True,
)
nas_port_type = models.CharField(
verbose_name=_("NAS port type"),
max_length=32,
db_column="nasporttype",
null=True,
blank=True,
)
start_time = models.DateTimeField(
verbose_name=_("start time"),
db_column="acctstarttime",
db_index=True,
null=True,
blank=True,
)
update_time = models.DateTimeField(
verbose_name=_("update time"), db_column="acctupdatetime", null=True, blank=True
)
stop_time = models.DateTimeField(
verbose_name=_("stop time"),
db_column="acctstoptime",
db_index=True,
null=True,
blank=True,
)
interval = models.IntegerField(
verbose_name=_("interval"), db_column="acctinterval", null=True, blank=True
)
session_time = models.PositiveIntegerField(
verbose_name=_("session time"),
db_column="acctsessiontime",
null=True,
blank=True,
)
authentication = models.CharField(
verbose_name=_("authentication"),
max_length=32,
db_column="acctauthentic",
null=True,
blank=True,
)
connection_info_start = models.CharField(
verbose_name=_("connection info start"),
max_length=50,
db_column="connectinfo_start",
null=True,
blank=True,
)
connection_info_stop = models.CharField(
verbose_name=_("connection info stop"),
max_length=50,
db_column="connectinfo_stop",
null=True,
blank=True,
)
input_octets = models.BigIntegerField(
verbose_name=_("input octets"),
db_column="acctinputoctets",
null=True,
blank=True,
)
output_octets = models.BigIntegerField(
verbose_name=_("output octets"),
db_column="acctoutputoctets",
null=True,
blank=True,
)
called_station_id = models.CharField(
verbose_name=_("called station ID"),
max_length=253,
db_column="calledstationid",
db_index=True,
blank=True,
null=True,
)
calling_station_id = models.CharField(
verbose_name=_("calling station ID"),
max_length=253,
db_column="callingstationid",
db_index=True,
blank=True,
null=True,
)
terminate_cause = models.CharField(
verbose_name=_("termination cause"),
max_length=32,
db_column="acctterminatecause",
blank=True,
null=True,
)
service_type = models.CharField(
verbose_name=_("service type"),
max_length=32,
db_column="servicetype",
null=True,
blank=True,
)
framed_protocol = models.CharField(
verbose_name=_("framed protocol"),
max_length=32,
db_column="framedprotocol",
null=True,
blank=True,
)
framed_ip_address = models.GenericIPAddressField(
verbose_name=_("framed IP address"),
db_column="framedipaddress",
# the default MySQL freeradius schema defines
# this as NOT NULL but defaulting to empty string
# but that wouldn't work on PostgreSQL
null=True,
blank=True,
)
framed_ipv6_address = models.GenericIPAddressField(
verbose_name=_("framed IPv6 address"),
db_column="framedipv6address",
protocol="IPv6",
null=True,
blank=True,
)
framed_ipv6_prefix = models.CharField(
verbose_name=_("framed IPv6 prefix"),
max_length=44,
db_column="framedipv6prefix",
validators=[ipv6_network_validator],
null=True,
blank=True,
)
framed_interface_id = models.CharField(
verbose_name=_("framed interface ID"),
max_length=19,
db_column="framedinterfaceid",
null=True,
blank=True,
)
delegated_ipv6_prefix = models.CharField(
verbose_name=_("delegated IPv6 prefix"),
max_length=44,
db_column="delegatedipv6prefix",
validators=[ipv6_network_validator],
null=True,
blank=True,
)
def save(self, *args, **kwargs):
if not self.start_time:
self.start_time = now()
super(AbstractRadiusAccounting, self).save(*args, **kwargs)
class Meta:
db_table = "radacct"
verbose_name = _("accounting")
verbose_name_plural = _("accountings")
abstract = True
def __str__(self):
return self.unique_id
@classmethod
def close_stale_sessions(cls, days=None, hours=None):
if hours:
delta = timedelta(hours=hours)
elif days:
delta = timedelta(days=days)
else:
raise ValueError("Missing `days` or `hours`")
# determine limit date time
older_than = timezone.now() - delta
# If the "update_time" is recent, then the session is not closed
# even when the "start_time" is older than the specified time.
# The "start_time" of a session is only checked when the
# "update_time" is not set.
sessions = cls.objects.filter(
Q(stop_time__isnull=True)
& (
Q(update_time__lt=older_than)
| (Q(update_time=None) & Q(start_time__lt=older_than))
)
)
for session in sessions.iterator():
# calculate seconds in between two dates
session.session_time = (now() - session.start_time).total_seconds()
session.stop_time = now()
session.update_time = session.stop_time
session.terminate_cause = "Session-Timeout"
session.save()
@classmethod
def _close_stale_sessions_on_nas_boot(cls, called_station_id):
"""
Called during RADIUS Accounting-On.
"""
if not called_station_id:
return 0
stale_sessions = cls.objects.filter(
called_station_id=called_station_id,
stop_time__isnull=True,
)
closed_count = stale_sessions.update(
stop_time=now(), terminate_cause="NAS-Reboot"
)
return closed_count
class AbstractNas(OrgMixin, TimeStampedEditableModel):
name = models.CharField(
verbose_name=_("name"),
max_length=128,
help_text=_("NAS Name (or IP address)"),
db_index=True,
db_column="nasname",
)
short_name = models.CharField(
verbose_name=_("short name"), max_length=32, db_column="shortname"
)
type = models.CharField(
verbose_name=_("type"), max_length=30, default="other", choices=RAD_NAS_TYPES
)
ports = models.PositiveIntegerField(verbose_name=_("ports"), blank=True, null=True)
secret = models.CharField(
verbose_name=_("secret"), max_length=60, help_text=_("Shared Secret")
)
server = models.CharField(
verbose_name=_("server"), max_length=64, blank=True, null=True
)
community = models.CharField(
verbose_name=_("community"), max_length=50, blank=True, null=True
)
description = models.CharField(
verbose_name=_("description"), max_length=200, null=True, blank=True
)
class Meta:
db_table = "nas"
verbose_name = _("NAS")
verbose_name_plural = _("NAS")
abstract = True
def __str__(self):
return self.name
class AbstractRadiusGroup(OrgMixin, TimeStampedEditableModel):
"""
This is not part of the standard freeradius schema.
It's added to facilitate the management of groups.
"""
name = models.CharField(
verbose_name=_("group name"), max_length=255, unique=True, db_index=True
)
description = models.CharField(
verbose_name=_("description"), max_length=64, blank=True, null=True
)
_DEFAULT_HELP_TEXT = (
"The default group is automatically assigned to new users; "
"changing the default group has only effect on new users "
"(existing users will keep being members of their current group)"
)
default = models.BooleanField(
verbose_name=_("is default?"), help_text=_(_DEFAULT_HELP_TEXT), default=False
)
class Meta:
verbose_name = _("group")
verbose_name_plural = _("groups")
abstract = True
def __str__(self):
return self.name
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._initial_default = self.default
def clean(self):
self.check_default()
if not hasattr(self, "organization"):
return
if not self.name.startswith(f"{self.organization.slug}-"):
self.name = f"{self.organization.slug}-{self.name}"
def save(self, *args, **kwargs):
result = super().save(*args, **kwargs)
if self.default:
self.set_default()
# sync all related records
if not self._state.adding:
self.radiusgroupcheck_set.update(groupname=self.name)
self.radiusgroupreply_set.update(groupname=self.name)
self.radiususergroup_set.update(groupname=self.name)
return result
_DEFAULT_VALIDATION_ERROR = _(
"There must be at least one default group present in "
"the system. To change the default group, simply set "
"as default the group you want to make the new default."
)
_DEFAULT_PROTECTED_ERROR = _("The default group cannot be deleted")
def delete(self, *args, **kwargs):
if self.default:
raise ProtectedError(self._DEFAULT_PROTECTED_ERROR, self)
return super().delete(*args, **kwargs)
def set_default(self):
"""
ensures there's only 1 default group
(logic overridable via custom models)
"""
queryset = self.get_default_queryset()
if queryset.exists():
queryset.update(default=False)
def check_default(self):
"""
ensures the default group cannot be undefaulted
(logic overridable via custom models)
"""
if not self.default and self._initial_default:
raise ValidationError({"default": self._DEFAULT_VALIDATION_ERROR})
def get_default_queryset(self):
"""
looks for default groups excluding the current one
overridable by openwisp-radius and other 3rd party apps
"""
return self.__class__.objects.exclude(pk=self.pk).filter(
default=True, organization_id=self.organization.pk
)
class AbstractRadiusUserGroup(
AutoGroupnameMixin, AutoUsernameMixin, TimeStampedEditableModel
):
username = models.CharField(
verbose_name=_("username"),
max_length=64,
db_index=True,
# blank values are forbidden with custom validation
# because this field can left blank if the user
# foreign key is filled (it will be auto-filled)
blank=True,
)
groupname = models.CharField(
verbose_name=_("group name"),
max_length=64,
# blank values are forbidden with custom validation
# because this field can left blank if the group
# foreign key is filled (it will be auto-filled)
blank=True,
)
priority = models.IntegerField(verbose_name=_("priority"), default=1)
# the foreign keys are not part of the standard freeradius schema,
# these are added here to facilitate the synchronization of the
# records which are related in different tables
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True
)
group = models.ForeignKey(
"RadiusGroup", on_delete=models.CASCADE, blank=True, null=True
)
class Meta:
db_table = "radusergroup"
verbose_name = _("user group")
verbose_name_plural = _("user groups")
unique_together = ("user", "group")
abstract = True
def __str__(self):
return str(self.username)
class AbstractRadiusGroupCheck(
AutoGroupnameMixin, GroupAttributeValidationMixin, TimeStampedEditableModel
):
groupname = models.CharField(
verbose_name=_("group name"),
max_length=64,
db_index=True,
# blank values are forbidden with custom validation
# because this field can left blank if the group
# foreign key is filled (it will be auto-filled)
blank=True,
)
attribute = models.CharField(verbose_name=_("attribute"), max_length=64)
op = models.CharField(
verbose_name=_("operator"),
max_length=2,
choices=RADOP_CHECK_TYPES,
default=":=",
)
value = models.CharField(verbose_name=_("value"), max_length=253)
# the foreign key is not part of the standard freeradius schema
group = models.ForeignKey(
"RadiusGroup", on_delete=models.CASCADE, blank=True, null=True
)
class Meta:
db_table = "radgroupcheck"
verbose_name = _("group check")
verbose_name_plural = _("group checks")
abstract = True
def __str__(self):
return str(self.groupname)
class AbstractRadiusGroupReply(
AutoGroupnameMixin, GroupAttributeValidationMixin, TimeStampedEditableModel
):
groupname = models.CharField(
verbose_name=_("group name"),
max_length=64,
db_index=True,
# blank values are forbidden with custom validation
# because this field can left blank if the group
# foreign key is filled (it will be auto-filled)
blank=True,
)
attribute = models.CharField(verbose_name=_("attribute"), max_length=64)
op = models.CharField(
verbose_name=_("operator"), max_length=2, choices=RADOP_REPLY_TYPES, default="="
)
value = models.CharField(verbose_name=_("value"), max_length=253)
# the foreign key is not part of the standard freeradius schema
group = models.ForeignKey(
"RadiusGroup", on_delete=models.CASCADE, blank=True, null=True
)
class Meta:
db_table = "radgroupreply"
verbose_name = _("group reply")
verbose_name_plural = _("group replies")
abstract = True
def __str__(self):
return str(self.groupname)
class AbstractRadiusPostAuth(OrgMixin, UUIDModel):
username = models.CharField(verbose_name=_("username"), max_length=64)
password = models.CharField(
verbose_name=_("password"), max_length=64, db_column="pass", blank=True
)
reply = models.CharField(verbose_name=_("reply"), max_length=32)
called_station_id = models.CharField(
verbose_name=_("called station ID"),
max_length=253,
db_column="calledstationid",
blank=True,
null=True,
)
calling_station_id = models.CharField(
verbose_name=_("calling station ID"),
max_length=253,
db_column="callingstationid",
blank=True,
null=True,
)
date = models.DateTimeField(
verbose_name=_("date"), db_column="authdate", auto_now_add=True
)
class Meta:
db_table = "radpostauth"
verbose_name = _("post auth")
verbose_name_plural = _("post auth log")
abstract = True
def __str__(self):
return str(self.username)
def _get_csv_file_location(instance, filename):
return os.path.join(
str(instance.organization.slug),
"batch",
str(instance.organization.pk),
"csv",
filename,
)
class AbstractRadiusBatch(OrgMixin, TimeStampedEditableModel):
PENDING = "pending"
PROCESSING = "processing"
COMPLETED = "completed"
FAILED = "failed"
BATCH_STATUS_CHOICES = (
(PENDING, _("Pending")),
(PROCESSING, _("Processing")),
(COMPLETED, _("Completed")),
(FAILED, _("Failed")),
)
strategy = models.CharField(
_("strategy"),
max_length=16,
choices=_STRATEGIES,
db_index=True,
help_text=_("Import users from a CSV or generate using a prefix"),
)
status = models.CharField(
max_length=16,
choices=BATCH_STATUS_CHOICES,
default=PENDING,
db_index=True,
)
name = models.CharField(
verbose_name=_("name"),
max_length=128,
help_text=_("A unique batch name"),
db_index=True,
unique=False,
)
users = models.ManyToManyField(
settings.AUTH_USER_MODEL,
blank=True,
related_name="radius_batch",
help_text=_("List of users uploaded in this batch"),
)
csvfile = PrivateFileField(
null=True,
blank=True,
verbose_name="CSV",
storage=app_settings.PRIVATE_STORAGE_INSTANCE,
upload_to=_get_csv_file_location,
help_text=_("The csv file containing the user details to be uploaded"),
max_file_size=app_settings.MAX_CSV_FILE_SIZE,
)
prefix = models.CharField(
_("prefix"),
null=True,
blank=True,
max_length=20,
help_text=_("Usernames generated will be of the format [prefix][number]"),
)
# List of usernames and passwords used to create PDF
user_credentials = JSONField(
null=True,
blank=True,
verbose_name="PDF",
encoder=DjangoJSONEncoder,
)
expiration_date = models.DateField(
verbose_name=_("expiration date"),
null=True,
blank=True,
help_text=_("If left blank users will never expire"),
)
class Meta:
db_table = "radbatch"
unique_together = ("name", "organization")
verbose_name = _("batch user creation")
verbose_name_plural = _("batch user creation operations")
abstract = True
def __str__(self):
return self.name
def clean(self):
if self.strategy == "csv" and not self.csvfile:
raise ValidationError(
{"csvfile": _("This field cannot be blank.")}, code="invalid"
)
if self.strategy == "prefix" and not self.prefix:
raise ValidationError(
{"prefix": _("This field cannot be blank.")}, code="invalid"
)
if self.strategy == "prefix" and self.prefix:
valid_chars = string.ascii_letters + string.digits + "@.+-_"
for char in self.prefix:
if char not in valid_chars:
raise ValidationError(
{
"prefix": _(
"This value may contain only letters, numbers,"
" and `@/./`+/-/_ characters."
)
},
code="invalid",
)
if (
self.strategy == "csv"
and self.prefix
or self.strategy == "prefix"
and self.csvfile
):
# this case would happen only when using the internal API
raise ValidationError(
_("Mixing fields of different strategies"), code="invalid"
)
if self.strategy == "csv":
validate_csvfile(self.csvfile.file)
super().clean()
def add(self, reader, password_length=BATCH_DEFAULT_PASSWORD_LENGTH):
users_list = []
generated_passwords = []
with transaction.atomic():
for row in reader:
if len(row) == 5:
user, password = self.get_or_create_user(
row, users_list, password_length
)
users_list.append(user)
if password:
generated_passwords.append(password)
for user in users_list:
self.save_user(user)
for element in generated_passwords:
username, password, user_email = element