Exemplo n.º 1
0
    def test_populate_groups(self) -> None:
        self.server.version = "3.7"
        with open(POPULATE_GROUPS_XML, "rb") as f:
            response_xml = f.read().decode("utf-8")
        with requests_mock.mock() as m:
            m.get(self.server.users.baseurl +
                  "/dd2239f6-ddf1-4107-981a-4cf94e415794/groups",
                  text=response_xml)
            single_user = TSC.UserItem("test", "Interactor")
            single_user._id = "dd2239f6-ddf1-4107-981a-4cf94e415794"
            self.server.users.populate_groups(single_user)

            group_list = list(single_user.groups)

            self.assertEqual(3, len(group_list))
            self.assertEqual("ef8b19c0-43b6-11e6-af50-63f5805dbe3c",
                             group_list[0].id)
            self.assertEqual("All Users", group_list[0].name)
            self.assertEqual("local", group_list[0].domain_name)

            self.assertEqual("e7833b48-c6f7-47b5-a2a7-36e7dd232758",
                             group_list[1].id)
            self.assertEqual("Another group", group_list[1].name)
            self.assertEqual("local", group_list[1].domain_name)

            self.assertEqual("86a66d40-f289-472a-83d0-927b0f954dc8",
                             group_list[2].id)
            self.assertEqual("TableauExample", group_list[2].name)
            self.assertEqual("local", group_list[2].domain_name)
def automatically_create_users(users_to_import,
                               tableau_token_value='',
                               tableau_token_name='datadev',
                               tableau_content_url='chrishastieiwdev598367'):
    import tableauserverclient as tsc
    import getpass

    # Request user password if not provided already
    if tableau_token_value == '':
        import getpass
        tableau_token_value = getpass.getpass('Access token:')

    tableau_auth = tsc.PersonalAccessTokenAuth(tableau_token_name,
                                               tableau_token_value,
                                               tableau_content_url)
    server = tsc.Server('https://10ax.online.tableau.com/',
                        use_server_version=True)

    with server.auth.sign_in(tableau_auth):
        for user in users_to_import:
            group_item = check_if_group_exists(server, user['group'])
            if not group_item:
                new_group = tsc.GroupItem(user['group'])
                group_item = server.groups.create(new_group)

            user_item = check_if_user_exists(server, user['email'])
            if not user_item:
                new_user = tsc.UserItem(user['email'], 'Unlicensed')
                user_item = server.users.add(new_user)

            server.groups.add_user(group_item, user_item.id)
Exemplo n.º 3
0
    def test_populate_workbooks(self) -> None:
        with open(POPULATE_WORKBOOKS_XML, "rb") as f:
            response_xml = f.read().decode("utf-8")
        with requests_mock.mock() as m:
            m.get(self.baseurl +
                  "/dd2239f6-ddf1-4107-981a-4cf94e415794/workbooks",
                  text=response_xml)
            single_user = TSC.UserItem("test", "Interactor")
            single_user._id = "dd2239f6-ddf1-4107-981a-4cf94e415794"
            self.server.users.populate_workbooks(single_user)

            workbook_list = list(single_user.workbooks)
            self.assertEqual("3cc6cd06-89ce-4fdc-b935-5294135d6d42",
                             workbook_list[0].id)
            self.assertEqual("SafariSample", workbook_list[0].name)
            self.assertEqual("SafariSample", workbook_list[0].content_url)
            self.assertEqual(False, workbook_list[0].show_tabs)
            self.assertEqual(26, workbook_list[0].size)
            self.assertEqual("2016-07-26T20:34:56Z",
                             format_datetime(workbook_list[0].created_at))
            self.assertEqual("2016-07-26T20:35:05Z",
                             format_datetime(workbook_list[0].updated_at))
            self.assertEqual("ee8c6e70-43b6-11e6-af4f-f7b0d8e20760",
                             workbook_list[0].project_id)
            self.assertEqual("default", workbook_list[0].project_name)
            self.assertEqual("5de011f8-5aa9-4d5b-b991-f462c8dd6bb7",
                             workbook_list[0].owner_id)
            self.assertEqual(set(["Safari", "Sample"]), workbook_list[0].tags)
