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

不打扰是莪最后的温柔 提交于 2021-02-17 07:00:07

问题


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

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

How can I ensure usernames are strictly alphanumeric (without @/./+/-/_.)?

I'm already using this clean_username() validator which currently works:

class UsernameMaxAdapter(DefaultAccountAdapter):

    def clean_username(self, username):
        exclude = ['@', '/', '.', '+', '-', '/', '_', ',']
        if len(username) > 20:
            raise ValidationError("Username can't be over 20 characters")
        for i in exclude:
            if i in username:
                raise ValidationError("Use only alphanumeric characters")
        return DefaultAccountAdapter.clean_username(self,username) # For other default validations.

Edit: Just realised both the validators are not working...trying to find the problem now..


回答1:


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'



回答2:


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]



回答3:


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).



来源:https://stackoverflow.com/questions/51704795/how-to-prevent-usernames-from-containing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!