Django: how to override authenticate () method?

I am using a custom User and I have an email_verified field for this user. I would like the user to log in to be rejected if this field is false .

I cannot do this in views.py , since users can log in from different sources (Django site, but REST API too). The whole goal is to avoid writing N times of logic for the N sign in the sources. I would like to override the ( login() ? authenticate() ?) Method in models.py to do this only once.

I quickly read the authentication setup document, but did'nt not find what I was looking for.

Thanks for the help.

-1
source share
1 answer

Please refer to the Django Doc: Having written an authentication server , this is probably what you need. It covers both uses of common logins and REST APIs, such as token authentication:

 The authenticate method takes credentials as keyword arguments. Most of the time, it'll just look like this: class MyBackend(object): def authenticate(self, username=None, password=None): # Check the username/password and return a User. ... But it could also authenticate a token, like so: class MyBackend(object): def authenticate(self, token=None): # Check the token and return a User. ... Either way, authenticate should check the credentials it gets, and it should return a User object that matches those credentials, if the credentials are valid. If they're not valid, it should return None. 

Once you have written your own authentication server, you just need to change your own default backend in your settings.py as follows:

 AUTHENTICATION_BACKENDS = ('project.path.to.MyBackend',) 

Update

Instead of overriding the default authenticate behavior, you can simply include both Backend in your settings, for example:

 AUTHENTICATION_BACKENDS = ('project.path.to.MyBackend', 'django.contrib.auth.backends.ModelBackend',) 

The order of the backends matters, you can read the source code and better understand how authenticate works by default and all together ( Read here )

AFAIK is the preferred way to configure authenticate , because one day you can change your default backend to something like RemoteUserBackend or whatever (for example, from RestFramework), and so you can just put your logic (MyBackend) on order in your settings and no need to worry about code breaking.

Hope this helps.

+3
source

Source: https://habr.com/ru/post/978081/


All Articles