Increasing Django login security and password strengths - django

When I create the Django superuser , if I try to add a weak password Django doesn't let me, but for normal users, in admin, or using register form I can add very simple password.
How can I ad the password validation from the superuser creation to all users ?
Can the number of login bad tries be limited (I prefer without third-party)

When creating users or super users alike both use the same Django configuration settings AUTH_PASSWORD_VALIDATORS and if left unmodified it'll contain a list of validators that all passwords will validate against when creating users via Django admin.
This is also the place where you strengthen your validators by adding more if you want harder or remove if you want to be more lax.
However, if you're creating users via the management commands create_user and create_superuser this list of validators will not apply. This is because Django assumes that only developers are interacting with Django at this level.
For your second ask, there is nothing built-in to Django that supports login tries and following blocking of further logins. This is something that either comes from 3rd party apps such as django-defender or from own implementation.
The broad strokes of that implementation is
Add a new tablemechanism that stores number of tries
Add a new settings in settings.py LOGIN_ATTEMPTS = 3
Override the login flow for a user in which you check this table for attempts
If failed attempt increment counter, if successful reset counter.
If user hits the limit of attempts, set users is_active to False and always return False from your login override.

Related

Django allauth - Add custom logic after email verification is successful

I am creating an application that has a list of Employees, and after a user registers and verifies their email, I create a relationship between the Employee and their User account.
I am using Django all auth, and have the email confirmation on GET set to True.
I am unsure on how I can add logic, so after the GET I perform some operations, find use the email to find the user, etc.
I have created a custom RegisterSerializer before, but since this is a GET instead of POST I wasn't sure if I could do something similar with EmailVerification.
How would I go about adding custom logic for this?

Django-allauth How to Ban Certain Users?

I'm using django-allauth for my Django web app. How can I ban certain users from logging in or restrict certain actions after they log in for a period of time?
Should I just deactivate their accounts outright? What are some good solutions?
Normally for django authentication you would set the user object's is_active attribute to False and the user wouldn't be able to log in (into django admin for example). But you're using allauth, so by simply setting the is_staff attribute would be enough to block them from entering django admin for example.
Now, if you're implementing another type of frontend dashboard or need to set rules to how a user logs in, I'd say for you to use AccessMixins if you're using CBVs or decorators if you're using FBV. Specially the UserPassesTest mixin and user_passes_test decorator. With them you can check if a user comply to a certain rule and then allow them to log in or not. Check the docs here.

Django registering users against a list of existing usernames

