使用Django自定义身份验证? [英] Custom authentication with django?
问题描述
由于我不想使用Django在构建认证系统(也许我应该做的,请告诉我,如果是这样的话),我创建了一个简单的小AUTH类:
Because I didn't want to use Django's in-build authentication system (maybe I should do, please tell me if this is the case), I created a simple little 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/')
问题是,当我想用它来阻止未经授权的访问,我在每一个单一视图的方法来使用这个code片断:
The problem is, that when I want to use it to stop unauthorized access, I have to use this code snippet in every single view method:
def example(req):
auth = CustomerAuth(req.session)
if not auth.is_logged_in():
return auth.redirect_to_login()
你可以想象,这会产生相当丑陋和重复code。什么是这样做的更好的办法?我应该使用Django的权威性框架?
As you can imagine, this yields fairly ugly and repetitive code. What is a better way of doing this? Should I be using Django's auth framework?
推荐答案
首先,是你应该使用Django的认证框架,并建立自己的自定义身份验证后端。
Firstly, yes you should use Django's authentication framework, and build your own custom auth backend.
其次,但你这样做,你需要在你想限制访问的意见的东西。要做到这一点,最好的方法是通过在视图上一个装饰。同样,Django的内置的框架,您可以访问到<一个href=\"http://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator\"><$c$c>@login_required$c$c>装饰,这不正是你想要的东西。
Secondly, however you do it, you'll need to have something in the views that you want to restrict access to. The best way to do that is via a decorator on the view. Again, Django's built-in framework gives you access to the @login_required
decorator, which does exactly what you want.
这篇关于使用Django自定义身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!