How to prevent usernames from containing @/./+/-/_.?

后端 未结 3 1881
故里飘歌
故里飘歌 2021-01-27 09:38

I\'m using django-allauth, and for some reason the username default allows:

\"letters, digits and @/./+/-/_.\"

How can I ensure usernames are strictly alphanumer

相关标签:
3条回答
  • 2021-01-27 09:56

    I haven't used django and certainly don't know about its authorisation mechanisms, but I know that in plain python, if you wanted to carry this out, you could simply sanitise input by doing:

    newUserName = ''.join(ch for ch in oldUserName if ch.isalnum())
    

    Essentially, I'm looping through each character and am appending them to the 'clean' username if the character is alphanumeric.

    In your function, if the username doesn't comply with the alphanumeric restrictions, execute the statement above (place it under the if).

    0 讨论(0)
  • 2021-01-27 10:01

    You could use a regex expression to ensure that a username contains only allowed characters. For alphanumeric characters the following should do the trick:

    import re
    def is_valid_username(username):
        pattern = re.compile('([a-zA-Z]+|\d+)')
        return ''.join(re.findall(pattern, username)) == username
    

    Here's an example of the output:

    username_list = ["WhatAGre4tUsern4me", "548ThatISAgoodUsername005",
                     "CheckOutMy_Username", "It'sAUsern@me"]
    print([is_valid_username(u) for u in username_list])
    >>> [True, True, False, False]
    
    0 讨论(0)
  • 2021-01-27 10:12

    I think python's builtin function str.isalnum() could be usefull here.

    class UsernameMaxAdapter(DefaultAccountAdapter):
        def clean_username(self, username):
            # assumes "username" is a type of "str" object
            if not username.isalnum():
                raise ValidationError("Use only alphanumeric characters")
            # your logic



    UPDATE-1
    set ACCOUNT_USERNAME_VALIDATORS in settings.py as mentioned in documentation

    class CustomValidator(object):
    
        def __call__(self, username="", *args, **kwargs):
            username = username.isalnum()
            if not username:
                raise ValidationError("Use only alphanumeric characters")
    


    in your settings.py,

    custom_username_validators = [CustomValidator()]
    ACCOUNT_USERNAME_VALIDATORS = 'path.to.settings.custom_username_validators'
    
    0 讨论(0)
提交回复
热议问题