|
|
|
|
import json
|
|
|
|
|
from django_redis import get_redis_connection
|
|
|
|
|
from erp_system.models import PermissionsModel
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def cache_permissions_by_user(user):
|
|
|
|
|
"""
|
|
|
|
|
把当前用户的权限信息,缓存到Redis数据库中
|
|
|
|
|
Redis 中存放用户权限的结构为: user_用户ID---> 字典{key:path, value[列表] }
|
|
|
|
|
"""
|
|
|
|
|
permission_ids = user.roles.values_list('permissions', flat=True).distinct()
|
|
|
|
|
# permission_list 返回是列表和字典的嵌套,如下:[{'id':1, 'path': '/xxx/xxx'}, {'id':2, 'path': '/xxx/aaa'}]
|
|
|
|
|
permission_list = PermissionsModel.objects.filter(id__in=permission_ids, is_menu=False).values('id', 'path', 'method', 'name')
|
|
|
|
|
|
|
|
|
|
if not permission_list.exists():
|
|
|
|
|
# 该用户根本就没有分配权限, 直接返回
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
permission_dict = {} # 存放权限的字典
|
|
|
|
|
for permission in permission_list: # permission是字典
|
|
|
|
|
# 去除不可见字符, ’\u200b’是Unicode中的零宽度字符,可以理解为不可见字符。
|
|
|
|
|
method = str(permission.get('method')).replace('\u200b', '')
|
|
|
|
|
path = str(permission.get('path')).replace('\u200b', '')
|
|
|
|
|
_name = str(permission.get('name')).replace('\u200b', '')
|
|
|
|
|
_id = permission.get('id')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if permission_dict.get(path):
|
|
|
|
|
# 如果字典中已经存在一个相同path的权限,把新权限追加
|
|
|
|
|
permission_dict[path].append({
|
|
|
|
|
'method': method,
|
|
|
|
|
'sign': _name,
|
|
|
|
|
'id': _id
|
|
|
|
|
})
|
|
|
|
|
else:
|
|
|
|
|
permission_dict[path] = [{
|
|
|
|
|
'method': method,
|
|
|
|
|
'sign': _name,
|
|
|
|
|
'id': _id
|
|
|
|
|
}]
|
|
|
|
|
|
|
|
|
|
# 因为redis中的值,只能存放字节, 由字符串转换字节 。 json格式的字符串
|
|
|
|
|
for key in permission_dict:
|
|
|
|
|
permission_dict[key] = json.dumps(permission_dict[key])
|
|
|
|
|
|
|
|
|
|
redis_conn = get_redis_connection('default')
|
|
|
|
|
redis_conn.hmset(f'user_{user.id}', permission_dict)
|