Added validator to allow only letters + spaces + hyphen, Normalizing usernames to ASCII

This commit is contained in:
ahmadbilalkhalid 2019-12-13 20:37:30 +05:00
parent b4995336c6
commit 2a1932e052
5 changed files with 65 additions and 55 deletions

View file

@ -1 +1 @@
10185
10192

View file

@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2019-12-13 13:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('membership', '0015_customuser_in_ldap'),
]
operations = [
migrations.AlterField(
model_name='customuser',
name='username',
field=models.CharField(max_length=60, null=True, unique=True),
),
]

View file

@ -1,5 +1,6 @@
import logging
import random
import unicodedata
from datetime import datetime
from django.conf import settings
@ -12,6 +13,8 @@ from django.core.validators import RegexValidator
from django.db import models, IntegrityError
from django.utils.crypto import get_random_string
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from utils.mailer import BaseEmail
from utils.mailer import DigitalGlarusRegistrationMailer
@ -82,10 +85,8 @@ def assign_username(user):
# Try to come up with a username
first_name, last_name = get_first_and_last_name(user.name)
user.username = first_name + last_name
user.username = "".join(user.username.split()).lower()
user.username = "".join([char for char in user.username if char.isalnum()])
user.username = unicodedata.normalize('NFKD', first_name + last_name)
user.username = "".join([char for char in user.username if char.isalnum()]).lower()
exist = True
while exist:
# Check if it exists
@ -102,12 +103,21 @@ def assign_username(user):
user.username = user.username + str(random.randint(0, 2 ** 10))
def validate_name(value):
valid_chars = [char for char in value if (char.isalpha() or char == "-" or char == " ")]
if len(valid_chars) < len(value):
raise ValidationError(
_('%(value)s is not a valid name. A valid name can only include letters, spaces or -'),
params={'value': value},
)
class CustomUser(AbstractBaseUser, PermissionsMixin):
VALIDATED_CHOICES = ((0, 'Not validated'), (1, 'Validated'))
site = models.ForeignKey(Site, default=1)
name = models.CharField(max_length=50)
name = models.CharField(max_length=50, validators=[validate_name])
email = models.EmailField(unique=True)
username = models.CharField(max_length=50, unique=True, null=True)
username = models.CharField(max_length=60, unique=True, null=True)
validated = models.IntegerField(choices=VALIDATED_CHOICES, default=0)
in_ldap = models.BooleanField(default=False)
# By default, we initialize the validation_slug with appropriate value
@ -232,6 +242,7 @@ class CustomUser(AbstractBaseUser, PermissionsMixin):
email=self.email)
self.in_ldap = True
self.save()
def __str__(self): # __unicode__ on Python 2
return self.email

View file

@ -4,6 +4,7 @@ import logging
from membership.models import CustomUser
logger = logging.getLogger(__name__)
class MyLDAPBackend(object):
def authenticate(self, email, password):
try:
@ -18,54 +19,6 @@ class MyLDAPBackend(object):
else:
return None
# # User exists in Database
# user.create_ldap_account()
# # User does not have a username
# if not user.username:
# assign_username(user)
#
# ldap_manager = LdapManager()
# try:
# user_exists_in_ldap, entries = ldap_manager.check_user_exists(
# uid=user.username,
# attributes=['uid', 'givenName', 'sn', 'mail', 'userPassword'],
# search_base=settings.ENTIRE_SEARCH_BASE,
# search_attr='uid'
# )
# except Exception:
# logger.exception("Exception occur while searching for user in LDAP")
# else:
# ph = PasswordHasher()
# if user_exists_in_ldap:
# # User Exists in LDAP
# password_hash_from_ldap = entries[0]["userPassword"].value
# try:
# ph.verify(password_hash_from_ldap, password)
# except Exception:
# # Incorrect LDAP Password
# return None
# else:
# # Correct LDAP Password
# return user
# else:
# # User does not exists in LDAP
# if user.check_password(password):
# # Password is correct as per database
# first_name, last_name = get_first_and_last_name(user.name)
# if not last_name:
# last_name = first_name
#
# ldap_manager.create_user(user.username, password=ph.hash(password),
# firstname=first_name, lastname=last_name,
# email=user.email)
# user.password = "IN_LDAP"
# user.save()
# return user
# else:
# # Incorrect Password
# print("Incorrect password")
# return None
def get_user(self, user_id):
try:
return CustomUser.objects.get(pk=user_id)

File diff suppressed because one or more lines are too long