使用Django自定义身份验证?

编程入门 行业动态 更新时间:2024-10-21 10:15:26
本文介绍了使用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的内置的框架,您可以访问到@login_required装饰,这不正是你想要的东西。

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自定义身份验证?

本文发布于:2023-10-27 03:10:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532138.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   身份验证   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!