2018-07-26 17:59:58 +00:00
|
|
|
# IP address part of this of this copied from
|
|
|
|
# https://github.com/benliles/django-ipauth/blob/master/ipauth/models.py
|
2020-02-07 04:02:29 +00:00
|
|
|
import logging
|
2013-10-10 06:41:50 +00:00
|
|
|
import re
|
2020-02-18 02:14:39 +00:00
|
|
|
from functools import total_ordering
|
2020-02-07 04:02:29 +00:00
|
|
|
|
2018-07-26 17:59:58 +00:00
|
|
|
from django.contrib.auth.models import Group
|
2016-07-22 22:49:19 +00:00
|
|
|
from django.conf import settings
|
2013-10-08 19:37:22 +00:00
|
|
|
from django.core.exceptions import ValidationError
|
|
|
|
from django.core import validators
|
2013-10-02 16:02:08 +00:00
|
|
|
from django.db import models
|
2013-10-10 06:41:50 +00:00
|
|
|
from django.db.models.signals import post_save
|
2020-02-18 15:25:48 +00:00
|
|
|
from django.db.utils import OperationalError
|
2018-04-19 17:13:02 +00:00
|
|
|
from django.forms import GenericIPAddressField as BaseIPAddressField
|
2018-07-24 15:33:39 +00:00
|
|
|
from django.urls import reverse
|
2018-12-07 19:51:25 +00:00
|
|
|
from django.utils import timezone
|
2013-10-02 16:02:08 +00:00
|
|
|
|
2020-02-07 04:02:29 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2013-10-02 16:02:08 +00:00
|
|
|
class Library(models.Model):
|
|
|
|
'''
|
|
|
|
name and other things derive from the User
|
|
|
|
'''
|
2018-07-26 17:59:58 +00:00
|
|
|
user = models.OneToOneField(
|
|
|
|
settings.AUTH_USER_MODEL,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name='library',
|
|
|
|
)
|
|
|
|
group = models.OneToOneField(
|
|
|
|
Group,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name='library',
|
|
|
|
null=True
|
|
|
|
)
|
|
|
|
backend = models.CharField(max_length=10, choices=(
|
|
|
|
('ip', 'IP authentication'),
|
|
|
|
('cardnum', 'Library Card Number check'),
|
|
|
|
('email', 'e-mail pattern check'),
|
|
|
|
), default='ip')
|
|
|
|
name = models.CharField(max_length=80, default='')
|
2013-11-28 03:14:52 +00:00
|
|
|
approved = models.BooleanField(default=False)
|
2018-07-26 17:59:58 +00:00
|
|
|
owner = models.ForeignKey(
|
|
|
|
settings.AUTH_USER_MODEL,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name="libraries",
|
|
|
|
)
|
2013-10-10 19:56:40 +00:00
|
|
|
credential = None
|
2018-07-26 17:59:58 +00:00
|
|
|
|
2020-02-12 16:36:49 +00:00
|
|
|
def __str__(self):
|
|
|
|
return str(self.name)
|
2018-07-26 17:59:58 +00:00
|
|
|
|
2013-10-08 19:37:22 +00:00
|
|
|
def add_user(self, user):
|
|
|
|
user.groups.add(self.group)
|
2013-10-10 19:56:40 +00:00
|
|
|
(library_user, created) = LibraryUser.objects.get_or_create(library=self, user=user)
|
2018-07-26 17:59:58 +00:00
|
|
|
library_user.credential = self.credential
|
2013-10-10 19:56:40 +00:00
|
|
|
library_user.save()
|
2018-07-26 17:59:58 +00:00
|
|
|
|
2013-10-08 19:37:22 +00:00
|
|
|
def has_user(self, user):
|
2013-10-15 20:18:30 +00:00
|
|
|
return self.group in user.groups.all() or user == self.user
|
2018-07-26 17:59:58 +00:00
|
|
|
|
2013-10-08 19:37:22 +00:00
|
|
|
@property
|
|
|
|
def join_template(self):
|
2013-12-02 00:20:42 +00:00
|
|
|
if self.approved:
|
|
|
|
return 'libraryauth/' + self.backend + '_join.html'
|
2018-07-26 17:59:58 +00:00
|
|
|
return 'libraryauth/unapproved.html'
|
|
|
|
|
2013-12-02 05:46:25 +00:00
|
|
|
@property
|
|
|
|
def help_template(self):
|
|
|
|
return 'libraryauth/' + self.backend + '_help.html'
|
2018-07-26 17:59:58 +00:00
|
|
|
|
2013-11-28 03:14:52 +00:00
|
|
|
def get_absolute_url(self):
|
|
|
|
return reverse('library', args=[self.user.username])
|
2013-10-10 06:41:50 +00:00
|
|
|
|
|
|
|
def add_group(sender, created, instance, **kwargs):
|
|
|
|
if created:
|
2018-07-26 17:59:58 +00:00
|
|
|
num = ''
|
2013-10-10 06:41:50 +00:00
|
|
|
while created:
|
2018-07-26 17:59:58 +00:00
|
|
|
(group, created) = Group.objects.get_or_create(name=instance.user.username + num)
|
2013-10-10 06:41:50 +00:00
|
|
|
# make sure not using a group twice!
|
|
|
|
if created:
|
|
|
|
created = False
|
|
|
|
else:
|
|
|
|
num += '+'
|
|
|
|
try:
|
|
|
|
group.library
|
|
|
|
created = True
|
|
|
|
except Library.DoesNotExist:
|
|
|
|
pass
|
2018-07-26 17:59:58 +00:00
|
|
|
instance.group = group
|
2013-10-10 06:41:50 +00:00
|
|
|
instance.save()
|
|
|
|
|
|
|
|
post_save.connect(add_group, sender=Library)
|
2013-10-08 19:37:22 +00:00
|
|
|
|
2020-02-17 21:34:02 +00:00
|
|
|
def ip_to_int(value):
|
2013-10-08 19:37:22 +00:00
|
|
|
validators.validate_ipv4_address(value)
|
|
|
|
|
|
|
|
lower_validator = validators.MinValueValidator(0)
|
2020-02-18 02:14:39 +00:00
|
|
|
upper_validator = validators.MaxValueValidator(255)
|
2013-10-08 19:37:22 +00:00
|
|
|
|
2020-02-18 02:14:39 +00:00
|
|
|
value = [int(octet) for octet in value.split('.')]
|
2013-10-08 19:37:22 +00:00
|
|
|
output = 0
|
|
|
|
|
|
|
|
for i in range(0, 4):
|
|
|
|
validators.validate_integer(value[i])
|
|
|
|
lower_validator(value[i])
|
|
|
|
upper_validator(value[i])
|
2020-02-18 02:14:39 +00:00
|
|
|
output += value[i] * (256**(3-i))
|
2013-10-08 19:37:22 +00:00
|
|
|
|
|
|
|
return output
|
|
|
|
|
2020-02-17 21:34:02 +00:00
|
|
|
def int_to_ip(value):
|
2013-10-08 19:37:22 +00:00
|
|
|
validators.validate_integer(value)
|
2020-02-17 19:02:47 +00:00
|
|
|
value = int(value)
|
2013-10-08 19:37:22 +00:00
|
|
|
|
|
|
|
validators.MinValueValidator(0)(value)
|
|
|
|
validators.MaxValueValidator(4294967295)(value)
|
|
|
|
|
|
|
|
return '%d.%d.%d.%d' % (value >> 24, value >> 16 & 255,
|
|
|
|
value >> 8 & 255, value & 255)
|
|
|
|
|
2020-02-18 02:14:39 +00:00
|
|
|
@total_ordering
|
2013-10-08 19:37:22 +00:00
|
|
|
class IP(object):
|
|
|
|
def __init__(self, value):
|
|
|
|
self.int = value
|
|
|
|
|
|
|
|
def _set_int(self, value):
|
|
|
|
if isinstance(value, IP):
|
|
|
|
self._int = IP.int
|
|
|
|
|
|
|
|
try:
|
2020-02-17 21:34:02 +00:00
|
|
|
self._int = int(value)
|
2013-10-08 19:37:22 +00:00
|
|
|
except ValueError:
|
2020-02-17 21:34:02 +00:00
|
|
|
self._int = ip_to_int(value)
|
2013-10-08 19:37:22 +00:00
|
|
|
except (TypeError, ValidationError):
|
|
|
|
self._int = None
|
|
|
|
|
|
|
|
def _get_int(self):
|
|
|
|
return self._int
|
|
|
|
|
|
|
|
int = property(_get_int, _set_int)
|
|
|
|
|
|
|
|
def _get_str(self):
|
2018-07-26 17:59:58 +00:00
|
|
|
if self.int != None:
|
2020-02-17 21:34:02 +00:00
|
|
|
return int_to_ip(self.int)
|
2013-10-08 19:37:22 +00:00
|
|
|
return ''
|
|
|
|
|
|
|
|
string = property(_get_str, _set_int)
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
if not isinstance(other, IP):
|
|
|
|
try:
|
|
|
|
other = IP(other)
|
|
|
|
except:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return self.int == other.int
|
|
|
|
|
2020-02-18 02:14:39 +00:00
|
|
|
def __gt__(self, other):
|
2013-10-08 19:37:22 +00:00
|
|
|
if not isinstance(other, IP):
|
|
|
|
other = IP(other)
|
|
|
|
|
2016-11-09 20:24:11 +00:00
|
|
|
if self.int is not None and other.int is not None:
|
2020-02-18 02:14:39 +00:00
|
|
|
return self.int.__gt__(other.int)
|
2013-10-08 19:37:22 +00:00
|
|
|
|
|
|
|
raise ValueError('Invalid arguments')
|
|
|
|
|
2020-02-12 16:36:49 +00:00
|
|
|
def __str__(self):
|
2013-10-08 19:37:22 +00:00
|
|
|
return self.string
|
|
|
|
|
|
|
|
class IPAddressFormField(BaseIPAddressField):
|
|
|
|
default_validators = []
|
|
|
|
|
|
|
|
def prepare_value(self, value):
|
|
|
|
if isinstance(value, IP):
|
|
|
|
return value.string
|
|
|
|
|
|
|
|
try:
|
|
|
|
return IP(value).string
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2018-07-26 17:59:58 +00:00
|
|
|
if value == 0:
|
2013-10-08 19:37:22 +00:00
|
|
|
return IP(0)
|
|
|
|
if value in validators.EMPTY_VALUES:
|
|
|
|
return None
|
|
|
|
|
|
|
|
try:
|
|
|
|
return IP(value)
|
|
|
|
except ValidationError:
|
|
|
|
raise ValidationError(self.default_error_messages['invalid'],
|
|
|
|
code='invalid')
|
|
|
|
|
2016-11-09 20:24:11 +00:00
|
|
|
class IPAddressModelField(models.GenericIPAddressField):
|
2013-10-08 19:37:22 +00:00
|
|
|
empty_strings_allowed = False
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
models.Field.__init__(self, *args, **kwargs)
|
|
|
|
|
|
|
|
def get_internal_type(self):
|
|
|
|
return "PositiveIntegerField"
|
|
|
|
|
|
|
|
def get_prep_value(self, value):
|
|
|
|
if not value:
|
|
|
|
return value
|
|
|
|
|
|
|
|
if isinstance(value, IP):
|
|
|
|
return value.int
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
if isinstance(value, IP):
|
|
|
|
return value
|
|
|
|
try:
|
|
|
|
return IP(value)
|
|
|
|
except ValidationError:
|
|
|
|
return None
|
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
|
|
|
defaults = {'form_class': IPAddressFormField}
|
|
|
|
defaults.update(kwargs)
|
2016-11-09 20:24:11 +00:00
|
|
|
return super(models.GenericIPAddressField, self).formfield(**defaults)
|
2018-07-26 17:59:58 +00:00
|
|
|
|
2016-07-21 20:09:42 +00:00
|
|
|
def deconstruct(self):
|
2016-11-09 20:24:11 +00:00
|
|
|
name, path, args, kwargs = super(models.GenericIPAddressField, self).deconstruct()
|
2016-07-21 20:09:42 +00:00
|
|
|
return name, path, args, kwargs
|
2013-10-08 19:37:22 +00:00
|
|
|
|
2018-07-22 17:14:27 +00:00
|
|
|
|
2013-10-08 19:37:22 +00:00
|
|
|
class Block(models.Model):
|
2018-07-24 03:48:35 +00:00
|
|
|
library = models.ForeignKey(Library, on_delete=models.CASCADE, related_name='ip_auths')
|
2013-10-08 19:37:22 +00:00
|
|
|
lower = IPAddressModelField(db_index=True, unique=True)
|
|
|
|
upper = IPAddressModelField(db_index=True, blank=True, null=True)
|
|
|
|
|
|
|
|
def clean(self):
|
|
|
|
if self.upper and self.upper.int:
|
|
|
|
try:
|
|
|
|
if self.lower > self.upper:
|
|
|
|
raise ValidationError('Lower end of the Block must be less '
|
|
|
|
'than or equal to the upper end')
|
2020-02-12 22:56:04 +00:00
|
|
|
except ValueError as e:
|
2013-10-08 19:37:22 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
2020-02-12 16:36:49 +00:00
|
|
|
def __str__(self):
|
2013-10-08 19:37:22 +00:00
|
|
|
if self.upper and self.upper.int:
|
|
|
|
return u'%s %s-%s' % (self.library, self.lower, self.upper)
|
|
|
|
return u'%s %s' % (self.library, self.lower)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
ordering = ['lower',]
|
|
|
|
|
2013-10-10 06:41:50 +00:00
|
|
|
|
2017-07-27 14:33:13 +00:00
|
|
|
# from https://en.wikipedia.org/wiki/Luhn_algorithm#Implementation_of_standard_Mod_10
|
2013-10-10 06:41:50 +00:00
|
|
|
def luhn_checksum(card_number):
|
|
|
|
def digits_of(n):
|
|
|
|
return [int(d) for d in str(n)]
|
|
|
|
digits = digits_of(card_number)
|
|
|
|
odd_digits = digits[-1::-2]
|
|
|
|
even_digits = digits[-2::-2]
|
|
|
|
checksum = 0
|
|
|
|
checksum += sum(odd_digits)
|
|
|
|
for d in even_digits:
|
|
|
|
checksum += sum(digits_of(d*2))
|
|
|
|
return checksum % 10
|
2018-07-26 17:59:58 +00:00
|
|
|
|
2013-10-10 06:41:50 +00:00
|
|
|
class CardPattern(models.Model):
|
2018-07-24 03:48:35 +00:00
|
|
|
library = models.ForeignKey(Library, on_delete=models.CASCADE, related_name='cardnum_auths')
|
2013-10-10 06:41:50 +00:00
|
|
|
# match pattern ^\d+#+$
|
|
|
|
pattern = models.CharField(max_length=20)
|
|
|
|
checksum = models.BooleanField(default=True)
|
|
|
|
|
|
|
|
def is_valid(self, card_number):
|
2018-07-26 17:59:58 +00:00
|
|
|
match_pattern = '^' + self.pattern.replace('#', r'\d', 20) + '$'
|
|
|
|
if re.match(match_pattern, card_number) is None:
|
2013-10-10 06:41:50 +00:00
|
|
|
return False
|
|
|
|
if self.checksum:
|
|
|
|
return luhn_checksum(card_number) == 0
|
2018-07-26 17:59:58 +00:00
|
|
|
return True
|
2013-10-08 19:37:22 +00:00
|
|
|
|
2013-10-10 19:56:40 +00:00
|
|
|
class LibraryUser(models.Model):
|
2018-07-24 03:48:35 +00:00
|
|
|
library = models.ForeignKey(Library, on_delete=models.CASCADE, related_name='library_users')
|
2018-07-26 17:59:58 +00:00
|
|
|
user = models.ForeignKey(
|
|
|
|
settings.AUTH_USER_MODEL,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name='user_libraries',
|
|
|
|
)
|
2013-10-10 19:56:40 +00:00
|
|
|
credential = models.CharField(max_length=30, null=True)
|
|
|
|
date_modified = models.DateTimeField(auto_now=True)
|
2013-10-11 02:31:31 +00:00
|
|
|
|
|
|
|
class EmailPattern(models.Model):
|
2018-07-24 03:48:35 +00:00
|
|
|
library = models.ForeignKey(Library, on_delete=models.CASCADE, related_name='email_auths')
|
2013-10-11 02:31:31 +00:00
|
|
|
# email endswith string
|
|
|
|
pattern = models.CharField(max_length=20)
|
|
|
|
|
|
|
|
def is_valid(self, email):
|
2018-07-26 17:59:58 +00:00
|
|
|
return email.lower().endswith(self.pattern.lower())
|
2018-12-07 19:51:25 +00:00
|
|
|
|
|
|
|
class BadUsernamePattern(models.Model):
|
|
|
|
pattern = models.CharField(max_length=100)
|
|
|
|
last = models.DateTimeField(default=timezone.now)
|
|
|
|
|
|
|
|
def matches(self, username):
|
|
|
|
if re.match(self.pattern, username):
|
|
|
|
self.last = timezone.now()
|
2018-12-07 21:00:44 +00:00
|
|
|
self.save()
|
2018-12-07 19:51:25 +00:00
|
|
|
return True
|
|
|
|
return False
|
2020-02-07 04:02:29 +00:00
|
|
|
|
|
|
|
def get_special():
|
2020-02-18 15:17:27 +00:00
|
|
|
try:
|
|
|
|
specials = Library.objects.filter(user__username='special')
|
|
|
|
for special in specials:
|
|
|
|
return special
|
|
|
|
return None
|
2020-02-18 15:35:22 +00:00
|
|
|
except OperationalError:
|
2020-02-18 15:17:27 +00:00
|
|
|
# database not loaded yet, for example during testing
|
|
|
|
return None
|
2020-02-07 04:02:29 +00:00
|
|
|
|