简单阐述一下,我的导入系统在3个位置与Hub(权限系统)进行了交互: 登录、导入、登出。
First——op_login(登录)
? ? ? ?在导入系统登录的时候,会调用到对应的url:
# Create your views here.
# 登录界面
@csrf_exempt
def op_login(request):
logobj = Logger(APP_LOG_PATH + 'cus_auth.log', logging.ERROR, logging.DEBUG)
logobj.info('METHOD op_login START')
if request.method == "POST":
try:
request_body = byteify(json.loads(request.body))
print request_body
# 用户名、密码、部门
username = request_body.get('username', '')
password = request_body.get('password', '')
department = request_body.get('department', '')
logobj.info('<op_login>: 正在验证{}的{}...'.format(department, username))
# 进行验证(判断)
user = authenticate(username=username,
password=password,
userprofile__department= department)
# 如果用户 authenticate成功的话
if user is not None:
# user是激活状态的话
if user.is_active:
# login 1
login(request, user)
# login 2
user.userprofile.is_login = True
user.userprofile.save()
# userprofile---这个数据表中 含有相关的secret_level_id(每一个用户也对应这相应的密级) 以及 user_id、department、is_login(是否登录状态)
logobj.info('<op_login>: 用户{}登录成功'.format(user.username.encode("utf-8")))
response = HttpResponse(
json.dumps({'code': '2',
'info': u'Login successfully',
'url': '/ExperimentList',
'secret_level': user.userprofile.secret_level.name}), status=200)
logobj.close()
return response
# user是一个未激活的状态:is_active=Flase
else:
logobj.war('<op_login>: 用户{}没有被激活'.format(user.username.encode("utf-8")))
logobj.close()
return HttpResponse(json.dumps({'code': '-5', 'info': u'User not be active'}), status=503)
# else:用户authenticate失败的话
else:
logobj.war('<op_login>: 认证失败, 用户名或密码错误')
logobj.close()
return HttpResponse(json.dumps({'code': '-4', 'info': u'Username or Password is wrong'}), status=503)
except Exception, e:
logobj.error('<op_login>: 登录失败,错误信息为{}'.format(str(e)))
# logobj.error('<op_login>: {}'.format(e.message))
logobj.close()
return HttpResponse(json.dumps({'code': '0', 'info': e.message}), status=503)
logobj.close()
return HttpResponseBadRequest
?在上述代码中,有一个login(request,user)方法,如下
Second——导入(dataImport):
@_decorator_login_verification()
@csrf_exempt
# 将任务的权限分配给提交它的所有者:assign the permissions of task to its owner who submits it
def op_authorization_task_permissions(request):
logobj = Logger("{}{}/{}".format(APP_LOG_PATH,
"{}-{}".format(str(request.user.id), request.user.username.encode("utf-8")),
'cus_auth.log'), logging.ERROR, logging.DEBUG)
logobj.info('METHOD <op_authorization_task_permissions> START')
# 导入数据的user
user = request.user
# 新建一个[]用来存相关的表:1、data_info(Data_info); 2、perm_ins(Permission)
rollback_del = []
# POST过来请求
if request.method == 'POST':
try:
logobj.info('<op_authorization_task_permissions>: 从request中获取相关信息...')
request_body = byteify(json.loads(request.body))
kernel = lambda x: request_body.get(x, None)
params = {name: kernel(name) for name in [
'task_id',
'secret_level',
'data_type',
'table_name',
]}
if any(map(lambda x: x is None or x is "", params.values())):
logobj.war('<op_authorization_task_permissions>: Task_id或secret_level或data_type或table_name为null')
logobj.close()
return HttpResponse(json.dumps({
'code': '-6',
'info': u'Task_id or secret_level or data_type or table_name is null'}),
status=503)
# 初始化Task_permission表:init the Task_permissions table
with transaction.atomic():
logobj.info('<op_authorization_task_permissions>: 初始化Data_info表')
data_info = Data_info.objects.get_or_create(task_id=params['task_id'],
secret_level=SecretLevel.objects.get(name=params['secret_level']),
data_type=params['data_type'],
table_name=params['table_name'])[0]
rollback_del.append(data_info)
# 为任务添加新的permissions:add the new permissions for task
logobj.info('<op_authorization_task_permissions>: 为{}:{}添加新的权限...'.format(params['table_name'], params['task_id']))
from __init__ import _data_basic_permissions_list, _data_extend_permissions_list
content_type = ContentType.objects.get(app_label='data', model='manage')
# _data_permissions_list:【读、写、授权(grant)】 ------{'name': 'can grant {} data', 'perm': 'data.grant_{}'}
_data_permissions_list = _data_basic_permissions_list + _data_extend_permissions_list
for permission in _data_permissions_list:
perm_ins = Permission.objects.get_or_create(codename=permission['perm'].split(".")[1].format('data{}'.format(str(data_info.id))),
name=permission['name'].format('data{}'.format(str(data_info.id))),
content_type=content_type)[0]
rollback_del.append(perm_ins)
user.user_permissions.add(perm_ins)
# 增加user与任务的关系:add the relationship between user and task
logobj.info('<op_authorization_task_permissions>: 增加{}与{}:{}之间的关联关系...'.format(user.username, params['table_name'], params['task_id']))
User_data_info.objects.get_or_create(user=user, data=data_info)
# 增加admin与任务之间的联系
logobj.info(
'<op_authorization_task_permissions>: 增加admin与{}:{}之间的关联关系...'.format(params['table_name'], params['task_id']))
admin = User.objects.get(is_superuser=True)
# User_data_info表
User_data_info.objects.get_or_create(user=admin, data=data_info)
# 增加"user"与{table_name}:{task_id}之间的关联关系(IN ORACLE)...
logobj.info(
'<op_authorization_task_permissions>: 增加{}与{}:{}之间的关联关系(IN ORACLE)...'.format(user.username, params['table_name'], params['task_id']))
from cus_auth_extension.views import _action_add_relation
_action_add_relation(user_id=user.id,
task_id=params['task_id'],
table_name=params['table_name'])
# 增加"admin"与{table_name}:{task_id}之间的关联关系(IN ORACLE)...
logobj.info(
'<op_authorization_task_permissions>: 增加admin与{}之间的关联关系(IN ORACLE)...'.format(params['task_id']))
_action_add_relation(user_id=admin.id,
task_id=params['task_id'],
table_name=params['table_name'])
rollback_del = []
logobj.info('<op_authorization_task_permissions>: 授权成功')
logobj.close()
return HttpResponse(json.dumps({'code': '4', 'info': u'Authorization successfully'}), status=200)
except Exception, e:
print e
logobj.error('<op_authorization_task_permissions>: METHOD <op_authorization_task_permissions>失败')
logobj.error('<op_authorization_task_permissions>: {}'.format(str(e)))
logobj.info('<op_authorization_task_permissions>: 开始回滚...')
for item in rollback_del:
user.user_permissions.remove(item)
item.delete()
logobj.info('<op_authorization_task_permissions>: 回滚成功')
logobj.close()
return HttpResponse(json.dumps({'code': '0', 'info': e.message}), status=503)
logobj.war('<op_authorization_task_permissions>: request的方法必须为POST, 但是只获得{}'.format(request.method))
logobj.close()
return HttpResponseBadRequest
在op_authorization_task_permissions这个函数中byteify函数:
?
Last——logout(登出):
@_decorator_login_verification()
@csrf_exempt
# 登出界面
def op_logout(request):
try:
# 将is_login属性设置为False,显示user是未登录状态的(都在userprofile这个表里显示)
request.user.userprofile.is_login = False
request.user.userprofile.save()
logout(request)
return HttpResponse(json.dumps({'code': '3', 'info': 'Logout successfully'
, 'url': '/index'}), status=200)
except Exception, e:
print e.message
return HttpResponse(json.dumps({'code': '0', 'info': e.message}), status=503)
补充:权限系统中表结构关系:
●User表:(userprofile表的外键user_id)
?●secretlevel表(密级---userprofile、datainfo的外键)
?●userprofile表:
●data_info表:
?●content_type表:追踪项目中所有app和model的对应关系,并记录在ContentType表中
Django之ContentType详解_aaronthon的博客-CSDN博客
●Permission表:(权限)
?●user_data_info:增加user与任务的关系(可以是普通用户,也可以是admin)
//增加{user.name}与{table_name} : {task_id}之间的关联关系
??
至于这个,是在Oracle层面上进行的关联,至此“授权成功”!!!
# 增加"user"与{table_name}:{task_id}之间的关联关系(IN ORACLE)...
logobj.info(
'<op_authorization_task_permissions>: 增加{}与{}:{}之间的关联关系(IN ORACLE)...'.format(user.username, params['table_name'], params['task_id']))
from cus_auth_extension.views import _action_add_relation
_action_add_relation(user_id=user.id,
task_id=params['task_id'],
table_name=params['table_name'])
# 增加"admin"与{table_name}:{task_id}之间的关联关系(IN ORACLE)...
logobj.info(
'<op_authorization_task_permissions>: 增加admin与{}之间的关联关系(IN ORACLE)...'.format(params['task_id']))
_action_add_relation(user_id=admin.id,
task_id=params['task_id'],
table_name=params['table_name'])
|