Exemplo n.º 4
0
    def test_populate_workbooks(self):
        with open(POPULATE_WORKBOOKS_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.get(self.baseurl +
                  '/dd2239f6-ddf1-4107-981a-4cf94e415794/workbooks',
                  text=response_xml)
            single_user = TSC.UserItem('test', 'Interactor')
            single_user._id = 'dd2239f6-ddf1-4107-981a-4cf94e415794'
            pagination_item = self.server.users.populate_workbooks(single_user)

        workbook_list = single_user.workbooks
        self.assertEqual(1, pagination_item.total_available)
        self.assertEqual('3cc6cd06-89ce-4fdc-b935-5294135d6d42',
                         workbook_list[0].id)
        self.assertEqual('SafariSample', workbook_list[0].name)
        self.assertEqual('SafariSample', workbook_list[0].content_url)
        self.assertEqual(False, workbook_list[0].show_tabs)
        self.assertEqual(26, workbook_list[0].size)
        self.assertEqual('2016-07-26T20:34:56Z', workbook_list[0].created_at)
        self.assertEqual('2016-07-26T20:35:05Z', workbook_list[0].updated_at)
        self.assertEqual('ee8c6e70-43b6-11e6-af4f-f7b0d8e20760',
                         workbook_list[0].project_id)
        self.assertEqual('default', workbook_list[0].project_name)
        self.assertEqual('5de011f8-5aa9-4d5b-b991-f462c8dd6bb7',
                         workbook_list[0].owner_id)
        self.assertEqual(set(['Safari', 'Sample']), workbook_list[0].tags)
Exemplo n.º 5
0
    def test_populate_groups(self):
        self.server.version = '3.7'
        with open(POPULATE_GROUPS_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.get(self.server.users.baseurl +
                  '/dd2239f6-ddf1-4107-981a-4cf94e415794/groups',
                  text=response_xml)
            single_user = TSC.UserItem('test', 'Interactor')
            single_user._id = 'dd2239f6-ddf1-4107-981a-4cf94e415794'
            self.server.users.populate_groups(single_user)

            group_list = list(single_user.groups)

            self.assertEqual(3, len(group_list))
            self.assertEqual('ef8b19c0-43b6-11e6-af50-63f5805dbe3c',
                             group_list[0].id)
            self.assertEqual('All Users', group_list[0].name)
            self.assertEqual('local', group_list[0].domain_name)

            self.assertEqual('e7833b48-c6f7-47b5-a2a7-36e7dd232758',
                             group_list[1].id)
            self.assertEqual('Another group', group_list[1].name)
            self.assertEqual('local', group_list[1].domain_name)

            self.assertEqual('86a66d40-f289-472a-83d0-927b0f954dc8',
                             group_list[2].id)
            self.assertEqual('TableauExample', group_list[2].name)
            self.assertEqual('local', group_list[2].domain_name)
Exemplo n.º 6
0
 def to_tsc_user(self) -> TSC.UserItem:
     site_role = UserCommand.evaluate_site_role(self.license_level,
                                                self.admin_level,
                                                self.publisher)
     if not site_role:
         raise AttributeError("Site role is required")
     user = TSC.UserItem(self.name, site_role, self.auth)
     user.email = self.email
     user.fullname = self.fullname
     return user
Exemplo n.º 7
0
    def test_invalid_name(self):
        self.assertRaises(ValueError, TSC.UserItem, None,
                          TSC.UserItem.Roles.Publisher)
        self.assertRaises(ValueError, TSC.UserItem, "",
                          TSC.UserItem.Roles.Publisher)
        user = TSC.UserItem("me", TSC.UserItem.Roles.Publisher)
        with self.assertRaises(ValueError):
            user.name = None

        with self.assertRaises(ValueError):
            user.name = ""
    def setUp(self):
        self.server = TSC.Server('http://test')
        self.server.version = '2.5'

        # Fake signin
        self.server._site_id = 'dad65087-b08b-4603-af4e-2887b8aafc67'
        self.server._auth_token = 'j80k54ll2lfMZ0tv97mlPvvSCRyD0DOM'

        self.baseurl = self.server.favorites.baseurl
        self.user = TSC.UserItem('alice', TSC.UserItem.Roles.Viewer)
        self.user._id = 'dd2239f6-ddf1-4107-981a-4cf94e415794'
Exemplo n.º 9
0
    def setUp(self):
        self.server = TSC.Server("http://test", False)
        self.server.version = "2.5"

        # Fake signin
        self.server._site_id = "dad65087-b08b-4603-af4e-2887b8aafc67"
        self.server._auth_token = "j80k54ll2lfMZ0tv97mlPvvSCRyD0DOM"

        self.baseurl = self.server.favorites.baseurl
        self.user = TSC.UserItem("alice", TSC.UserItem.Roles.Viewer)
        self.user._id = "dd2239f6-ddf1-4107-981a-4cf94e415794"
Exemplo n.º 10
0
    def test_add(self):
        with open(ADD_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.post(self.baseurl + '', text=response_xml)
            new_user = TSC.UserItem(name='Cassie', site_role='Viewer', auth_setting='ServerDefault')
            new_user = self.server.users.add(new_user)

        self.assertEqual('4cc4c17f-898a-4de4-abed-a1681c673ced', new_user.id)
        self.assertEqual('Cassie', new_user.name)
        self.assertEqual('Viewer', new_user.site_role)
        self.assertEqual('ServerDefault', new_user.auth_setting)
def add_new_user(server, tableau_auth, df_no_ac):
    if not df_no_ac.empty:
        print('Adding new members...')
        with server.auth.sign_in(tableau_auth):
            for idx, row in df_no_ac.iterrows():
                # create a new user_item
                user1 = TSC.UserItem(row.KlookEmail, 'Viewer')
                # add new user
                user1 = server.users.add(user1)
                print(user1.name, user1.site_role, user1.id)
            print('finish adding all new members!')
    else:
        print('No no member have to add!')
Exemplo n.º 12
0
    def test_add(self) -> None:
        with open(ADD_XML, "rb") as f:
            response_xml = f.read().decode("utf-8")
        with requests_mock.mock() as m:
            m.post(self.baseurl + "", text=response_xml)
            new_user = TSC.UserItem(name="Cassie",
                                    site_role="Viewer",
                                    auth_setting="ServerDefault")
            new_user = self.server.users.add(new_user)

        self.assertEqual("4cc4c17f-898a-4de4-abed-a1681c673ced", new_user.id)
        self.assertEqual("Cassie", new_user.name)
        self.assertEqual("Viewer", new_user.site_role)
        self.assertEqual("ServerDefault", new_user.auth_setting)
Exemplo n.º 13
0
    def test_update(self):
        with open(UPDATE_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.put(self.baseurl + '/dd2239f6-ddf1-4107-981a-4cf94e415794', text=response_xml)
            single_user = TSC.UserItem('test', 'Viewer')
            single_user._id = 'dd2239f6-ddf1-4107-981a-4cf94e415794'
            single_user.name = 'Cassie'
            single_user.fullname = 'Cassie'
            single_user.email = '*****@*****.**'
            single_user = self.server.users.update(single_user)

        self.assertEqual('Cassie', single_user.name)
        self.assertEqual('Cassie', single_user.fullname)
        self.assertEqual('*****@*****.**', single_user.email)
        self.assertEqual('Viewer', single_user.site_role)
def addusertogroup(username, role, mygroup):
    # create a new UserItem object.
    # 添加用户,分配站点角色
    newU = TSC.UserItem(username, role)

    # add the new user to the site
    # 将用户加入群组
    newU = server.users.add(newU)
    print(newU.name, newU.site_role, newU.id)

    # all_groups, pagination_item = server.groups.get()
    # mygroup = all_groups[1]

    # The id for Ian is '59a8a7b6-be3a-4d2d-1e9e-08a7b6b5b4ba'

    # add Ian to the group
    server.groups.add_user(mygroup, newU.id)
Exemplo n.º 15
0
    def test_update(self) -> None:
        with open(UPDATE_XML, "rb") as f:
            response_xml = f.read().decode("utf-8")
        with requests_mock.mock() as m:
            m.put(self.baseurl + "/dd2239f6-ddf1-4107-981a-4cf94e415794",
                  text=response_xml)
            single_user = TSC.UserItem("test", "Viewer")
            single_user._id = "dd2239f6-ddf1-4107-981a-4cf94e415794"
            single_user.name = "Cassie"
            single_user.fullname = "Cassie"
            single_user.email = "*****@*****.**"
            single_user = self.server.users.update(single_user)

        self.assertEqual("Cassie", single_user.name)
        self.assertEqual("Cassie", single_user.fullname)
        self.assertEqual("*****@*****.**", single_user.email)
        self.assertEqual("Viewer", single_user.site_role)
Exemplo n.º 16
0
    def test_add_user_to_alert(self) -> None:
        response_xml = read_xml_asset(ADD_USER_TO_ALERT)
        single_alert = TSC.DataAlertItem()
        single_alert._id = "0448d2ed-590d-4fa0-b272-a2a8a24555b5"
        in_user = TSC.UserItem("Bob", TSC.UserItem.Roles.Explorer)
        in_user._id = "5de011f8-5aa9-4d5b-b991-f462c8dd6bb7"

        with requests_mock.mock() as m:
            m.post(self.baseurl +
                   "/0448d2ed-590d-4fa0-b272-a2a8a24555b5/users",
                   text=response_xml)

            out_user = self.server.data_alerts.add_user_to_alert(
                single_alert, in_user)

            self.assertEqual(out_user.id, in_user.id)
            self.assertEqual(out_user.name, in_user.name)
            self.assertEqual(out_user.site_role, in_user.site_role)
Exemplo n.º 17
0
    def add_user(self, username, site_role=''):
        #TODO: need to verify user doesnt exist on site already, if so,
        # then just grab that id, otherwise create new user

        switched_sites = False
        if site_role == '':
            site_role = 'ExplorerCanPublish'

        if self.is_current_site is False:
            self.__server.switch_current_site(self)
            switched_sites = True

        user = tsc.UserItem(username, site_role)
        user = self.__server.item.users.add(user)

        if switched_sites is True:
            self.__server.switch_current_site(self.__server.previous_site)

        return userItem.User_Item(self.server, user)
Exemplo n.º 18
0
def addNewUser(email, password, persona):
    username = getUsersName(email)
    try:
        with open(FILE_NAME, mode='a', newline='') as csv_file:
            csv_writer = csv.writer(csv_file,
                                    delimiter=',',
                                    quotechar='"',
                                    quoting=csv.QUOTE_MINIMAL)
            csv_writer.writerow([username, email, password, persona])

        server, isUserLoggedInToServerAsAdmin = loginToServer()
        server.version = '3.0'
        user = TSC.UserItem(username, USER_ROLE)
        user = server.users.add(user)
        user.email = email
        user = server.users.update(user, password)
        return True
    except:
        pass
    return False
Exemplo n.º 19
0
    def test_populate_favorites(self) -> None:
        self.server.version = "2.5"
        baseurl = self.server.favorites.baseurl
        single_user = TSC.UserItem("test", "Interactor")
        with open(GET_FAVORITES_XML, "rb") as f:
            response_xml = f.read().decode("utf-8")
        with requests_mock.mock() as m:
            m.get("{0}/{1}".format(baseurl, single_user.id), text=response_xml)
            self.server.users.populate_favorites(single_user)
        self.assertIsNotNone(single_user._favorites)
        self.assertEqual(len(single_user.favorites["workbooks"]), 1)
        self.assertEqual(len(single_user.favorites["views"]), 1)
        self.assertEqual(len(single_user.favorites["projects"]), 1)
        self.assertEqual(len(single_user.favorites["datasources"]), 1)

        workbook = single_user.favorites["workbooks"][0]
        view = single_user.favorites["views"][0]
        datasource = single_user.favorites["datasources"][0]
        project = single_user.favorites["projects"][0]

        self.assertEqual(workbook.id, "6d13b0ca-043d-4d42-8c9d-3f3313ea3a00")
        self.assertEqual(view.id, "d79634e1-6063-4ec9-95ff-50acbf609ff5")
        self.assertEqual(datasource.id, "e76a1461-3b1d-4588-bf1b-17551a879ad9")
        self.assertEqual(project.id, "1d0304cd-3796-429f-b815-7258370b9b74")
Exemplo n.º 20
0
    def test_populate_favorites(self):
        self.server.version = '2.5'
        baseurl = self.server.favorites.baseurl
        single_user = TSC.UserItem('test', 'Interactor')
        with open(GET_FAVORITES_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.get('{0}/{1}'.format(baseurl, single_user.id), text=response_xml)
            self.server.users.populate_favorites(single_user)
        self.assertIsNotNone(single_user._favorites)
        self.assertEqual(len(single_user.favorites['workbooks']), 1)
        self.assertEqual(len(single_user.favorites['views']), 1)
        self.assertEqual(len(single_user.favorites['projects']), 1)
        self.assertEqual(len(single_user.favorites['datasources']), 1)

        workbook = single_user.favorites['workbooks'][0]
        view = single_user.favorites['views'][0]
        datasource = single_user.favorites['datasources'][0]
        project = single_user.favorites['projects'][0]

        self.assertEqual(workbook.id, '6d13b0ca-043d-4d42-8c9d-3f3313ea3a00')
        self.assertEqual(view.id, 'd79634e1-6063-4ec9-95ff-50acbf609ff5')
        self.assertEqual(datasource.id, 'e76a1461-3b1d-4588-bf1b-17551a879ad9')
        self.assertEqual(project.id, '1d0304cd-3796-429f-b815-7258370b9b74')
Exemplo n.º 21
0
 def test_update_missing_id(self):
     single_user = TSC.UserItem('test', 'Interactor')
     self.assertRaises(TSC.MissingRequiredFieldError,
                       self.server.users.update, single_user)
Exemplo n.º 22
0
 def test_invalid_site_role(self):
     user = TSC.UserItem("me", TSC.UserItem.Roles.Publisher)
     with self.assertRaises(ValueError):
         user.site_role = "Hello"
Exemplo n.º 23
0
 def test_invalid_auth_setting(self):
     user = TSC.UserItem("me", TSC.UserItem.Roles.Publisher)
     with self.assertRaises(ValueError):
         user.auth_setting = "Hello"
Exemplo n.º 24
0
    ###Creating site and user###
    if site_check == 0:
        with server.auth.sign_in(tableau_auth):
            new_site = TSC.SiteItem(name=uniqueField[i],
                                    content_url=uniqueField[i].replace(
                                        " ", ""))
            server.sites.create(new_site)
        time.sleep(0.5)
        with server.auth.sign_in(tableau_auth):
            all_sites, pagination_item = server.sites.get()
        for site in all_sites:
            if site.name == uniqueField[i]:
                tableau_auth.site_id = site.content_url
                break
        with server.auth.sign_in(tableau_auth):
            user = TSC.UserItem(server_username[i], 'SiteAdministrator')
            user = server.users.add(user)
            user = server.users.update(user, 'password')

#Getting the default project and publishing workbook and datasource###
    project_id = ''
    time.sleep(1)
    with server.auth.sign_in(tableau_auth):
        all_projects, pagination_item = server.projects.get()
        for project in all_projects:

            if project.name == 'Default':
                project_id = project.id

    new_workbook = TSC.WorkbookItem(project_id)
    new_datasource = TSC.DatasourceItem(project_id)
Exemplo n.º 25
0
 def test_populate_workbooks_missing_id(self) -> None:
     single_user = TSC.UserItem("test", "Interactor")
     self.assertRaises(TSC.MissingRequiredFieldError,
                       self.server.users.populate_workbooks, single_user)
Exemplo n.º 26
0
 def test_populate_workbooks_missing_id(self):
     single_user = TSC.UserItem('test', 'Interactor')
     self.assertRaises(TSC.MissingRequiredFieldError,
                       self.server.users.populate_workbooks, single_user)
Exemplo n.º 27
0
 def test_update_missing_id(self) -> None:
     single_user = TSC.UserItem("test", "Interactor")
     self.assertRaises(TSC.MissingRequiredFieldError,
                       self.server.users.update, single_user)
Exemplo n.º 28
0
def main():
    '''主函数
    '''
    # 连接tableau server
    request_options = TSC.RequestOptions(pagesize=200)

    tableau_auth = TSC.TableauAuth('20040201', 'GT2020!qaz', site_id='')
    # tableau_auth = TSC.TableauAuth('GT_Account', 'GT2020123456', site_id='')
    # server = TSC.Server('https://fas-gt.com:8000', use_server_version=True)
    server = TSC.Server('https://tab.sucgm.com:10000', use_server_version=True)

    nowTime = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')  # 现在
    content = fwapi()
    infos = content['data']
    # print("输出本次全部数据:",infos)
    connect = sqlcon()
    workgroup = []
    cursor = connect.cursor()  # 创建一个游标对象,python里的sql语句都要通过cursor来执行

    # 1. 创建文件对象
    f = open('user&pwd-' + nowTime + '.csv',
             'w',
             encoding='utf-8',
             newline=''
             "")
    # 2. 基于文件对象构建 csv写入对象
    csv_writer = csv.writer(f)

    # 3. 构建列表头
    csv_writer.writerow(["Workcode", "Password"])
    tbgroup = tabgroup(server, tableau_auth, request_options)
    tbuser = tabuser(server, tableau_auth, request_options)

    # 本次新加入用户计数器
    addCount = 0
    addRecord = []
    # 本次离职人数计数器
    quitCount = 0

    # 系统账户(不可删除)
    SystemUser = ['SHCJTS_Admin', '20040201', 'RPA_Account']

    for info in infos:
        # 遍历获取员工信息号和群组名称
        workcode = info['workcode']
        # workcode = 'A0716'
        groupidnew = info['rolesmark']
        status = info['status']
        if status == '1':
            groupidnew = groupidnew[:-5]  # 将群组名称后的 -致同群组 字段删除
            workgroup.append([workcode, groupidnew])
            print(workcode)
            # 查询FW_Users库内对应workcoode 人员状态信息
            sql = "select * from OFW_USER_TAB_ALLOWED where IsDelete = 0 and MemberCode = %s"
            # sql = "select * from OFW_USER_TAB_ALLOWED where  MemberCode = %s"
            # sql = "select * from OFW_USER_TAB_ALLOWED_TEST where IsDelete = 0 and MemberCode = %s"
            cursor.execute(sql, workcode)  # 执行sql语句
            row = cursor.fetchall()  # 读取查询结果,
            rowCount = len(row)
            print(row)
            # for n in row:
            #     print(n[1])
            print(workcode, "该员工当前在Tableau Server对应群组记录数", rowCount)
            # time.sleep(5)

            # 查询用户是否已存在 若不存在 创建新用户并加入相应群组
            if rowCount == 0:
                # 查询该用户是否之前曾有过群组的记录
                sql = "select * from OFW_USER_TAB_ALLOWED where IsDelete = 1 and MemberCode = %s and GroupID= %s"
                # sql = "select * from OFW_USER_TAB_ALLOWED_TEST where IsDelete = 0 and MemberCode = %s and GroupID= %s"
                value = (workcode, groupidnew)
                cursor.execute(sql, value)  # 执行sql语句
                row = cursor.fetchall()  # 读取查询结果,
                rowCount = len(row)
                if rowCount != 0:
                    sql = "UPDATE OFW_USER_TAB_ALLOWED SET IsDelete =0 WHERE MemberCode = %s and GroupID= %s"
                    # sql = "UPDATE OFW_USER_TAB_ALLOWED_TEST SET IsDelete =0 WHERE MemberCode = %s and GroupID= %s"
                    cursor.execute(sql, value)
                    connect.commit()
                    addCount = addCount + 1
                    with server.auth.sign_in(tableau_auth):
                        # 将用户加入群组
                        # index = getTwoDimensionListIndex(tbgroup, groupidnew)
                        user = getTwoDimensionListIndex(tbuser, workcode)
                        # print(user)
                        all_groups, pagination_item = server.groups.get(
                            request_options)
                        for group in all_groups:
                            if group.name == groupidnew:
                                server.groups.add_user(group, tbuser[user][0])
                                break
                else:
                    with server.auth.sign_in(tableau_auth):
                        # 先查询用户是否存在

                        # 将新用户添加至user表
                        newU = TSC.UserItem(workcode, 'Viewer')
                        # add the new user to the site
                        newU = server.users.add(newU)
                        # 将用户的id,name加入tbuser
                        tbuser.append([newU.id, newU.name])
                        # 更新详细信息
                        newU.fullname = workcode
                        # index = getTwoDimensionListIndex(tbgroup, groupidnew)

                        # 加入群组
                        # if index !="不存在该值":
                        all_groups, pagination_item = server.groups.get(
                            request_options)
                        for group in all_groups:
                            if group.name == groupidnew:
                                server.groups.add_user(group, newU.id)
                                break
                        # else:
                        #     print(index)
                        pwd = pwdcreate()
                        csv_writer.writerow([workcode, pwd])
                        user1 = server.users.update(newU, password=pwd)
                    sql2 = "insert into OFW_USER_TAB_ALLOWED (MemberCode,GroupID) VALUES (%s,%s)"
                    # sql2 = "insert into OFW_USER_TAB_ALLOWED_TEST (MemberCode,GroupID) VALUES (%s,%s)"
                    value = (workcode, groupidnew)
                    cursor.execute(sql2, value)
                    connect.commit()
                    print('完成账号 ' + workcode + ' 在群组 ' + groupidnew + ' 的添加')
                    addCount = addCount + 1
                    addRecord.append([workcode, groupidnew])

            # 用户已存在的情况
            else:
                # 查询该用户是否之前曾有过群组的记录
                sql = "select * from OFW_USER_TAB_ALLOWED where IsDelete = 1 and MemberCode = %s and GroupID= %s"
                # sql = "select * from OFW_USER_TAB_ALLOWED_TEST where IsDelete = 1 and MemberCode = %s and GroupID= %s"
                value = (workcode, groupidnew)
                cursor.execute(sql, value)  # 执行sql语句
                rowold = cursor.fetchall()  # 读取查询结果,
                rowCount = len(rowold)
                # 无群组记录
                if rowCount != 0:  # rowCount不为0 说明该用户在该群组之前有记录被删除,将isdel置0#
                    sql = "UPDATE OFW_USER_TAB_ALLOWED SET IsDelete =0 WHERE MemberCode = %s and GroupID= %s"
                    # sql = "UPDATE OFW_USER_TAB_ALLOWED_TEST SET IsDelete =0 WHERE MemberCode = %s and GroupID= %s"
                    cursor.execute(sql, value)
                    connect.commit()
                    with server.auth.sign_in(tableau_auth):
                        # 将用户加入群组
                        # index = getTwoDimensionListIndex(tbgroup, groupidnew)
                        user = getTwoDimensionListIndex(tbuser, workcode)
                        # print(user)
                        all_groups, pagination_item = server.groups.get(
                            request_options)
                        for group in all_groups:
                            if group.name == groupidnew:
                                server.groups.add_user(group, tbuser[user][0])
                                print('完成账号 ' + workcode + ' 在群组 ' +
                                      groupidnew + ' 的添加')
                                addCount = addCount + 1
                                addRecord.append([workcode, groupidnew])
                                break
                else:
                    oldgroup = []
                    # 该员工原有的群组
                    for n in row:
                        oldgroup.append(n[1])
                        # api传递的数据是一一对应的情况
                    print(workcode, "该员工对应原有群组", oldgroup)
                    if groupidnew not in oldgroup:
                        with server.auth.sign_in(tableau_auth):
                            # 将用户加入群组
                            # index = getTwoDimensionListIndex(tbgroup, groupidnew)
                            user = getTwoDimensionListIndex(tbuser, workcode)
                            print(user)
                            all_groups, pagination_item = server.groups.get(
                                request_options)
                            for group in all_groups:
                                if group.name == groupidnew:
                                    server.groups.add_user(
                                        group, tbuser[user][0])
                                    break

                            # 更新详细信息
                            # newU.name = 'test'
                            # newU.fullname = workcode
                            sql2 = "insert into OFW_USER_TAB_ALLOWED (MemberCode,GroupID) VALUES (%s,%s)"
                            # sql2 = "insert into OFW_USER_TAB_ALLOWED_TEST (MemberCode,GroupID) VALUES (%s,%s)"
                            value = (workcode, groupidnew)
                            cursor.execute(sql2, value)
                            connect.commit()
                            print('完成账号 ' + workcode + ' 在群组 ' + groupidnew +
                                  ' 的添加')
                            addCount = addCount + 1
                            addRecord.append([workcode, groupidnew])
    f.close()
    cursor = connect.cursor()  # 创建一个游标对象,python里的sql语句都要通过cursor来执行
    # 查询群组表内的群组信息
    sql = "select GroupName from OFW_GROUP_TAB_ALLOWED"
    # sql = "select GroupName from OFW_GROUP_TAB_ALLOWED_TEST"
    cursor.execute(sql)  # 执行sql语句
    rowgroup = cursor.fetchall()  # 读取查询结果,
    # rowCount = len(row)
    for groupid in rowgroup:
        # print(groupid)
        groupid = groupid[0]
        # 查询表内对应该群组的workcode
        sqls = "select MemberCode from OFW_USER_TAB_ALLOWED where GroupID= %s and IsDelete =0"
        # sqls = "select MemberCode from OFW_USER_TAB_ALLOWED_TEST where GroupID= %s"
        cursor.execute(sqls, groupid)  # 执行sql语句
        rowidingroups = cursor.fetchall()  # 读取查询结果,
        # print(rowidingroups)
        for rowidingroup in rowidingroups:
            rawdata = rowidingroup[0]
            # 此处注意判断是否有另外开的账号 需要加在指定群组中 但不在泛微数据中
            if [rawdata, groupid] not in workgroup:
                # 通过tsc 获取id 在group中删除
                # indexgroup=getTwoDimensionListIndex(tbgroup,groupid)
                indexuser = getTwoDimensionListIndex(tbuser, rawdata)
                with server.auth.sign_in(tableau_auth):
                    # mygroup = tbgroup[indexgroup][0]
                    userdel = tbuser[indexuser][0]
                    all_groups, pagination_item = server.groups.get(
                        request_options)
                    for group in all_groups:
                        if group.name == groupid:
                            server.groups.remove_user(group, userdel)
                            # 若该群组不存在 进行逻辑删除
                            sql = "UPDATE OFW_USER_TAB_ALLOWED SET IsDelete =1 WHERE MemberCode = %s and GroupID= %s"
                            # sql = "UPDATE OFW_USER_TAB_ALLOWED_TEST SET IsDelete =1 WHERE MemberCode = %s and GroupID= %s"
                            value = (rawdata, groupid)
                            cursor.execute(sql, value)
                            # 提交到数据库执行
                            connect.commit()
                            break
                    print('完成对 ' + rawdata + " 在群组 " + groupid + " 的删除操作")

    for userid in tbuser:
        # 判断是否为非城建用户
        if userid[1] not in SystemUser:
            sql = "select * from DW_HR_MEMBER where MemberMsgCode = %s AND snapdate = CONVERT(DATE,GETDATE(),110)"
            cursor.execute(sql, userid[1])  # 执行sql语句
            row = cursor.fetchall()  # 读取查询结果,
            rowCount = len(row)
            # 为0代表用户已离职 从tableau server端删除 计数器+1
            if rowCount == 0:
                with server.auth.sign_in(tableau_auth):
                    server.users.remove(userid[0])
                    print('员工' + userid[1] + '已离职,从Tableau Server端删除成功')
                    quitCount = quitCount + 1

    print('本次共删除用户' + str(quitCount) + '人')

    # 统计各群组新增用户
    if addRecord:
        for record in addRecord:
            print('本次已完成对用户 ' + record[0] + ' 在群组 ' + record[1] + '中的添加')

    print('本次完成群组新增' + str(addCount) + '人')
Exemplo n.º 29
0
#get list of all the users from Server Site
with server.auth.sign_in(tableau_auth_sndbx):
    all_users = list(TSC.Pager(endpoint, request_option))
    userlist = [user.name for user in all_users]
    user_role = [user.site_role for user in all_users]
    user_id = [user.id for user in all_users]
    print(userlist)
    print(len(userlist))

# create user
with server.auth.sign_in(tableau_auth):
    for u in userlist:
        try:
            newU = TSC.UserItem(
                u, 'Viewer'
            )  #Keeping all of them viewers Server Admins will be recognized automatically
            # add the new user to the site
            newU = server.users.add(newU)
            print(newU.name, newU.site_role)
        except:
            pass

# print the names of the groups on the server
with server.auth.sign_in(tableau_auth_sndbx):
    all_groups, pagination_item = server.groups.get()
    group_list = [group.name for group in all_groups]
    print("\nThere are {} groups on site: ".format(
        pagination_item.total_available))
    print(group_list)
Exemplo n.º 30
0
    def _sync_site_user(self):
        self.logger.debug('Revision users on site')
        tableau_all_site_users = [user for user in TSC.Pager(self.tab.users)]
        # tableau_unlicensed_users = [user for user in TSC.Pager(tab.users) if user.site_role == 'ServerAdministrator']
        # self.logger.debug(f"tableau_unlicensed_users: {', '.join([u.name for u in  tableau_unlicensed_users])}")
        self.logger.debug('Revision users on AD')
        ad_all_site_users = self.ad.get_all_site_users(self.site_name)
        old_users = list(
            set([u.name for u in tableau_all_site_users]) -
            set([u.sAMAccountName.value
                 for u in ad_all_site_users]) - self.serviceaccounts)
        new_users = list(
            set([u.sAMAccountName.value for u in ad_all_site_users]) -
            set([u.name
                 for u in tableau_all_site_users]) - self.serviceaccounts)

        # This ugly code, but I was forced to write this.
        if self.site_name == 'ERS':
            self.logger.info(f"Site ERS. Set old_users to None")
            old_users = []
        # End ugly code

        if old_users:
            self.logger.info(f"Old users: {old_users}")
        if new_users:
            self.logger.info(f"New users: {new_users}")

        for user in old_users:
            self.logger.info(f"Removing {user}")
            user_obj = [u for u in tableau_all_site_users
                        if u.name == user].pop()
            if user_obj.site_role == 'ServerAdministrator':
                self.logger.info(
                    f"{user_obj.name} is ServerAdministrator. Send mail")
                if self.noop:
                    self.mails.send_mail_old_serveradministrator(
                        name=user_obj.name)
            else:
                self.tab.users.populate_workbooks(user_obj)
                user_workbooks = [
                    b for b in user_obj.workbooks if b.owner_id == user_obj.id
                ]
                if len(user_workbooks) > 0:
                    self.logger.info(
                        f"{user_obj.name} has workbooks: {[w.name for w in user_workbooks]}"
                    )
                    if not user_obj.site_role == 'Unlicensed':
                        old_role = user_obj.site_role
                        user_obj.site_role = 'Unlicensed'
                        if self.noop:
                            self.tab.users.update(user_obj)
                        self.logger.info(
                            f"{user_obj.name}'s user role has been changed from {old_role} to Unlicensed."
                        )
                    else:
                        self.logger.info(
                            f"{user_obj.name} already has role Unlicensed. Skip"
                        )
                else:
                    if self.noop:
                        try:
                            self.tab.users.remove(user_obj.id)
                        except TSC.server.endpoint.exceptions.ServerResponseError as ServerResponseError:
                            if not ServerResponseError.code == '409003':
                                raise ServerResponseError
                    self.logger.info(f"{user} has been removed")

        for user in new_users:
            if user in [
                    u.name for u in tableau_all_site_users
                    if u.site_role != 'Unlicensed'
            ]:
                tableau_user = [
                    u for u in tableau_all_site_users if u.name == user
                ].pop()
                self.logger.info(
                    'Change site role to Interactor for {0}'.format(user))
                tableau_user.site_role = 'Interactor'
                if self.noop:
                    self.tab.users.update(tableau_user)

            else:
                self.logger.info("Creating user: {0}".format(user))
                ad_user_data = self.ad.get_user_by_samaccountname(user)
                password = ''.join(
                    random.choice(string.ascii_letters + string.digits)
                    for x in range(32))
                new_user = TSC.UserItem(
                    name=ad_user_data[0].sAMAccountName.value,
                    site_role='Interactor')
                if self.noop:
                    new_user = self.tab.users.add(new_user)
                new_user.email = ad_user_data[0].mail.value
                new_user.fullname = ad_user_data[0].name.value
                new_user.password = password
                if self.noop:
                    _ = self.tab.users.update(new_user)
        self.logger.debug("Start revision userdata on the site")

        tableau_site_users = [
            u for u in TSC.Pager(self.tab.users) if u.site_role != 'Unlicensed'
            and u.name not in self.serviceaccounts
        ]
        for user in tableau_site_users:
            #It's tableau server bug.
            #Tableau returns users tho was deleted in the previous step.
            try:
                tuser_obj = self.tab.users.get_by_id(user.id)
            except Exception as e:
                self.logger.warning(f"Error while self.tab.users.get_by_id{e}")
            else:
                auser_obj = self.ad.get_user_by_samaccountname(tuser_obj.name)
                if auser_obj:
                    if tuser_obj.fullname != auser_obj[0].name.value:
                        self.logger.info(
                            f"Changing {tuser_obj.name}'s fullname: {tuser_obj.fullname} -> {auser_obj[0].name.value}"
                        )
                        tuser_obj.fullname = auser_obj[0].name.value
                        if self.noop:
                            self.tab.users.update(tuser_obj)
                            tuser_obj.email = auser_obj[0].mail.value