def test_repo_perm_in_structure(repo, permission): id1 = ccnet_api.create_group('group1', USER, parent_group_id=-1) id2 = ccnet_api.create_group('group2', USER, parent_group_id=id1) assert id1 != -1 and id2 != -1 assert ccnet_api.group_add_member(id2, USER, USER2) != -1 assert api.group_share_repo(repo.id, id1, USER2, permission) != -1 assert api.check_permission(repo.id, USER2) == permission assert api.group_unshare_repo(repo.id, id1, USER2) != -1 assert api.check_permission(repo.id, USER2) == None assert ccnet_api.remove_group(id2) != -1 assert ccnet_api.remove_group(id1) != -1
def post(self, request): """ Create a group Permission checking: 1. Admin user; """ # argument check group_name = request.data.get('group_name', '') if not group_name: error_msg = 'group_name %s invalid.' % group_name return api_error(status.HTTP_400_BAD_REQUEST, error_msg) group_name = group_name.strip() # Check whether group name is validate. if not validate_group_name(group_name): error_msg = _( u'Group name can only contain letters, numbers, blank, hyphen, dot, single quote or underscore' ) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is duplicated. if check_group_name_conflict(request, group_name): error_msg = _(u'There is already a group with that name.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) group_owner = request.data.get('group_owner', '') if group_owner: try: User.objects.get(email=group_owner) except User.DoesNotExist: error_msg = 'User %s not found.' % group_owner return api_error(status.HTTP_404_NOT_FOUND, error_msg) username = request.user.username new_owner = group_owner or username # create group. try: group_id = ccnet_api.create_group(group_name, new_owner) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # send admin operation log signal admin_op_detail = { "id": group_id, "name": group_name, "owner": new_owner, } admin_operation.send(sender=None, admin_name=username, operation=GROUP_CREATE, detail=admin_op_detail) # get info of new group group_info = get_group_info(group_id) return Response(group_info, status=status.HTTP_201_CREATED)
def post(self, request): """Add a group in address book. parent_group: -1 - no parent group; > 0 - have parent group. group_owner: default to system admin group_staff: default to system admin """ group_name = request.data.get('group_name', '').strip() if not group_name: error_msg = 'name %s invalid.' % group_name return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is validate. if not validate_group_name(group_name): error_msg = _('Name can only contain letters, numbers, blank, hyphen or underscore.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is duplicated. pattern_matched_groups = ccnet_api.search_groups(group_name, -1, -1) for group in pattern_matched_groups: if group.group_name == group_name: error_msg = _('There is already a group with that name.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Group owner is 'system admin' group_owner = request.data.get('group_owner', '') try: parent_group = int(request.data.get('parent_group', -1)) except ValueError: error_msg = 'parent_group invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if parent_group < 0 and parent_group != -1: error_msg = 'parent_group invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # TODO: check parent group exists try: if is_org_context(request): # request called by org admin org_id = request.user.org.org_id group_id = ccnet_api.create_org_group( org_id, group_name, group_owner, parent_group_id=parent_group) else: group_id = ccnet_api.create_group(group_name, group_owner, parent_group_id=parent_group) seafile_api.set_group_quota(group_id, -2) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # get info of new group group_info = address_book_group_to_dict(group_id) return Response(group_info, status=status.HTTP_200_OK)
def test_can_clean_department_repo_trash(self): if not LOCAL_PRO_DEV_ENV: return # create a department group_id = ccnet_api.create_group('department_test', 'system admin', parent_group_id=-1) seafile_api.set_group_quota(group_id, -2) repo_id = seafile_api.add_group_owned_repo(group_id, 'dep_test', 'rw') repo_owner = seafile_api.get_repo_owner(repo_id) assert '@seafile_group' in repo_owner group_repos = seafile_api.get_repos_by_group(group_id) assert len(group_repos) == 1 group = ccnet_api.get_group(group_id) # department add user ccnet_api.group_add_member(group_id, group.creator_name, self.user_name) ccnet_api.group_add_member(group_id, group.creator_name, self.tmp_user.username) ccnet_api.group_set_admin(group_id, self.user_name) ccnet_api.group_unset_admin(group_id, self.tmp_user.username) assert is_group_admin(group_id, self.user_name) assert not is_group_admin(group_id, self.tmp_user.username) file_name = 'dep_test.txt' self.create_file(repo_id=repo_id, parent_dir='/', filename=file_name, username=self.user_name) # delete a file first seafile_api.del_file(repo_id, '/', file_name, self.user_name) # get trash item count self.login_as(self.user) resp = self.client.get(reverse('api-v2.1-repo-trash', args=[repo_id])) json_resp = json.loads(resp.content) assert len(json_resp['data']) > 0 # department member can not clean trash self.logout() self.login_as(self.tmp_user) resp = self.client.delete(self.url) self.assertEqual(403, resp.status_code) # department admin can clean library trash self.logout() self.login_as(self.user) ccnet_api.group_set_admin(group_id, self.user_name) resp = self.client.delete(self.url) self.assertEqual(200, resp.status_code) # get trash item count again resp = self.client.get(self.url) json_resp = json.loads(resp.content) assert len(json_resp['data']) == 0
def post(self, request): """Add a group in address book. parent_group: -1 - no parent group; > 0 - have parent group. group_owner: default to system admin group_staff: default to system admin """ group_name = request.data.get('group_name', '').strip() if not group_name: error_msg = 'name %s invalid.' % group_name return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is validate. if not validate_group_name(group_name): error_msg = _(u'Name can only contain letters, numbers, blank, hyphen or underscore.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is duplicated. if check_group_name_conflict(request, group_name): error_msg = _(u'The name already exists.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Group owner is 'system admin' group_owner = request.data.get('group_owner', '') try: parent_group = int(request.data.get('parent_group', -1)) except ValueError: error_msg = 'parent_group invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if parent_group < 0 and parent_group != -1: error_msg = 'parent_group invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # TODO: check parent group exists try: if is_org_context(request): # request called by org admin org_id = request.user.org.org_id group_id = ccnet_api.create_org_group( org_id, group_name, group_owner, parent_group_id=parent_group) else: group_id = ccnet_api.create_group(group_name, group_owner, parent_group_id=parent_group) seafile_api.set_group_quota(group_id, -2) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # get info of new group group_info = address_book_group_to_dict(group_id) return Response(group_info, status=status.HTTP_200_OK)
def post(self, request): """ Create a group Permission checking: 1. Admin user; """ # argument check group_name = request.data.get('group_name', '') if not group_name: error_msg = 'group_name %s invalid.' % group_name return api_error(status.HTTP_400_BAD_REQUEST, error_msg) group_name = group_name.strip() # Check whether group name is validate. if not validate_group_name(group_name): error_msg = _(u'Group name can only contain letters, numbers, blank, hyphen, single quote or underscore') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is duplicated. if check_group_name_conflict(request, group_name): error_msg = _(u'There is already a group with that name.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) group_owner = request.data.get('group_owner', '') if group_owner: try: User.objects.get(email=group_owner) except User.DoesNotExist: error_msg = 'User %s not found.' % group_owner return api_error(status.HTTP_404_NOT_FOUND, error_msg) username = request.user.username new_owner = group_owner or username # create group. try: group_id = ccnet_api.create_group(group_name, new_owner) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # send admin operation log signal admin_op_detail = { "id": group_id, "name": group_name, "owner": new_owner, } admin_operation.send(sender=None, admin_name=username, operation=GROUP_CREATE, detail=admin_op_detail) # get info of new group group_info = get_group_info(group_id) return Response(group_info, status=status.HTTP_201_CREATED)
def test_cannot_delete_group_with_child(self): if not LOCAL_PRO_DEV_ENV: return child_group_id = ccnet_api.create_group('child group xxx', self.user.username, parent_group_id=self.top_group_id) resp = self.client.delete(self.url) self.assertEqual(400, resp.status_code) self.remove_group(child_group_id)
def test_share_with_not_group_member(self): tmp_group_id = ccnet_api.create_group(randstring(10), self.admin_name) self.login_as(self.user) data = { 'operation': 'share', 'share_type': 'group', 'group_id': tmp_group_id, 'repo_id': [self.repo_id] } resp = self.client.post(self.url, data) self.assertEqual(403, resp.status_code)
def setUp(self): if not LOCAL_PRO_DEV_ENV: return self.user_name = self.user.username self.admin_name = self.admin.username group_name = 'top group xxx' self.top_group_id = ccnet_api.create_group(group_name, self.admin_name, parent_group_id=-1) self.login_as(self.admin) self.url = reverse('api-v2.1-admin-address-book-group', args=[self.top_group_id])
def test_cannot_delete_group_with_child(self): if not LOCAL_PRO_DEV_ENV: return child_group_id = ccnet_api.create_group( 'child group xxx', self.user.username, parent_group_id=self.top_group_id) resp = self.client.delete(self.url) self.assertEqual(400, resp.status_code) self.remove_group(child_group_id)
def test_can_list_top_groups(self): if not LOCAL_PRO_DEV_ENV: return top_group_id = ccnet_api.create_group('top group xxx', self.user.username, parent_group_id=-1) resp = self.client.get(self.url) self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert len(json_resp['data']) >= 1 self.remove_group(top_group_id)
def test_can_list_child_groups(self): if not LOCAL_PRO_DEV_ENV: return child_group_id = ccnet_api.create_group('child group xxx', self.user.username, parent_group_id=self.top_group_id) resp = self.client.get(self.url) self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert len(json_resp['groups']) >= 1 assert len(json_resp['members']) >= 1 assert len(json_resp['ancestor_groups']) == 0 assert json_resp['id'] == self.top_group_id self.remove_group(child_group_id)
def test_can_ancestor_groups(self): if not LOCAL_PRO_DEV_ENV: return child_group_id = ccnet_api.create_group('child group xxx', self.user.username, parent_group_id=self.top_group_id) url = reverse('api-v2.1-admin-address-book-group', args=[child_group_id]) + '?return_ancestors=true' resp = self.client.get(url) self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert len(json_resp['groups']) == 0 assert len(json_resp['ancestor_groups']) >= 1 assert json_resp['ancestor_groups'][-1]['id'] == self.top_group_id self.remove_group(child_group_id)
def test_can_list_child_groups(self): if not LOCAL_PRO_DEV_ENV: return child_group_id = ccnet_api.create_group( 'child group xxx', self.user.username, parent_group_id=self.top_group_id) resp = self.client.get(self.url) self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert len(json_resp['groups']) >= 1 assert len(json_resp['members']) >= 1 assert len(json_resp['ancestor_groups']) == 0 assert json_resp['id'] == self.top_group_id self.remove_group(child_group_id)
def test_can_set_department_repo(self): if not LOCAL_PRO_DEV_ENV: return # create a department group_id = ccnet_api.create_group('department_test', 'system admin', parent_group_id=-1) seafile_api.set_group_quota(group_id, -2) repo_id = seafile_api.add_group_owned_repo(group_id, 'dep_test', 'rw') repo_owner = seafile_api.get_repo_owner(repo_id) assert '@seafile_group' in repo_owner group_repos = seafile_api.get_repos_by_group(group_id) assert len(group_repos) == 1 group = ccnet_api.get_group(group_id) # department add user ccnet_api.group_add_member(group_id, group.creator_name, self.user.username) ccnet_api.group_add_member(group_id, group.creator_name, self.tmp_user.username) ccnet_api.group_set_admin(group_id, self.user.username) ccnet_api.group_unset_admin(group_id, self.tmp_user.username) assert is_group_admin(group_id, self.user.username) assert not is_group_admin(group_id, self.tmp_user.username) url = reverse("api2-repo-history-limit", args=[repo_id]) self.config.ENABLE_REPO_HISTORY_SETTING = True # department member can not set self.logout() self.login_as(self.tmp_user) data = 'keep_days=%s' % 6 resp = self.client.put(url, data, 'application/x-www-form-urlencoded') self.assertEqual(403, resp.status_code) # department admin can set self.logout() self.login_as(self.user) data = 'keep_days=%s' % 6 resp = self.client.put(url, data, 'application/x-www-form-urlencoded') self.assertEqual(200, resp.status_code) self.remove_group(group_id) self.remove_repo(repo_id)
def test_can_ancestor_groups(self): if not LOCAL_PRO_DEV_ENV: return child_group_id = ccnet_api.create_group( 'child group xxx', self.user.username, parent_group_id=self.top_group_id) url = reverse('api-v2.1-admin-address-book-group', args=[child_group_id]) + '?return_ancestors=true' resp = self.client.get(url) self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert len(json_resp['groups']) == 0 assert len(json_resp['ancestor_groups']) >= 1 assert json_resp['ancestor_groups'][-1]['id'] == self.top_group_id self.remove_group(child_group_id)
def test_can_create_child_group(self): if not LOCAL_PRO_DEV_ENV: return top_group_id = ccnet_api.create_group('top group xxx', self.user.username, parent_group_id=-1) resp = self.client.post(self.url, { 'group_name': randstring(10), 'parent_group': top_group_id, 'group_owner': self.user.username }) self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert len(json_resp['name']) == 10 assert json_resp['parent_group_id'] == top_group_id self.remove_group(json_resp['id']) self.remove_group(top_group_id)
def post(self, request): """ Create a group """ if not self._can_add_group(request): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) username = request.user.username group_name = request.data.get('name', '') group_name = group_name.strip() # Check whether group name is validate. if not validate_group_name(group_name): error_msg = _( 'Name can only contain letters, numbers, spaces, hyphen, dot, single quote, brackets or underscore.' ) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is duplicated. if check_group_name_conflict(request, group_name): error_msg = _('There is already a group with that name.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # create group. try: if is_org_context(request): org_id = request.user.org.org_id group_id = ccnet_api.create_org_group(org_id, group_name, username) else: group_id = ccnet_api.create_group(group_name, username) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # get info of new group group_info = get_group_info(request, group_id) return Response(group_info, status=status.HTTP_201_CREATED)
def test_can_create_child_group(self): if not LOCAL_PRO_DEV_ENV: return top_group_id = ccnet_api.create_group('top group xxx', self.user.username, parent_group_id=-1) resp = self.client.post( self.url, { 'group_name': randstring(10), 'parent_group': top_group_id, 'group_owner': self.user.username }) self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert len(json_resp['name']) == 10 assert json_resp['parent_group_id'] == top_group_id self.remove_group(json_resp['id']) self.remove_group(top_group_id)
def post(self, request): """import department from dingtalk """ if not ENABLE_DINGTALK: error_msg = 'Feature is not enabled.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if not request.user.admin_permissions.can_manage_user(): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') # argument check department_id = request.data.get('department_id') try: department_id = int(department_id) except Exception as e: logger.error(e) error_msg = 'department_id invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) access_token = dingtalk_get_access_token() if not access_token: error_msg = '获取钉钉组织架构失败' return api_error(status.HTTP_404_NOT_FOUND, error_msg) # get department list # https://developers.dingtalk.com/document/app/obtain-the-department-list data = {'access_token': access_token, 'id': department_id} current_department_resp_json = requests.get(DINGTALK_DEPARTMENT_GET_DEPARTMENT_URL, params=data).json() current_department_list = [current_department_resp_json] sub_department_resp_json = requests.get(DINGTALK_DEPARTMENT_LIST_DEPARTMENT_URL, params=data).json() sub_department_list = sub_department_resp_json.get('department', []) department_list = current_department_list + sub_department_list department_list = sorted(department_list, key=lambda x:x['id']) # get department user list data = { 'access_token': access_token, 'department_id': department_id, 'offset': 0, 'size': DINGTALK_DEPARTMENT_USER_SIZE, } user_resp_json = requests.get(DINGTALK_DEPARTMENT_GET_DEPARTMENT_USER_LIST_URL, params=data).json() api_user_list = user_resp_json.get('userlist', []) # main success = list() failed = list() department_map_to_group_dict = dict() for index, department_obj in enumerate(department_list): # check department argument new_group_name = department_obj.get('name') department_obj_id = department_obj.get('id') parent_department_id = department_obj.get('parentid', 0) if department_obj_id is None or not new_group_name or not validate_group_name(new_group_name): failed_msg = self._api_department_failed_msg( department_obj_id, new_group_name, '部门参数错误') failed.append(failed_msg) continue # check parent group if index == 0: parent_group_id = -1 else: parent_group_id = department_map_to_group_dict.get(parent_department_id) if parent_group_id is None: failed_msg = self._api_department_failed_msg( department_obj_id, new_group_name, '父级部门不存在') failed.append(failed_msg) continue # check department exist exist_department = ExternalDepartment.objects.get_by_provider_and_outer_id( DINGTALK_PROVIDER, department_obj_id) if exist_department: department_map_to_group_dict[department_obj_id] = exist_department.group_id failed_msg = self._api_department_failed_msg( department_obj_id, new_group_name, '部门已存在') failed.append(failed_msg) continue # import department try: group_id = ccnet_api.create_group( new_group_name, DEPARTMENT_OWNER, parent_group_id=parent_group_id) seafile_api.set_group_quota(group_id, -2) ExternalDepartment.objects.create( group_id=group_id, provider=DINGTALK_PROVIDER, outer_id=department_obj_id, ) department_map_to_group_dict[department_obj_id] = group_id success_msg = self._api_department_success_msg( department_obj_id, new_group_name, group_id) success.append(success_msg) except Exception as e: logger.error(e) failed_msg = self._api_department_failed_msg( department_obj_id, new_group_name, '部门导入失败') failed.append(failed_msg) # todo filter ccnet User database social_auth_queryset = SocialAuthUser.objects.filter(provider='dingtalk') # import api_user for api_user in api_user_list: uid = api_user.get('unionid', '') api_user['contact_email'] = api_user['email'] api_user_name = api_user.get('name') # determine the user exists if social_auth_queryset.filter(uid=uid).exists(): email = social_auth_queryset.get(uid=uid).username else: # create user email = gen_user_virtual_id() try: User.objects.create_user(email) SocialAuthUser.objects.add(email, 'dingtalk', uid) except Exception as e: logger.error(e) failed_msg = self._api_user_failed_msg( '', api_user_name, department_id, '导入用户失败') failed.append(failed_msg) continue # bind user to department api_user_department_list = api_user.get('department') for department_obj_id in api_user_department_list: group_id = department_map_to_group_dict.get(department_obj_id) if group_id is None: # the api_user also exist in the brother department which not import continue if ccnet_api.is_group_user(group_id, email, in_structure=False): failed_msg = self._api_user_failed_msg( email, api_user_name, department_obj_id, '部门成员已存在') failed.append(failed_msg) continue try: ccnet_api.group_add_member(group_id, DEPARTMENT_OWNER, email) success_msg = self._api_user_success_msg( email, api_user_name, department_obj_id, group_id) success.append(success_msg) except Exception as e: logger.error(e) failed_msg = self._api_user_failed_msg( email, api_user_name, department_id, '导入部门成员失败') failed.append(failed_msg) try: update_dingtalk_user_info(email, api_user.get('name'), api_user.get('contact_email'), api_user.get('avatar')) except Exception as e: logger.error(e) return Response({ 'success': success, 'failed': failed, })
def create_and_add_group_to_db(self, dn_name, group, group_dn_db, group_data_ldap): if group.is_department and group_dn_db.has_key(dn_name): return group_dn_db[dn_name] super_user = None if group.is_department: super_user = '******' else: super_user = LdapGroupSync.get_super_user() parent_id = 0 if not group.is_department: parent_id = 0 else: if not group.parent_dn: parent_id = -1 elif group_dn_db.has_key(group.parent_dn): parent_id = group_dn_db[group.parent_dn] else: parent_group = group_data_ldap[group.parent_dn] parent_id = self.create_and_add_group_to_db( group.parent_dn, parent_group, group_dn_db, group_data_ldap) group_id = ccnet_api.create_group(group.cn, super_user, 'LDAP', parent_id) if group_id < 0: logger.warning('create ldap group [%s] failed.' % group.cn) return ret = add_group_dn_pair(group_id, dn_name) if ret < 0: logger.warning('add group dn pair %d<->%s failed.' % (group_id, dn_name)) # admin should remove created group manually in web return logger.debug('create group %d, and add dn pair %s<->%d success.' % (group_id, dn_name, group_id)) self.agroup += 1 group.group_id = group_id if group.is_department: if group.config.default_department_quota > 0: quota_to_set = group.config.default_department_quota * 1000000 else: quota_to_set = group.config.default_department_quota ret = seafile_api.set_group_quota(group_id, quota_to_set) if ret < 0: logger.warning('Failed to set group [%s] quota.' % group.cn) if group.config.create_department_library: ret = seafile_api.add_group_owned_repo(group_id, group.cn, 'rw') if not ret: logger.warning( 'Failed to create group owned repo for %s.' % group.cn) for member in group.members: ret = group_add_member(group_id, super_user, member) if ret < 0: logger.warning('add member %s to group %d failed.' % (member, group_id)) return logger.debug('add member %s to group %d success.' % (member, group_id)) group_dn_db[dn_name] = group_id return group_id
def create_and_get_group(*a, **kw): group_id = ccnet_api.create_group(*a, **kw) group = ccnet_api.get_group(group_id) return group
def _create_group(self, request, group_name, username, parent_group_id): group_id = ccnet_api.create_group(group_name, username, parent_group_id=parent_group_id) return group_id
def test_multi_tier_groups(repo): id1 = ccnet_api.create_group('group1', USER, parent_group_id=-1) id2 = ccnet_api.create_group('group2', USER2, parent_group_id = id1) id3 = ccnet_api.create_group('group3', USER, parent_group_id = id1) id4 = ccnet_api.create_group('group4', USER2, parent_group_id = id3) id5 = ccnet_api.create_group('group5', USER2, parent_group_id = 0) assert id1 != -1 and id2 != -1 and id3 != -1 and id4 != -1 group1 = ccnet_api.get_group(id1) group2 = ccnet_api.get_group(id2) group3 = ccnet_api.get_group(id3) group4 = ccnet_api.get_group(id4) assert group1.parent_group_id == -1 assert group2.parent_group_id == id1 assert group3.parent_group_id == id1 assert group4.parent_group_id == id3 members = ccnet_api.search_group_members (id1, 'randgroup{}'.format(randstring(6))) assert len(members) == 0 members = ccnet_api.search_group_members (id1, USER) assert len(members) == 1 assert members[0].user_name == USER ances_order = [id5, id4, id3, id2, id1] user2_groups_with_ancestors = ccnet_api.get_groups (USER2, return_ancestors = True) assert len(user2_groups_with_ancestors) == 5 i = 0 for g in user2_groups_with_ancestors: assert g.id == ances_order[i] i = i + 1 order = [id5, id4, id2] i = 0 user2_groups = ccnet_api.get_groups (USER2) assert len(user2_groups) == 3 for g in user2_groups: assert g.id == order[i] i = i + 1 top_groups = ccnet_api.get_top_groups(True) assert len(top_groups) == 1 for g in top_groups: assert g.parent_group_id == -1 child_order = [id2, id3] i = 0 id1_children = ccnet_api.get_child_groups(id1) assert len(id1_children) == 2 for g in id1_children: assert g.id == child_order[i] i = i + 1 group4_order = [id1, id3, id4] i = 0 group4_ancestors = ccnet_api.get_ancestor_groups(id4) assert len(group4_ancestors) == 3 for g in group4_ancestors: assert g.id == group4_order[i] i = i + 1 rm5 = ccnet_api.remove_group(id5) rm4 = ccnet_api.remove_group(id4) rm3 = ccnet_api.remove_group(id3) rm2 = ccnet_api.remove_group(id2) rm1 = ccnet_api.remove_group(id1) assert rm5 == 0 and rm4 == 0 and rm3 == 0 and rm2 == 0 and rm1 == 0
def post(self, request): """import department from work weixin permission: IsProVersion """ if not request.user.admin_permissions.can_manage_user(): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') # argument check department_id = request.data.get('work_weixin_department_id') try: department_id = int(department_id) except Exception as e: logger.error(e) error_msg = 'work_weixin_department_ids invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # is pro version and work weixin check if not IsProVersion or not admin_work_weixin_departments_check(): error_msg = 'Feature is not enabled.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) access_token = get_work_weixin_access_token() if not access_token: logger.error('can not get work weixin access_token') error_msg = '获取企业微信组织架构失败' return api_error(status.HTTP_404_NOT_FOUND, error_msg) # list departments from work weixin api_department_list = self._list_departments_from_work_weixin( access_token, department_id) if api_department_list is None: error_msg = '获取企业微信组织架构失败' return api_error(status.HTTP_404_NOT_FOUND, error_msg) # list department members from work weixin api_user_list = self._list_department_members_from_work_weixin( access_token, department_id) if api_user_list is None: error_msg = '获取企业微信组织架构成员失败' return api_error(status.HTTP_404_NOT_FOUND, error_msg) # main success = list() failed = list() department_map_to_group_dict = dict() for index, department_obj in enumerate(api_department_list): # check department argument new_group_name = department_obj.get('name') department_obj_id = department_obj.get('id') if department_obj_id is None or not new_group_name or not validate_group_name( new_group_name): failed_msg = self._api_department_failed_msg( department_obj_id, new_group_name, '部门参数错误') failed.append(failed_msg) continue # check parent group if index == 0: parent_group_id = -1 else: parent_department_id = department_obj.get('parentid') parent_group_id = department_map_to_group_dict.get( parent_department_id) if parent_group_id is None: failed_msg = self._api_department_failed_msg( department_obj_id, new_group_name, '父级部门不存在') failed.append(failed_msg) continue # check department exist by group name exist, exist_group = self._admin_check_group_name_conflict( new_group_name) if exist: department_map_to_group_dict[ department_obj_id] = exist_group.id failed_msg = self._api_department_failed_msg( department_obj_id, new_group_name, '部门已存在') failed.append(failed_msg) continue # import department try: group_id = ccnet_api.create_group( new_group_name, DEPARTMENT_OWNER, parent_group_id=parent_group_id) seafile_api.set_group_quota(group_id, -2) department_map_to_group_dict[department_obj_id] = group_id success_msg = self._api_department_success_msg( department_obj_id, new_group_name, group_id) success.append(success_msg) except Exception as e: logger.error(e) failed_msg = self._api_department_failed_msg( department_obj_id, new_group_name, '部门导入失败') failed.append(failed_msg) # todo filter ccnet User database social_auth_queryset = SocialAuthUser.objects.filter( provider=WORK_WEIXIN_PROVIDER, uid__contains=WORK_WEIXIN_UID_PREFIX) # import api_user for api_user in api_user_list: uid = WORK_WEIXIN_UID_PREFIX + api_user.get('userid', '') api_user['contact_email'] = api_user['email'] api_user_name = api_user.get('name') # determine the user exists if social_auth_queryset.filter(uid=uid).exists(): email = social_auth_queryset.get(uid=uid).username else: # create user email = gen_user_virtual_id() create_user_success = _import_user_from_work_weixin( email, api_user) if not create_user_success: failed_msg = self._api_user_failed_msg( '', api_user_name, department_id, '导入用户失败') failed.append(failed_msg) continue # bind user to department api_user_department_list = api_user.get('department') for department_obj_id in api_user_department_list: group_id = department_map_to_group_dict.get(department_obj_id) if group_id is None: # the api_user also exist in the brother department which not import continue if ccnet_api.is_group_user(group_id, email): failed_msg = self._api_user_failed_msg( email, api_user_name, department_obj_id, '部门成员已存在') failed.append(failed_msg) continue try: ccnet_api.group_add_member(group_id, DEPARTMENT_OWNER, email) success_msg = self._api_user_success_msg( email, api_user_name, department_obj_id, group_id) success.append(success_msg) except Exception as e: logger.error(e) failed_msg = self._api_user_failed_msg( email, api_user_name, department_id, '导入部门成员失败') failed.append(failed_msg) return Response({ 'success': success, 'failed': failed, })
def test_user_management(repo): email1 = '%s@%s.com' % (randstring(6), randstring(6)) email2 = '%s@%s.com' % (randstring(6), randstring(6)) passwd1 = 'randstring(6)' passwd2 = 'randstring(6)' ccnet_api.add_emailuser(email1, passwd1, 1, 1) ccnet_api.add_emailuser(email2, passwd2, 0, 0) ccnet_email1 = ccnet_api.get_emailuser(email1) ccnet_email2 = ccnet_api.get_emailuser(email2) assert ccnet_email1.is_active == True assert ccnet_email1.is_staff == True assert ccnet_email2.is_active == False assert ccnet_email2.is_staff == False assert ccnet_api.validate_emailuser(email1, passwd1) == 0 assert ccnet_api.validate_emailuser(email2, passwd2) == 0 users = ccnet_api.search_emailusers('DB', email1, -1, -1) assert len(users) == 1 user_ccnet = users[0] assert user_ccnet.email == email1 user_counts = ccnet_api.count_emailusers('DB') user_numbers = ccnet_api.get_emailusers('DB', -1, -1) ccnet_api.update_emailuser('DB', ccnet_email2.id, passwd2, 1, 1) email2_new = ccnet_api.get_emailuser(email2) assert email2_new.is_active == True assert email2_new.is_staff == True #test group when update user id id1 = ccnet_api.create_group('group1', email1, parent_group_id=-1) assert id1 != -1 group1 = ccnet_api.get_group(id1) assert group1.parent_group_id == -1 # test shared repo when update user id api.share_repo(repo.id, USER, email1, "rw") assert api.repo_has_been_shared(repo.id) new_email1 = '%s@%s.com' % (randstring(6), randstring(6)) assert ccnet_api.update_emailuser_id(email1, new_email1) == 0 shared_users = api.list_repo_shared_to(USER, repo.id) assert len(shared_users) == 1 assert shared_users[0].repo_id == repo.id assert shared_users[0].user == new_email1 assert shared_users[0].perm == "rw" api.remove_share(repo.id, USER, new_email1) email1_groups = ccnet_api.get_groups(new_email1) assert len(email1_groups) == 1 assert email1_groups[0].id == id1 rm1 = ccnet_api.remove_group(id1) assert rm1 == 0 ccnet_api.remove_emailuser('DB', new_email1) ccnet_api.remove_emailuser('DB', email2)