【问题标题】:Custom authentication with django?使用 django 进行自定义身份验证?
【发布时间】:2009-11-23 10:59:58
【问题描述】:

因为我不想使用 Django 的内置身份验证系统(也许我应该这样做,如果是这种情况请告诉我),我创建了一个简单的小 auth 类:

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/')

问题是,当我想用​​它来阻止未经授权的访问时,我必须在每个单独的视图方法中使用这段代码 sn-p:

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

您可以想象,这会产生相当丑陋和重复的代码。有什么更好的方法来做到这一点?我应该使用 Django 的身份验证框架吗?

【问题讨论】:

    标签: django authentication


    【解决方案1】:

    首先,是的,您应该使用 Django 的身份验证框架,并构建您自己的custom auth backend。

    其次,无论您怎么做,您都需要在视图中添加一些您想要限制访问的内容。最好的方法是通过视图上的装饰器。同样,Django 的内置框架让您可以访问 @login_required 装饰器,这正是您想要的。

    【讨论】:

    • 谢谢 - 现在刚刚实现。实际上很容易做到令人惊讶。另外,即使它是“必需的”,我也不需要使用用户名属性(因为我想使用电子邮件地址进行身份验证)。
    猜你喜欢
    • 2016-07-05
    • 2012-05-06
    • 2016-07-09
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多