User authentication with django?

Because I did not want to use the authentication system in the Django format (maybe I should do this, please tell me if this is the case), I created a simple small auth class:

import random
import hashlib
from myapp import models

class CustomerAuth:
    key = 'customer'

    def __init__(self, session):
        self.session = session

    def attempt(self, email_address, password):
        password_hash = hashlib.sha1(password).hexdigest()
        try:
            return models.Customer.objects.get(
                email_address=email_address,
                password_hash=password_hash)
        except models.Customer.DoesNotExist:
            return None

    def login(self, customer):
        self.session[self.key] = customer

    def logout(self):
        if self.session.has_key(self.key):
            self.session[self.key] = None

    def is_logged_in(self):
        return self.session.has_key(self.key)
            and self.session[self.key] != None

    def get_active(self):
        if self.is_logged_in():
            return self.session[self.key]
        else:
            raise Exception('No user is logged in.')

    def redirect_to_login(self):
        return HttpResponseRedirect('/login/')

    def redirect_from_login(self):
        return HttpResponseRedirect('/account/')

The problem is that when I want to use it to prevent unauthorized access, I have to use this piece of code in each view method:

def example(req):
    auth = CustomerAuth(req.session)
    if not auth.is_logged_in():
        return auth.redirect_to_login()

As you can imagine, this gives a pretty ugly and repetitive code. What is the best way to do this? Should I use the Django auth framework?

+3
source share
1 answer

-, , Django auth backend.

-, , - , . . , Django @login_required decorator, , .

+15

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


All Articles