First, the initialization menu, right information
In a user-name and password verification is successful after initialize authority and menus to generate the user's menu and authority data.
class the LoginView (APIView): authentication_classes = [] # landing page-free, the rest of the global configuration has DEF POST (Self, Request, * args, ** kwargs): RET = { " Data " : {}, " Meta " : { " code " : 2001 , " Message " : " user name or password error " } } USER_OBJ = json.loads (STR (request._request.body, encoding = ' UTF8 ')) username = user_obj.get('username') password = user_obj.get('password') if username and password: obj = UserInfo.objects.filter( username=username, password=password).first() if obj: #初始化权限、菜单信息 InitPermission(request,obj).init_menus_dict() InitPermission(request,obj).init_permissions_dict() # 生成token值 # token=str(uuid.uuid4()) #uuid生成token token = get_md5(username) ret["data"]["username"] = username ret["data"]["password"] = password ret["data"]["token"] = token # ret["data"]["permission_session_id"] = settings.PERMISSION_SESSION_KEY # ret["data"]["menu_session_id"] = settings.MENU_SESSION_KEY ret["meta"]["code"] = 2000 ret["meta"]["message"] = "登陆成功" else: pass else: pass return HttpResponse(json.dumps(ret, ensure_ascii=False))
Second, the Build menu, right information
Processed by the username passed Initpermission class
from RBAC Import Models from django.conf Import Settings from crm.utils.session Import SessionStore Import JSON class InitPermission (Object): DEF the __init__ (Self, Request, User): self.request = Request self.user = User self.permissions_dict = } { self.menus_dict = {} DEF init_data (Self): "" " acquired right information and user information from the database : return: " "" self.permissions_queryset = self.user.roles.filter(permissions__url__isnull=False).values( 'permissions__id', 'permissions__url', 'permissions__title', 'permissions__parent_id', 'permissions__action__code', 'permissions__menu_id', 'permissions__menu__title', 'permissions__menu__icon', ' Permissions__menu__position ' ) .distinct () return self.permissions_queryset DEF init_permissions_dict (Self): "" " initialize permissions, user privileges acquired and added to the current session of the user rights information current is converted to the following format, and add it to the Session { '/index.html': [ 'the GET', 'the POST', 'DEL', 'the EDIT], ' /detail-(\d+).html ': [' the GET ',' the POST ',' DEL ', 'the EDIT], } : return: "" " for Row in self.init_data (): IF Row [ " permissions__url "] in self.permissions_dict: self.permissions_dict[row["permissions__url"]].append(row["permissions__action__code"]) else: self.permissions_dict[row["permissions__url"]] = [row["permissions__action__code"], ] print('init',self.permissions_dict) #将权限信息存入redis,后续中间件中去除进行验证 SessionStore().set_session(settings.PERMISSION_SESSION_KEY,self.permissions_dict) return self.permissions_dict def init_menus_dict(self): """ self.menus_dict={ 1:{ title:'客户管理',icon:'fa fa-coffe',children:[ {'id':1,'url':'/customer/list/','title':'客户列表'} ... ] } } :return: """ for row in self.init_data(): menu_id = row["permissions__menu_id"] if not menu_id: continue if menu_id not in self.menus_dict: self.menus_dict[row["permissions__menu__position"]] = { "id":row["permissions__menu_id"], "title": row["permissions__menu__title"], "icon": row["permissions__menu__icon"], "children": [ { 'id': row['permissions__id'], 'title': row['permissions__title'], 'url': row['permissions__url'] } ] } else: self.menus_dict[row["permissions__menu__position"]]["children"].append( { 'id': row['permissions__id'], 'title': row['permissions__title'], 'url': row['permissions__url'] } ) return self.menus_dict
Wherein the menu information generation following form:
{ { ' Title ' : ' User Manager ' , ' icon ' : ' EL-icon-LOCATION ' , ' ID ' :. 1 , ' Children ' : [{ ' title ' : ' User List ' , ' URL ' : ' / CRM / User ' , ' ID ' :. 1 }, { 'title': ' List of departments ' , ' URL ' : ' / CRM / Dept ' , ' ID ' :. 11 } ] }, { ' title ' : ' rights management ' , ' icon ' : ' EL-icon-S-Check ' , ' ID ' : 2 , ' Children ' : [{ ' title ' : 'Permissions list ', ' URL ' : ' / RBAC / Rights / List ' , ' ID ' : 2 }, { ' title ' : ' role list ' , ' URL ' : ' / RBAC / Roles ' , ' ID ' :. 7 }, { ' title ' : ' menu list ' , ' url ' : '/crm/menus', 'id': 12} ] } }
Right information generates the following form:
{ '/crm/dept': ['get'], '/crm/menus': ['get'], '/rbac/roles': ['get'], '/rbac/roles/(?P<roleId>\\d+)/permission$': ['put'], '/rbac/rights/list': ['get'], '/rbac/roles/(?P<roleId>\\d+)/permission/(?P<permissionId>\\d+)$': ['delete'], '/crm/user': ['get', 'post'] }
Above is the one owned by the user menu and rights information.
Third, check the permissions middleware
from django.utils.deprecation import MiddlewareMixin from django.conf import settings import re from django.shortcuts import HttpResponse import json from crm.utils.session import SessionStore class RbacMiddleware(MiddlewareMixin): def process_request(self,request,*args,**kwargs): """跳过无需权限访问的URL""" # permission_dict = request.session.get(settings.RBAC_PERMISSION_SESSION_KEY) print('process_request',request.path_info) for pattern in settings.RBAC_NO_AUTH_URL: if re.match(pattern, request.path_info): return None #从redis中获取permission_dict,是bytes类型 permission_bytes = SessionStore().get_session(settings.PERMISSION_SESSION_KEY) permission_dict = eval(permission_bytes)
if not permission_dict: return HttpResponse(json.dumps({"data": {}, "meta": {"message": "无权限访问" , " Code " : 2002 }})) # request url and authority redis stored matching " "" { '/ Rights': [ 'GET'], '/ User': [ 'GET', 'POST' ], '/ Roles': [ 'GET']} "" " in Flag = False for pattern, code_list in permission_dict.items (): Print ( ' PAR, code ... ' , pattern, request.path_info) upper_code_list = [ item.upper() for item in code_list] request_permission_code = request.method ifre.match (pattern, request.path_info): Print (request_permission_code) Print (upper_code_list) IF request_permission_code in upper_code_list: permission_code_list = upper_code_list
# will be stored user role requests mode, authentication passed to the front end of a button authority SessionStore (). set_session (settings.PERMISSION_CODE_LIST_KEY, permission_code_list) In Flag = True BREAK IF Not In Flag: return the HttpResponse (json.dumps ({ " Data ": {}, " Meta " : { " the Message " : " RBAC no access " , " code " : 2002}}))