I am using Django rest framework to build my application backend. I have used Django-rest-auth (https://github.com/Tivix/django-rest-auth) to enable login and registration for my app. It is already working.
However as per my new requirement, I have a list of usernames and only those usernames can register into my system. How can I achieve this?
I had few ideas (do not know if they make total sense):
1. A new model to store usernames, so that in future more usernames can be added via admin interface
2. Whenever a user makes a call from client: the entered username is checked against this new usernames table and if it exists in the table registration is allowed.
Or there can be a still easier way to do this? Any code snippets?

Django view Site as another user from admin without knowing/resetting password

Is there a way in Django for the admin to view site as another user.
This can be used to debug user specific bugs.
As we don't know the password, the only solution I found is to reset the password from djangoadmin and login it to that user.
This functionality is not built-in to django, fortunately like many such cases, the community is there to help.
django-hijack does what you require:
django-hijack allows superusers to hijack (=login as) and work on
behalf of another user.

In Django, what is the right place to plug in changes to the user instance during the login process?

Background
I have a custom authentication back end for our django applications that refers to an LDAP server.
As soon as I authenticate someone, I have a wealth of information that our network infrastructure guys put in the LDAP server about the user - their last names (which can change, for instance, if they marry), their e-mails (which can also change), plus other company specific information that would be useful to transfer to the Django auth_user table or profile table for local reference. (*)
To take advantage of this data, as of now, in our custom authenticate method I'm looking up (if it is an existing user logging in) or creating a new (if a new user that never logged in to our Django apps) user, making any changes to it and saving it.
This smells bad to me. Authentication should be about saying yay or nay in granting access, not about collecting information about the user to store. I believe that should happen elsewhere!
But I don't know where that elsewhere is...
My current implementation also causes a problem on the very first login of a user to one of our Django apps, because:
New user to our apps logs in - request.user now has a user with no user.id
My custom authenticate method saves the user information. Now the user exists in the DB
django.contrib.auth.login() kicks in and retrieves the request.user (which still has no user.id and no idea that authenticate saved the user) and tries to save an update to last logged in date.
Save fails because there is already a row in the database for that username (unique constraint violation)
Yes, this only happens the very first time a user logs in; the next time around it will be an update, request.user will have a user.id and everything is fine.
Edit: I'm investigating the striked-out area above. The login code clearly only uses the request.user if the user is None (which, coming out of the validation of the AuthenticationForm it shouldn't be. I probably am doing something wrong in my code...
But it still smells bad to have the authentication doing more than just, you know, authenticating...
Question
What is the right place to plug in changes to the user instance during the login process?
Ideally I would be able to, in my custom authenticate method, state that after login the information collected from a LDAP server should be written to the user instance and potentially the user profile instance.
(*) I do this local caching of the ldap information because I don't want to depend on it being up and running to let users log in to my systems; if ldap is down, the last username and password in auth_user are accepted.
I've done similar things by writing my own authentication backend and putting it in the authenticate() method. The code is public and up here. I also included a pluggable system of "mappers" to do most of the work that isn't just authenticating the user (eg, getting fullname from ldap, automatically creating groups based on "affiliations" that our auth service gives us, and mapping certain users and affiliations into staff/superuser roles automatically).
Basically, the authenticate method looks like:
def authenticate(self, ticket=None):
if ticket is None:
return None
# "wind" is our local auth service
(response,username,groups) = validate_wind_ticket(ticket)
if response is True:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
user = User(username=username, password='wind user')
user.set_unusable_password()
# give plugins a chance to pull up more info on the user
for handler in self.get_profile_handlers():
handler.process(user)
user.save()
# give plugins a chance to map affiliations to groups
for handler in self.get_mappers():
handler.map(user,groups)
return user
else:
# i don't know how to actually get this error message
# to bubble back up to the user. must dig into
# django auth deeper.
pass
return None
So I pretty much agree with you that authentication should be just a yes/no affair and other stuff should happen elsewhere, but I think with the way Django sets things up, the path of least resistance is to put it in with authentication. I do recommend making your own authentication code delegate that stuff to plugins though since that's within your control.
I'm only fetching the LDAP data on their very first login though (when the auth_user row gets added). Anytime they login after that, it just uses what it already has locally. That means that if their LDAP info changes, it won't automatically propagate down to my apps. That's a tradeoff I'm willing to make for simplicity.
I'm not sure why you're running into problems with the first login though; I'm taking a very similar approach and haven't run into that. Maybe because the login process on my apps always involves redirecting them to another page immediately after authentication, so the dummy request.user never gets touched?
This will be a two part answer to my own question.
What is the right place to plug in changes to the user instance during the login process?
Judging from the Django code, my current implementation, and thraxil's answer above, I can only assume that it is expected and OK to modify the user instance in a custom authenticate() method.
It smells wrong to me, as I said in my question, but the django code clearly assumes that it is possible that a user instance will be modified and I can find no other hooks to apply changes to the user model AFTER authentication, elsewhere.
So, if you need an example, look at thraxil's code - in the selected answer to my question.
Why my implementation is working differently from thraxil's and generating a unique constraint violation?
This one was rather nasty to figure out.
There is absolutely nothing wrong with Django. Well, if it already supported multiple databases (it is coming, I know!!!) I probably wouldn't have the problem.
I have multiple databases, and different applications connect to one or more different ones. I'm using SQL Server 2005 (with django_pyodbc). I wanted to share the auth_user table between all my applications.
With that in mind, what I did was create the auth models in one of the databases, and then create SQL Server synonyms for the tables in the other databases.
It works just fine: allowing me to, when using database B, select/insert/update/delete from B.dbo.auth_user as if it were a real table; although what is really happening is that I'm operating on A.dbo.auth_user.
But it does break down in one case: to find the generated identity, django_pyodbc does a:
SELECT CAST(IDENT_CURRENT(%s) as bigint) % [table_name]
and that doesn't appear to work against synonyms. It always returns nulls. So when in my authenticate() method I did user.save(), the saving part worked fine, but the retrieval of the identity column didn't - it would keep the user instance with a id of None, which would indicate to the django code that it should be inserted, not updated.
The workaround: I had two choices:
a) Use views instead of synonyms (this is what I did)
b) Reload the user right after a user.save() using User.objects.get(username=username)
Hope that might help someone else.