account_base_service.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. import datetime
  2. import json
  3. import time
  4. import jwt
  5. from django.conf import settings
  6. from django.contrib.auth import authenticate
  7. from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
  8. from django.contrib.auth.hashers import make_password
  9. from django.db.models import Q
  10. from apps.account.models import AppToken, LoonUser, LoonUserRole, LoonDept, LoonRole, LoonUserDept
  11. from service.base_service import BaseService
  12. from service.common.constant_service import constant_service_ins
  13. from service.common.log_service import auto_log
  14. class AccountBaseService(BaseService):
  15. """
  16. account
  17. """
  18. @classmethod
  19. @auto_log
  20. def get_token_by_app_name(cls, app_name: str)->tuple:
  21. """
  22. get app's call token by app_name
  23. :param app_name:
  24. :return:
  25. """
  26. app_token_obj = AppToken.objects.filter(app_name=app_name, is_deleted=0).first()
  27. return True, app_token_obj
  28. @classmethod
  29. @auto_log
  30. def get_user_by_username(cls, username: str)->tuple:
  31. """
  32. get user info by username
  33. :return:
  34. """
  35. result = LoonUser.objects.filter(username=username, is_deleted=0).first()
  36. if result:
  37. return True, result
  38. else:
  39. return False, 'username: {} is not existed or has been deleted'.format(username)
  40. @classmethod
  41. @auto_log
  42. def get_user_list_by_usernames(cls, usernames: list)->tuple:
  43. """
  44. get user info by username
  45. :return:
  46. """
  47. result = LoonUser.objects.filter(username__in=usernames, is_deleted=0).all()
  48. if result:
  49. return True, result
  50. else:
  51. return False, 'usernames: {} is not existed or has been deleted'.format(usernames)
  52. @classmethod
  53. @auto_log
  54. def get_user_by_user_id(cls, user_id: int)->tuple:
  55. """
  56. get user by user id
  57. :param user_id:
  58. :return:
  59. """
  60. result = LoonUser.objects.filter(id=user_id, is_deleted=0).first()
  61. if result:
  62. return True, result
  63. else:
  64. return False, 'user_id: {} is not existed or has been deleted'.format(user_id)
  65. @classmethod
  66. @auto_log
  67. def get_user_name_list_by_id_list(cls, user_id_list: list)->tuple:
  68. """
  69. get username list by user id list
  70. 根据用户id的数组获取用户名的list
  71. :param user_id_list:
  72. :return:
  73. """
  74. user_queryset = LoonUser.objects.filter(id__in=user_id_list, is_deleted=0).all()
  75. if not user_queryset:
  76. return False, 'user id is not existed or has been deleted'
  77. username_list = [user_query.username for user_query in user_queryset]
  78. return True, dict(username_list=username_list)
  79. @classmethod
  80. @auto_log
  81. def get_user_role_id_list(cls, username: str)->tuple:
  82. """
  83. get user's role id list by username
  84. :param username:
  85. :return:
  86. """
  87. user_obj = LoonUser.objects.filter(username=username, is_deleted=0).first()
  88. if not user_obj:
  89. return False, 'user is not existed or has been deleted'
  90. user_role_queryset = LoonUserRole.objects.filter(user_id=user_obj.id, is_deleted=0).all()
  91. user_role_id_list = [user_role.role_id for user_role in user_role_queryset]
  92. return True, user_role_id_list
  93. @classmethod
  94. @auto_log
  95. def get_user_role_info_by_user_id(cls, user_id: int, search_value: str=0, page: int =1, per_page: int=10)->tuple:
  96. """
  97. get user's role info list by user's id and query params: role name、page、per_page
  98. :param user_id:
  99. :param search_value:
  100. :param page:
  101. :param per_page:
  102. :return:
  103. """
  104. user_role_queryset = LoonUserRole.objects.filter(user_id=user_id, is_deleted=0).all()
  105. user_role_id_list = [user_role.role_id for user_role in user_role_queryset]
  106. query_params = Q(is_deleted=False, id__in=user_role_id_list)
  107. if search_value:
  108. query_params &= Q(name__contains=search_value)
  109. role_info_queryset = LoonRole.objects.filter(query_params).all()
  110. paginator = Paginator(role_info_queryset, per_page)
  111. try:
  112. role_info_result_paginator = paginator.page(page)
  113. except PageNotAnInteger:
  114. role_info_result_paginator = paginator.page(1)
  115. except EmptyPage:
  116. # If page is out of range (e.g. 9999), deliver last page of results
  117. role_info_result_paginator = paginator.page(paginator.num_pages)
  118. role_result_list = role_info_result_paginator.object_list
  119. role_result_format_list = []
  120. for role_info in role_result_list:
  121. role_result_format_list.append(dict(id=role_info.id, name=role_info.name, description=role_info.description,
  122. label=json.dumps(role_info.label) if role_info.label else {},
  123. creator=role_info.creator, gmt_created=str(role_info.gmt_created)[:19]))
  124. return True, dict(role_result_format_list=role_result_format_list,
  125. paginator_info=dict(per_page=per_page, page=page, total=paginator.count))
  126. @classmethod
  127. @auto_log
  128. def get_role_user_info_by_role_id(cls, role_id: int, search_value: str='', page: int=1, per_page: int =10)->tuple:
  129. """
  130. get role's user info list by role_id
  131. :param role_id:
  132. :param search_value:
  133. :param page:
  134. :param per_page:
  135. :return:
  136. """
  137. user_role_queryset = LoonUserRole.objects.filter(role_id=role_id, is_deleted=0).all()
  138. role_user_id_list = [user_role.user_id for user_role in user_role_queryset]
  139. query_params = Q(is_deleted=False, id__in=role_user_id_list)
  140. if search_value:
  141. query_params &= Q(username__contains=search_value) | Q(alias__contains=search_value)
  142. user_info_queryset = LoonUser.objects.filter(query_params).all()
  143. paginator = Paginator(user_info_queryset, per_page)
  144. try:
  145. user_info_result_paginator = paginator.page(page)
  146. except PageNotAnInteger:
  147. user_info_result_paginator = paginator.page(1)
  148. except EmptyPage:
  149. # If page is out of range (e.g. 9999), deliver last page of results
  150. user_info_result_paginator = paginator.page(paginator.num_pages)
  151. user_result_list = user_info_result_paginator.object_list
  152. user_result_format_list = []
  153. for user_info in user_result_list:
  154. user_result_format_list.append(user_info.get_dict())
  155. return True, dict(user_result_format_list=user_result_format_list,
  156. paginator_info=dict(per_page=per_page, page=page, total=paginator.count))
  157. @classmethod
  158. @auto_log
  159. def get_user_up_dept_id_list(cls, username: str)->tuple:
  160. """
  161. get user's department id list by username, include parent department
  162. :param username:
  163. :return:
  164. """
  165. dept_id_list = []
  166. user_obj = LoonUser.objects.filter(username=username, is_deleted=0).first()
  167. if not user_obj:
  168. return False, 'user is not existed or has been deleted'
  169. def iter_dept(dept_id):
  170. dept_obj = LoonDept.objects.filter(id=dept_id, is_deleted=0).first()
  171. if dept_obj:
  172. dept_id_list.append(dept_obj.id)
  173. if dept_obj.parent_dept_id:
  174. iter_dept(dept_obj.parent_dept_id)
  175. user_dept_queryset = LoonUserDept.objects.filter(user_id=user_obj.id, is_deleted=0).all()
  176. user_dept_id_list = [user_dept.dept_id for user_dept in user_dept_queryset]
  177. for user_dept_id in user_dept_id_list:
  178. iter_dept(user_dept_id)
  179. dept_id_list = list(set(dept_id_list))
  180. return True, dept_id_list
  181. @classmethod
  182. @auto_log
  183. def get_user_dept_approver(cls, username: str, dept_id: int=0)->tuple:
  184. """
  185. get user's department approver, Preferential access to the approver, without taking tl(team leader)
  186. :param username:
  187. :param dept_id: 用于用户可能属于多个部门的情况
  188. :return:
  189. """
  190. user_obj = LoonUser.objects.filter(username=username, is_deleted=0).first()
  191. if dept_id:
  192. if LoonUserDept.objects.filter(user_id=user_obj.id, dept_id=dept_id, is_deleted=0).first():
  193. loon_dept_obj = LoonDept.objects.filter(id=dept_id).first()
  194. if loon_dept_obj.approver:
  195. return True, loon_dept_obj.approver
  196. else:
  197. return True, loon_dept_obj.leader
  198. else:
  199. return False, 'dept_id is invalid'
  200. else:
  201. # no dept id specified, get all user dept's approver
  202. user_dept_queryset = LoonUserDept.objects.filter(user_id=user_obj.id, is_deleted=0)
  203. approver_list = []
  204. for user_dept in user_dept_queryset:
  205. if user_dept.dept.approver:
  206. approver_list.extend(user_dept.dept.approver.split(','))
  207. else:
  208. approver_list.append(user_dept.dept.leader)
  209. return True, ','.join(list(set(approver_list)))
  210. @classmethod
  211. @auto_log
  212. def get_user_dept_info(cls, username: str='', user_id: int=0)->tuple:
  213. """
  214. get user dept info
  215. :param username:
  216. :param user_id:
  217. :return:
  218. """
  219. if username:
  220. user_obj = LoonUser.objects.filter(username=username, is_deleted=0).first()
  221. user_id = user_obj.id
  222. user_dept_queryset = LoonUserDept.objects.filter(user_id=user_id, is_deleted=0).all()
  223. user_dept_info = {}
  224. user_dept_id_list = []
  225. user_dept_name_list = []
  226. for user_dept in user_dept_queryset:
  227. user_dept_id_list.append(str(user_dept.dept_id))
  228. user_dept_name_list.append(user_dept.dept.name)
  229. user_dept_info['id'] = ','.join(user_dept_id_list)
  230. user_dept_info['name'] = ','.join(user_dept_name_list)
  231. return True, user_dept_info
  232. @classmethod
  233. @auto_log
  234. def get_dept_sub_dept_id_list(cls, dept_id: int)->tuple:
  235. """
  236. get department's all subordinate department
  237. :param dept_id:
  238. :return:
  239. """
  240. dept_id_list = []
  241. dept_obj = LoonDept.objects.filter(id=dept_id, is_deleted=0).first()
  242. if dept_obj:
  243. dept_id_list.append(dept_obj.id)
  244. else:
  245. return True, []
  246. def iter_dept_id_list(new_dept_id):
  247. new_dept_obj = LoonDept.objects.filter(id=new_dept_id, is_deleted=0).first()
  248. if new_dept_obj:
  249. sub_dept_queryset = LoonDept.objects.filter(parent_dept_id=new_dept_obj.id, is_deleted=0).all()
  250. for sub_dept in sub_dept_queryset:
  251. if sub_dept:
  252. dept_id_list.append(sub_dept.id)
  253. iter_dept_id_list(sub_dept.id)
  254. iter_dept_id_list(dept_id)
  255. return True, dept_id_list
  256. @classmethod
  257. @auto_log
  258. def get_dept_username_list(cls, dept_id: object)->tuple:
  259. """
  260. get department's all username list
  261. :param dept_id: int or str
  262. :return:
  263. """
  264. if type(dept_id) == str:
  265. dept_id_str_list = dept_id.split(',') # 用于支持多部门
  266. dept_id_list = [int(dept_id_str) for dept_id_str in dept_id_str_list]
  267. else:
  268. dept_id_list = [dept_id]
  269. sub_dept_id_list_total = []
  270. for dept_id in dept_id_list:
  271. flag, sub_dept_id_list = cls.get_dept_sub_dept_id_list(dept_id)
  272. if flag is False:
  273. return False, sub_dept_id_list
  274. sub_dept_id_list_total = sub_dept_id_list_total + sub_dept_id_list
  275. user_dept_queryset = LoonUserDept.objects.filter(dept_id__in=sub_dept_id_list_total).all()
  276. user_id_list = [user_dept.user_id for user_dept in user_dept_queryset]
  277. user_queryset = LoonUser.objects.filter(id__in=user_id_list).all()
  278. user_name_list = [user.username for user in user_queryset]
  279. return True, user_name_list
  280. @classmethod
  281. @auto_log
  282. def get_role_username_list(cls, role_id: int)->tuple:
  283. """
  284. get role's username list by role_id
  285. :param role_id:
  286. :return:
  287. """
  288. user_role_queryset = LoonUserRole.objects.filter(role_id=role_id, is_deleted=0).all()
  289. user_id_list = []
  290. for user_role in user_role_queryset:
  291. user_id_list.append(user_role.user_id)
  292. if not user_id_list:
  293. return True, []
  294. username_queryset = LoonUser.objects.filter(id__in=user_id_list).all()
  295. username_list = []
  296. for username_obj in username_queryset:
  297. username_list.append(username_obj.username)
  298. return True, username_list
  299. @classmethod
  300. @auto_log
  301. def get_dept_by_id(cls, dept_id: int)->tuple:
  302. """
  303. get department's info by dept_id
  304. :param dept_id:
  305. :return:
  306. """
  307. return True, LoonDept.objects.filter(id=dept_id, is_deleted=False).first()
  308. @classmethod
  309. @auto_log
  310. def get_dept_by_ids(cls, dept_ids: str)->tuple:
  311. """
  312. get department's queryset by dept_ids
  313. :param dept_ids:
  314. :return:
  315. """
  316. if dept_ids:
  317. dept_id_list = dept_ids.split(',')
  318. return True, LoonDept.objects.filter(id__in=dept_id_list, is_deleted=False).all()
  319. @classmethod
  320. @auto_log
  321. def get_role_by_id(cls, role_id: int)->tuple:
  322. """
  323. get role's info by role_id
  324. :param role_id:
  325. :return:
  326. """
  327. return True, LoonRole.objects.filter(id=role_id, is_deleted=False).first()
  328. @classmethod
  329. @auto_log
  330. def app_workflow_permission_list(cls, app_name: str)->tuple:
  331. """
  332. get app's authorised workflow_id list by app_name
  333. :param app_name:
  334. :return:
  335. """
  336. if not app_name:
  337. return False, 'app_name is not provided'
  338. if app_name == 'loonflow':
  339. # loonflow有权限访问所有workflow
  340. from apps.workflow.models import Workflow
  341. workflow_query_set = Workflow.objects.filter(is_deleted=0).all()
  342. workflow_id_list = []
  343. for workflow_obj in workflow_query_set:
  344. workflow_id_list.append(workflow_obj.id)
  345. return True, dict(workflow_id_list=workflow_id_list)
  346. app_token_obj = AppToken.objects.filter(app_name=app_name, is_deleted=0).first()
  347. if not app_token_obj:
  348. return False, 'appname is unauthorized'
  349. @classmethod
  350. @auto_log
  351. def app_workflow_permission_check(cls, app_name: str, workflow_id: int)->tuple:
  352. """
  353. appname has permission for workflow check by app_name and workflow_id
  354. :param app_name:
  355. :param workflow_id:
  356. :return:
  357. """
  358. if app_name == 'loonflow':
  359. return True, ''
  360. from service.workflow.workflow_permission_service import workflow_permission_service_ins
  361. flag, result = workflow_permission_service_ins.get_workflow_id_list_by_permission('api', 'app', app_name)
  362. if flag and result.get('workflow_id_list') and workflow_id in result.get('workflow_id_list'):
  363. return True, ''
  364. else:
  365. return False, 'the app has no permission to the workflow_id'
  366. @classmethod
  367. @auto_log
  368. def app_ticket_permission_check(cls, app_name: str, ticket_id: int)-> tuple:
  369. """
  370. appname has permission to ticket check by app_name and ticket_id
  371. :param app_name:
  372. :param ticket_id:
  373. :return:
  374. """
  375. from service.ticket.ticket_base_service import ticket_base_service_ins
  376. flag, ticket_obj = ticket_base_service_ins.get_ticket_by_id(ticket_id)
  377. if not flag:
  378. return False, ticket_obj
  379. workflow_id = ticket_obj.workflow_id
  380. from service.workflow.workflow_permission_service import workflow_permission_service_ins
  381. permission_check, msg = workflow_permission_service_ins.workflow_id_permission_check(workflow_id, 'api', 'app', app_name)
  382. if not permission_check:
  383. return False, msg
  384. return True, ''
  385. @classmethod
  386. @auto_log
  387. def get_user_list(cls, search_value: str, page: int=1, per_page: int=10, simple=False)->tuple:
  388. """
  389. get user restful info list by query params: search_value, page, per_page
  390. :param search_value: support user's username, and user's alias. fuzzy query
  391. :param page:
  392. :param per_page:
  393. :param simple: 是否只返回简单信息
  394. :return:
  395. """
  396. query_params = Q(is_deleted=False)
  397. if search_value:
  398. query_params &= Q(username__contains=search_value) | Q(alias__contains=search_value)
  399. user_objects = LoonUser.objects.filter(query_params)
  400. paginator = Paginator(user_objects, per_page)
  401. try:
  402. user_result_paginator = paginator.page(page)
  403. except PageNotAnInteger:
  404. user_result_paginator = paginator.page(1)
  405. except EmptyPage:
  406. # If page is out of range (e.g. 9999), deliver last page of results
  407. user_result_paginator = paginator.page(paginator.num_pages)
  408. user_result_object_list = user_result_paginator.object_list
  409. user_result_object_format_list = []
  410. user_id_list = [user_result_object.id for user_result_object in user_result_object_list]
  411. # 获取用户所在部门信息
  412. user_dept_list = LoonUserDept.objects.filter(user_id__in=user_id_list, is_deleted=0)
  413. for user_result_object in user_result_object_list:
  414. user_result_format_dict = user_result_object.get_dict()
  415. # todo 获取部门信息
  416. user_dept_info_list = []
  417. for user_dept in user_dept_list:
  418. if user_result_object.id == user_dept.user_id:
  419. user_dept_info_list.append(
  420. dict(name=user_dept.dept.name, id=user_dept.dept.id))
  421. user_result_format_dict['user_dept_info_list'] = user_dept_info_list
  422. if simple:
  423. # 去除敏感信息
  424. user_result_format_dict.pop('last_login')
  425. user_result_format_dict.pop('email')
  426. user_result_format_dict.pop('creator_info')
  427. user_result_format_dict.pop('phone')
  428. user_result_format_dict.pop('type_id')
  429. user_result_format_dict.pop('gmt_created')
  430. user_result_format_dict.pop('gmt_modified')
  431. user_result_format_dict.pop('is_deleted')
  432. user_result_object_format_list.append(user_result_format_dict)
  433. return True, dict(user_result_object_format_list=user_result_object_format_list,
  434. paginator_info=dict(per_page=per_page, page=page, total=paginator.count))
  435. @classmethod
  436. @auto_log
  437. def add_user(cls, username: str, alias: str, email: str, phone: str, dept_ids: str, is_active: int,
  438. type_id: int, creator: str, password: str='')->tuple:
  439. """
  440. 新增用户, 因为非管理员或者工作流管理员无需登录管理后台,密码字段留空
  441. add user, not support set password, you need reset password
  442. :param username:
  443. :param alias:
  444. :param email:
  445. :param phone:
  446. :param dept_ids: 逗号隔开多个部门
  447. :param is_active:
  448. :param dept_ids:
  449. :param creator:
  450. :param password:
  451. :return:
  452. """
  453. password_str = make_password(password, None, 'pbkdf2_sha256')
  454. user_obj = LoonUser(username=username, alias=alias, email=email, phone=phone,
  455. is_active=is_active, type_id=type_id,
  456. creator=creator, password=password_str)
  457. user_obj.save()
  458. queryset_list = []
  459. for dept_id in dept_ids.split(','):
  460. queryset_list.append(LoonUserDept(user_id=user_obj.id, dept_id=dept_id))
  461. LoonUserDept.objects.bulk_create(queryset_list)
  462. return True, dict(user_id=user_obj.id)
  463. @classmethod
  464. @auto_log
  465. def edit_user(cls, user_id: int, username: str, alias: str, email: str, phone: str, dept_ids: str, is_active: int,
  466. type_id: int)-> tuple:
  467. """
  468. edit user
  469. :param user_id:
  470. :param username:
  471. :param alias:
  472. :param email:
  473. :param phone:
  474. :param dept_ids:
  475. :param is_active:
  476. :param type_id:
  477. :return:
  478. """
  479. user_obj = LoonUser.objects.filter(id=user_id, is_deleted=0)
  480. user_obj.update(username=username, alias=alias, email=email, phone=phone, is_active=is_active,
  481. type_id=type_id)
  482. # todo 更新部门信息
  483. dept_id_str_list = dept_ids.split(',')
  484. dept_id_int_list = [int(dept_id_str) for dept_id_str in dept_id_str_list]
  485. user_id = user_obj.first().id
  486. user_dept_queryset = LoonUserDept.objects.filter(user_id=user_id, is_deleted=0).all()
  487. user_dept_id_exist = [user_dept.dept_id for user_dept in user_dept_queryset]
  488. need_add_list = [dept_id_int for dept_id_int in dept_id_int_list if dept_id_int not in user_dept_id_exist]
  489. need_delete_list = [user_dept_id for user_dept_id in user_dept_id_exist if user_dept_id not in dept_id_int_list]
  490. add_queryset = []
  491. for need_add in need_add_list:
  492. add_queryset.append(LoonUserDept(user_id=user_id, dept_id=need_add))
  493. LoonUserDept.objects.bulk_create(add_queryset)
  494. LoonUserDept.objects.filter(user_id=user_id, dept_id__in=need_delete_list).update(is_deleted=1)
  495. return True, {}
  496. @classmethod
  497. @auto_log
  498. def delete_user(cls, user_id: int)->tuple:
  499. """
  500. delete user
  501. :param user_id:
  502. :return:
  503. """
  504. user_obj = LoonUser.objects.filter(id=user_id, is_deleted=0)
  505. user_obj.update(is_deleted=1)
  506. return True, {}
  507. @classmethod
  508. @auto_log
  509. def get_role_list(cls, search_value: str, page: int=1, per_page: int=10)->tuple:
  510. """
  511. 获取角色列表
  512. get role restful list by search params
  513. :param search_value: role name or role description Support fuzzy queries
  514. :param page:
  515. :param per_page:
  516. :return:
  517. """
  518. query_params = Q(is_deleted=False)
  519. if search_value:
  520. query_params &= Q(name__contains=search_value) | Q(description__contains=search_value)
  521. user_objects = LoonRole.objects.filter(query_params)
  522. paginator = Paginator(user_objects, per_page)
  523. try:
  524. role_result_paginator = paginator.page(page)
  525. except PageNotAnInteger:
  526. role_result_paginator = paginator.page(1)
  527. except EmptyPage:
  528. # If page is out of range (e.g. 9999), deliver last page of results
  529. role_result_paginator = paginator.page(paginator.num_pages)
  530. role_result_object_list = role_result_paginator.object_list
  531. role_result_object_format_list = []
  532. for role_result_object in role_result_object_list:
  533. role_result_object_format_list.append(role_result_object.get_dict())
  534. return True, dict(role_result_object_format_list=role_result_object_format_list,
  535. paginator_info=dict(per_page=per_page, page=page, total=paginator.count))
  536. @classmethod
  537. @auto_log
  538. def add_role(cls, name: str, description: str, label: str, creator: str)->tuple:
  539. """
  540. add role
  541. 新增角色
  542. :param name:
  543. :param description:
  544. :param label:
  545. :param creator:
  546. :return:
  547. """
  548. role_obj = LoonRole(name=name, description=description, label=label, creator=creator)
  549. role_obj.save()
  550. return True, dict(role_id=role_obj.id)
  551. @classmethod
  552. @auto_log
  553. def add_role_user(cls, role_id: int, user_id: int, creator: str)->tuple:
  554. """
  555. add role's user
  556. 新增角色用户
  557. :param role_id:
  558. :param user_id:
  559. :param creator:
  560. :return:
  561. """
  562. # 去重下
  563. role_user_queryset = LoonUserRole.objects.filter(user_id=user_id, role_id=role_id, is_deleted=0)
  564. if role_user_queryset:
  565. return False, 'user has been existed in this role'
  566. role_user_obj = LoonUserRole(user_id=user_id, role_id=role_id, creator=creator)
  567. role_user_obj.save()
  568. return True, dict(role_user_id=role_user_obj.id)
  569. @classmethod
  570. @auto_log
  571. def delete_role_user(cls, user_id: int)->tuple:
  572. """
  573. 删除角色用户
  574. :param user_id:
  575. :return:
  576. """
  577. role_user_obj = LoonUserRole.objects.filter(user_id=user_id, is_deleted=0)
  578. if not role_user_obj:
  579. return False, 'record is not existed or has been deleted'
  580. role_user_obj.update(is_deleted=1)
  581. return True, ''
  582. @classmethod
  583. @auto_log
  584. def update_role(cls, role_id: int, name: str, description: str, label: str)-> tuple:
  585. """
  586. update role
  587. 更新角色
  588. :param role_id:
  589. :param name:
  590. :param description:
  591. :param label:
  592. :return:
  593. """
  594. role_queryset = LoonRole.objects.filter(id=role_id, is_deleted=0)
  595. if not role_queryset:
  596. return False, 'role record is not existed'
  597. role_queryset.update(name=name, description=description, label=label)
  598. return True, {}
  599. @classmethod
  600. @auto_log
  601. def delete_role(cls, role_id: int)->tuple:
  602. """
  603. delete role record
  604. 删除角色
  605. :param role_id:
  606. :return:
  607. """
  608. role_queryset = LoonRole.objects.filter(id=role_id, is_deleted=0)
  609. if not role_queryset:
  610. return False, 'role record is not existed'
  611. role_queryset.update(is_deleted=1)
  612. return True, {}
  613. @classmethod
  614. @auto_log
  615. def get_dept_list(cls, search_value: str, page: int=1, per_page: int=10, simple=False)->tuple:
  616. """
  617. get dept restful list by search params
  618. :param search_value: department name or department description Support fuzzy queries
  619. :param page:
  620. :param per_page:
  621. :param simple: 只返回部分数据
  622. :return:
  623. """
  624. query_params = Q(is_deleted=False)
  625. if search_value:
  626. query_params &= Q(name__contains=search_value) | Q(label__contains=search_value)
  627. dept_objects = LoonDept.objects.filter(query_params)
  628. paginator = Paginator(dept_objects, per_page)
  629. try:
  630. dept_result_paginator = paginator.page(page)
  631. except PageNotAnInteger:
  632. dept_result_paginator = paginator.page(1)
  633. except EmptyPage:
  634. # If page is out of range (e.g. 9999), deliver last page of results
  635. dept_result_paginator = paginator.page(paginator.num_pages)
  636. dept_result_object_list = dept_result_paginator.object_list
  637. dept_result_object_format_list = []
  638. for dept_result_object in dept_result_object_list:
  639. result_dict = dept_result_object.get_dict()
  640. if simple:
  641. simple_result_dict = dict()
  642. simple_result_dict['id'] = result_dict['id']
  643. simple_result_dict['name'] = result_dict['name']
  644. simple_result_dict['parent_dept_info'] = result_dict['parent_dept_info']
  645. dept_result_object_format_list.append(result_dict)
  646. return True, dict(dept_result_object_format_list=dept_result_object_format_list,
  647. paginator_info=dict(per_page=per_page, page=page, total=paginator.count))
  648. @classmethod
  649. @auto_log
  650. def add_dept(cls, name: str, parent_dept_id: int, leader: str, approver: str, label: str, creator: str)->tuple:
  651. """
  652. add department
  653. 新增部门
  654. :param name:
  655. :param parent_dept_id:
  656. :param leader:
  657. :param approver:
  658. :param label:
  659. :param creator:
  660. :return:
  661. """
  662. dept_obj = LoonDept(name=name, parent_dept_id=parent_dept_id, leader=leader, approver=approver, label=label,
  663. creator=creator)
  664. dept_obj.save()
  665. return True, dict(dept_id=dept_obj.id)
  666. @classmethod
  667. @auto_log
  668. def update_dept(cls, dept_id: int, name: str, parent_dept_id: int, leader: str, approver: str, label: str)->tuple:
  669. """
  670. update department record
  671. 更新部门
  672. :param dept_id:
  673. :param name:
  674. :param parent_dept_id:
  675. :param leader:
  676. :param approver:
  677. :param label:
  678. :return:
  679. """
  680. dept_queryset = LoonDept.objects.filter(id=dept_id, is_deleted=0)
  681. if not dept_queryset:
  682. return False, 'dept is not existed or has been deleted'
  683. dept_queryset.update(name=name, parent_dept_id=parent_dept_id, leader=leader, approver=approver, label=label)
  684. return True, ''
  685. @classmethod
  686. @auto_log
  687. def delete_dept(cls, dept_id: int)-> tuple:
  688. """
  689. delete department record
  690. :param dept_id:
  691. :return:
  692. """
  693. dept_queryset = LoonDept.objects.filter(id=dept_id, is_deleted=0)
  694. if not dept_queryset:
  695. return False, 'dept is not existed or has been deleted'
  696. dept_queryset.update(is_deleted=1)
  697. return True, ''
  698. @classmethod
  699. @auto_log
  700. def get_token_list(cls, search_value: str, page: int=1, per_page: int=10, simple=False)->tuple:
  701. """
  702. get app permission token list
  703. :param search_value: support app name fuzzy queries
  704. :param page:
  705. :param per_page:
  706. :param simple: 返回简易数据,排除敏感信息
  707. :return:
  708. """
  709. query_params = Q(is_deleted=False)
  710. if search_value:
  711. query_params &= Q(app_name__contains=search_value)
  712. token_objects = AppToken.objects.filter(query_params)
  713. paginator = Paginator(token_objects, per_page)
  714. try:
  715. token_result_paginator = paginator.page(page)
  716. except PageNotAnInteger:
  717. token_result_paginator = paginator.page(1)
  718. except EmptyPage:
  719. # If page is out of range (e.g. 9999), deliver last page of results
  720. token_result_paginator = paginator.page(paginator.num_pages)
  721. token_result_object_list = token_result_paginator.object_list
  722. token_result_object_format_list = []
  723. for token_result_object in token_result_object_list:
  724. app_list = [token_result_object.app_name for token_result_object in token_result_object_list]
  725. # todo: get token permission workflow list
  726. from service.workflow.workflow_permission_service import workflow_permission_service_ins
  727. flag, result = workflow_permission_service_ins.get_record_list_by_app_list(app_list)
  728. permission_list = result.get('permission_query_set')
  729. token_result_data = token_result_object.get_dict()
  730. token_workflow_list = []
  731. if simple:
  732. token_result_data.pop('token')
  733. else:
  734. for permission in permission_list:
  735. if permission.user == token_result_data.get('app_name'):
  736. token_workflow_list.append(str(permission.workflow_id))
  737. token_result_data['workflow_ids'] = ','.join(token_workflow_list)
  738. token_result_object_format_list.append(token_result_data)
  739. return True, dict(token_result_object_format_list=token_result_object_format_list,
  740. paginator_info=dict(per_page=per_page, page=page, total=paginator.count))
  741. @classmethod
  742. @auto_log
  743. def add_token_record(cls, app_name: str, ticket_sn_prefix: str, workflow_ids: str, username: str)-> tuple:
  744. """
  745. add app token record
  746. :param app_name:
  747. :param ticket_sn_prefix:
  748. :param workflow_ids:
  749. :param username:
  750. :return:
  751. """
  752. import uuid
  753. token = uuid.uuid1()
  754. query_result = AppToken.objects.filter(app_name=app_name, is_deleted=0)
  755. if query_result:
  756. return False, 'app_name existed,please alter app_name'
  757. app_token_obj = AppToken(app_name=app_name, ticket_sn_prefix=ticket_sn_prefix,
  758. token=token, creator=username)
  759. app_token_obj.save()
  760. from apps.workflow.models import WorkflowUserPermission
  761. permission_sql_list = []
  762. if workflow_ids:
  763. for workflow_id in workflow_ids.split(','):
  764. permission_sql_list.append(WorkflowUserPermission(workflow_id=int(workflow_id), permission='api', user_type='app', user=app_name))
  765. WorkflowUserPermission.objects.bulk_create(permission_sql_list)
  766. return True, dict(app_token_id=app_token_obj.id)
  767. @classmethod
  768. @auto_log
  769. def update_token_record(cls, app_token_id: int, ticket_sn_prefix: str, workflow_ids: str)->tuple:
  770. """
  771. update token record
  772. :param app_token_id:
  773. :param ticket_sn_prefix:
  774. :param workflow_ids:
  775. :return:
  776. """
  777. app_token_obj = AppToken.objects.filter(id=app_token_id, is_deleted=0).first()
  778. if not app_token_obj:
  779. return False, 'record is not exist or has been deleted'
  780. app_token_obj.ticket_sn_prefix = ticket_sn_prefix
  781. app_token_obj.save()
  782. from service.workflow.workflow_permission_service import workflow_permission_service_ins
  783. workflow_permission_service_ins.update_app_permission(app_token_obj.app_name, workflow_ids)
  784. return True, ''
  785. @classmethod
  786. @auto_log
  787. def del_token_record(cls, app_token_id: int)->tuple:
  788. """
  789. del app token record
  790. :param app_token_id:
  791. :return:
  792. """
  793. app_token_obj = AppToken.objects.filter(id=app_token_id, is_deleted=0).first()
  794. if not app_token_obj:
  795. return False, 'record is not exist or has been deleted'
  796. app_token_obj.is_deleted = True
  797. app_token_obj.save()
  798. from service.workflow.workflow_permission_service import workflow_permission_service_ins
  799. workflow_permission_service_ins.del_app_permission(app_token_obj.app_name)
  800. return True, ''
  801. @classmethod
  802. @auto_log
  803. def admin_permission_check(cls, username: str='', user_id: int=0)->tuple:
  804. """
  805. admin permission check
  806. :param username:
  807. :param user_id:
  808. :return:
  809. """
  810. if username:
  811. flag, result = cls.get_user_by_username(username)
  812. elif user_id:
  813. flag, result = cls.get_user_by_user_id(user_id)
  814. else:
  815. return False, 'username or user_id is needed'
  816. if flag is False:
  817. return False, result
  818. if result.type_id == constant_service_ins.ACCOUNT_TYPE_SUPER_ADMIN:
  819. return True, 'user is admin'
  820. else:
  821. return False, 'user is not admin'
  822. @classmethod
  823. @auto_log
  824. def workflow_admin_permission_check(cls, username: str='', user_id: int=0)->tuple:
  825. """
  826. workflow admin permission check
  827. :param username:
  828. :param user_id:
  829. :return:
  830. """
  831. if username:
  832. flag, result = cls.get_user_by_username(username)
  833. elif user_id:
  834. flag, result = cls.get_user_by_username(username)
  835. else:
  836. return False, 'username or user_id is needed'
  837. if flag is False:
  838. return False, result
  839. if result.type_id == constant_service_ins.ACCOUNT_TYPE_WORKFLOW_ADMIN:
  840. return True, 'user is workflow admin'
  841. if result.type_id == constant_service_ins.ACCOUNT_TYPE_SUPER_ADMIN:
  842. return True, 'user is admin'
  843. else:
  844. return False, 'user is not admin or workflow admin'
  845. @classmethod
  846. @auto_log
  847. def admin_or_workflow_admin_check(cls, username: str='', user_id: int=0)-> tuple:
  848. """
  849. admin or workflow admin check
  850. :param username:
  851. :param user_id:
  852. :return:
  853. """
  854. if username:
  855. flag, result = cls.get_user_by_username(username)
  856. elif user_id:
  857. flag, result = cls.get_user_by_username(username)
  858. else:
  859. return False, 'username or user_id is needed'
  860. if flag is False:
  861. return False, result
  862. if result.type_id in (constant_service_ins.ACCOUNT_TYPE_SUPER_ADMIN, constant_service_ins.ACCOUNT_TYPE_WORKFLOW_ADMIN):
  863. return True, 'user is admin or workflow admin'
  864. else:
  865. return False, 'user is not admin or workflow admin'
  866. @classmethod
  867. @auto_log
  868. def reset_password(cls, username: str='', user_id: int=0)-> tuple:
  869. """
  870. reset user's password
  871. just admin or workflow admin need login loonflow's admin,so just admin and workflow admin can rest password
  872. :param username:
  873. :param user_id:
  874. :return:
  875. """
  876. flag, result = False, ''
  877. if username:
  878. flag, result = cls.get_user_by_username(username)
  879. if user_id:
  880. flag, result = cls.get_user_by_user_id(user_id)
  881. if flag:
  882. user_obj = result
  883. # if user_obj.type_id in (constant_service_ins.ACCOUNT_TYPE_SUPER_ADMIN, constant_service_ins.ACCOUNT_TYPE_WORKFLOW_ADMIN):
  884. password_str = make_password('123456', None, 'pbkdf2_sha256')
  885. user_obj.password = password_str
  886. user_obj.save()
  887. return True, 'password has been reset to 123456'
  888. # else:
  889. # return False, 'just admin or workflow admin can be reset password'
  890. else:
  891. return False, result
  892. @classmethod
  893. @auto_log
  894. def get_user_jwt(cls, username: str)->tuple:
  895. """
  896. get user's jwt
  897. :param username:
  898. :return:
  899. """
  900. flag, user_obj = cls.get_user_by_username(username)
  901. if flag is False:
  902. return False, user_obj
  903. user_info = user_obj.get_dict()
  904. timestamp = int(time.time())
  905. jwt_salt = settings.JWT_SALT
  906. jwt_info = jwt.encode(
  907. {
  908. 'exp': datetime.datetime.now() + datetime.timedelta(hours=24),
  909. 'iat': datetime.datetime.now(),
  910. 'data': user_info}, jwt_salt, algorithm='HS256')
  911. return True, jwt_info
  912. @classmethod
  913. @auto_log
  914. def change_password(cls, username: str, source_password: str, new_password: str)->tuple:
  915. """
  916. 修改密码
  917. :param username:
  918. :param source_password:
  919. :param new_password:
  920. :return:
  921. """
  922. flag, user_obj = cls.get_user_by_username(username)
  923. if flag is False:
  924. return False, user_obj
  925. user = authenticate(username=username, password=source_password)
  926. if user is None:
  927. return False, '原密码输入错误,不允许修改密码'
  928. new_password_format = make_password(new_password, None, 'pbkdf2_sha256')
  929. user_obj.password = new_password_format
  930. user_obj.save()
  931. return True, '密码修改成功'
  932. account_base_service_ins = AccountBaseService()