diff --git a/README.md b/README.md index 0eeb093..809323c 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ OPENID_CONNECT_VIEWSET_CONFIG = { # that's used to validate all field inputs retrieved for the particular key "FIELD_VALIDATION_REGEX": { "username": { - "regex": "(?!^\d+$)^.+$", + "regex": "^(?!\d+$).{4,}$", "help_text": "Username should only contain alpha numeric characters", } }, diff --git a/oidc/settings.py b/oidc/settings.py index 4c41b5a..c8a3477 100644 --- a/oidc/settings.py +++ b/oidc/settings.py @@ -18,7 +18,7 @@ "JWT_ALGORITHM": "HS256", "FIELD_VALIDATION_REGEX": { "username": { - "regex": "(?!^\d+$)^.+$", # noqa + "regex": "^(?!\d+$).{4,}$", # noqa "help_text": "Username should only contain alpha numeric characters", } }, diff --git a/oidc/viewsets.py b/oidc/viewsets.py index a8f55f8..25faedc 100644 --- a/oidc/viewsets.py +++ b/oidc/viewsets.py @@ -1,6 +1,7 @@ """ oidc Viewsets module """ + import importlib import re from typing import Optional, Tuple @@ -226,9 +227,15 @@ def _clean_user_data(self, user_data) -> Tuple[dict, Optional[list]]: user_data["first_name"] = user_data["last_name"] missing_fields.remove("first_name") - # use email as username if username is missing + # use email as username if username is missing or username is invalid if self.use_email_as_username: - if "username" in missing_fields and "email" in user_data: + username_regex = re.compile( + self.field_validation_regex["username"].get("regex") + ) + if ( + "username" in missing_fields + or not username_regex.search(user_data["username"]) + ) and "email" in user_data: username = user_data["email"].split("@")[0] if ( self.user_model.objects.filter(username__iexact=username).count() @@ -245,13 +252,12 @@ def _clean_user_data(self, user_data) -> Tuple[dict, Optional[list]]: ) # Validate retrieved username matches regex - if "username" in self.field_validation_regex: - regex = re.compile( - self.field_validation_regex["username"].get("regex") - ) - if regex.search(username): - user_data["username"] = username - missing_fields.remove("username") + if ( + "username" in self.field_validation_regex + and username_regex.search(username) + ): + user_data["username"] = username + missing_fields.remove("username") return user_data, missing_fields diff --git a/tests/test_viewsets.py b/tests/test_viewsets.py index 6d5e706..b18e15e 100644 --- a/tests/test_viewsets.py +++ b/tests/test_viewsets.py @@ -1,6 +1,7 @@ """ Tests for the OpenID Client """ + from django.contrib.auth import get_user_model from django.test import TestCase from django.test.utils import override_settings @@ -46,7 +47,7 @@ "JWT_SECRET_KEY": "abc", "FIELD_VALIDATION_REGEX": { "username": { - "regex": "^[\w\d]*$", + "regex": "^(?!\d+$).{4,}$", "help_text": "Username should only contain word characters & numbers i.e datatester23", }, },