Django view 权限验证

时间:2022-01-07 05:21:02

用过Django的人们都应该知道,Django集成了一个强大的auth应用。若我们有些页面需要验证权限才能进入的,则我们可以自定义一个装饰器进行拦截并验证。

代码如下:

from django.contrib.auth import authenticate
from django.http import HttpResponse
import json

def auth_required(view):
    '''
     Authentication decorator 
    '''
    def decorator(request, *args, **kwargs):
        username = request.POST.get('apiusername', None)
        password = request.POST.get('apipassword', None)
        user = authenticate(username=username, password=password)
        error_info = None
        if user is not None:
            if not user.is_active:
                # Return a 'disabled account' error message
                error_info = 'Your account has been disabled!'
        else:
            # Return an 'invalid login' error message.
            error_info = 'Your username or password is incorrect.'
        if error_info:
            resp = {'error_info' : error_info}
            data = json.dumps(resp)        
            return HttpResponse(data, 'application/javascript')
        else:
            return view(request, *args, **kwargs)
    return decorator

使用方法如下:

@auth_required
def my_view():
    pass