Commit 353b63c2 authored by David Seaward's avatar David Seaward

login and register update

* update labels on all forms
* add validator for username registration (letter followed by alphanumerics)
* allow @domain suffix for username login
* move DEBUG_ALL_ACCESS logic to the right place (and apply only to inactive limits)
parent 26e8f270
from django.contrib import admin
from .models import LdapGroup, LdapPerson
#
# Declare admin models
#
......@@ -14,6 +16,7 @@ class LdapPersonAdmin(admin.ModelAdmin):
exclude = ['dn', 'objectClass']
list_display = ['uid', 'description', ]
#
# Register admin models
#
......
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import AuthenticationForm as BaseAuthenticationForm
from django.utils.translation import ugettext_lazy as _
from registration.forms import RegistrationForm as BaseRegistrationForm
from django.contrib.auth.forms import AuthenticationForm as BaseAuthenticationForm
from django.contrib.auth import get_user_model
User = get_user_model()
......@@ -23,6 +23,7 @@ class RegistrationForm(BaseRegistrationForm):
self.fields[User.USERNAME_FIELD].label = _("Username")
self.fields["password1"].label = _("Passphrase")
self.fields["password2"].label = _("Passphrase confirmation")
self.fields["password2"].help_text = _("Enter the same passphrase as before, for verification.")
class Meta(BaseRegistrationForm.Meta):
......
import django.contrib.auth
import paramiko
from celery.utils.log import get_task_logger
from django.conf import settings
from django.db import transaction
from django.utils import timezone
from woocommerce import API as WOO_API
import django.contrib.auth
from ..models import ExternalCredit, ExternalBundle, Limit
......@@ -101,6 +101,9 @@ def activate(ssh, limit, credit_timedelta=None, renewal_date=None):
if limit.service == "TUNNEL":
managed_exec(ssh, "./create_new_ovpn_config --generate %s" % (limit.user.get_identity(),))
else:
# skip unsupported limits
limit.is_active = False
limit.save()
......
......@@ -3,11 +3,11 @@ from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User
#
# Declare admin models
#
class UserAdmin(BaseUserAdmin):
pass
......
import logging
from django.contrib.auth.password_validation import MinimumLengthValidator as BaseValidator
from django.core import validators
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
from django_auth_ldap.backend import LDAPBackend as BaseBackend
from django.utils.translation import ungettext
log = logging.getLogger(__name__)
......@@ -13,19 +14,28 @@ class AuthenticationBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(AuthenticationBackend, self).__init__(*args, **kwargs)
# def ldap_to_django_username(self, username):
# return username.lower().replace(".", "")
def authenticate(self, request=None, username=None, password=None, **kwargs):
model = self.get_user_model()
username = model.normalize_username(username)
# TODO: also validate, so that existing but invalid usernames are not permitted?
return super(AuthenticationBackend, self).authenticate(request, username, password, **kwargs)
@deconstructible
class UsernameValidator(validators.RegexValidator):
regex = r'^[A-Za-z][A-Za-z0-9]*$'
message = _(
'Enter a valid username. Must start with a letter, followed by letters and numbers. No punctuation or special characters.'
)
class PassphraseValidator(BaseValidator):
# TODO: bundle in all the other validators from django.contrib.auth.password_validation
def __init__(self, min_length=15, *args, **kwargs):
super(PassphraseValidator, self).__init__(min_length=15, *args, **kwargs)
super(PassphraseValidator, self).__init__(min_length, *args, **kwargs)
def get_help_text(self):
return ungettext(
"A good passphrase is made of at least three long words.",
"A good passphrase is made of at least three long words.",
0
)
return _("A good passphrase is made of at least three long words.")
import logging
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import UserManager as BaseUserManager
from django.utils.crypto import salted_hmac
from django.db import models
from django.utils import timezone
from django.conf import settings
from django.utils.crypto import salted_hmac
from django.utils.translation import ugettext_lazy as _
from ldapregister.models import LdapPerson
from limitmonitor import models as limitmonitor_models
from limitmonitor.task_resources import common as limitmonitor_common
from ldapregister.models import LdapPerson
from .custom import UsernameValidator
log = logging.getLogger(__name__)
......@@ -20,14 +23,6 @@ class UserManager(BaseUserManager):
user = super(UserManager, self).create_user(username, email, password, **extra_fields)
if settings.DEBUG_ALL_ACCESS:
ssh = limitmonitor_common.get_openvpn_ssh_connection()
renewal_date = timezone.now() + timezone.timedelta(weeks=5200)
for limit in limitmonitor_models.Limit.objects.filter(user=user, service="TUNNEL"):
limitmonitor_common.activate(ssh, limit, renewal_date=renewal_date)
def create_superuser(self, username, email=None, password=None, **extra_fields):
"""Create superusers with a Django password."""
......@@ -37,16 +32,33 @@ class UserManager(BaseUserManager):
class User(AbstractUser):
objects = UserManager()
REQUIRED_FIELDS = []
username_validator = UsernameValidator()
username = models.CharField(
_('username'),
max_length=150,
unique=True,
help_text=_('Required. Start with a letter, followed by letters and numbers.'),
validators=[username_validator],
error_messages={
'unique': _("A user with that username already exists."),
},
)
def __init__(self, *args, **kwargs):
user = super(User, self).__init__(*args, **kwargs)
return user
super(User, self).__init__(*args, **kwargs)
@classmethod
def normalize_username(cls, username):
username = super(User, cls).normalize_username(username)
return username.lower()
username = username.lower()
suffix = "@" + settings.SITE_DOMAIN
if username.endswith(suffix):
username = username[:-len(suffix)]
return username
def validate_unique(self, exclude=None):
......@@ -80,12 +92,20 @@ class User(AbstractUser):
if not self.has_ldap():
self.create_ldap()
# force null password (will use LDAP password instead)
# force null Django password (will use LDAP password instead)
self.set_unusable_password()
# create any missing limits
limitmonitor_models.create_missing_user_limits(self)
if settings.DEBUG_ALL_ACCESS:
ssh = limitmonitor_common.get_openvpn_ssh_connection()
renewal_date = timezone.now() + timezone.timedelta(weeks=5200)
for limit in limitmonitor_models.Limit.objects.filter(user=self, is_active=False):
limitmonitor_common.activate(ssh, limit, renewal_date=renewal_date)
def set_password(self, raw_password):
# force null Django password (will use LDAP password)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment