DEV Community

Discussion on: Django user auth

Collapse
 
agronick profile image
Kyle Agronick • Edited

This is not how to do authentication in Django.

Edit: I forgor the biggest issue. None of your passwords are hashed!

Your current view does no validation except checking that the passwords are equal and the user doesn't exist. All that validation should be happening on the Form layer - not the view layer. Currently a user could create an account with a username and password of ''. The point of Django is not to have to code stuff like that. Using a form would allow you to easily add validation rules and empty values would be prohibited by default. I know that this is probably an example and not meant for production but people find examples like these and they end up copying and pasting them without a second thought.

Additionally, this is duplicating a lot of logic that is built into Django. There are much more robust class based views for doing these authentication procedures. You should override just the parts of the views that you need to change. There are authentication forms (also shown on that page) that you can use or extend if you need custom logic on the form layer.

Using the default login view the login method you have would be rewritten:

from django.contrib.auth.views import LoginView

class MyLogin(LoginView):
    template_name = 'accounts/login.html'

You don't even need that. You could just pass template_name to as_view() in urls.py.

from django.contrib.auth.views import LoginView

urlpatterns = [
    path('login/', LoginView.as_view(template_name='accounts/login.html')),
]

There is another layer called the authentication provider. The default method of authentication is to use the ModelBackend which uses the database. If you need your own authentication through something like a REST API you would use an autenication provider.

You can switch out the authentication provider without touching the login form or view.

The only view Django doesn't provide is the sign up view. You will have to implement that yourself but I would recommend using a class based view with a form. You could use a CreateView. You definitely shouldn't use raw unsanitized POST variables.

Collapse
 
wesleyruede profile image
Wesley Ruede • Edited

Well, I guess in that case I could just add the HTML form. I didn't realize that I needed to show that. Thank you for the info. I'll make this post much better!