Beispiel #1
0
    def get_box_client(self, parsed_url):
        try:
            config_path = os.path.expanduser(
                parsed_url.query_args[u'config'][0])
            return Client(JWTAuth.from_settings_file(config_path))
        except Exception as e:
            config_path = os.environ.get(u'BOX_CONFIG_PATH')
            if config_path is not None:
                try:
                    return Client(JWTAuth.from_settings_file(config_path))
                except Exception as e:
                    raise BackendException(u'box config file is not found.')

            raise BackendException(
                u'box config file is not specified or not found.')
 def authenticate(self):
     '''
     JWT authentication
     '''
     auth = JWTAuth.from_settings_file(self.config_filename)
     access_token = auth.authenticate_instance()
     self.client = Client(auth)
Beispiel #3
0
 def __init__(self):
     config = JWTAuth.from_settings_file('800515977_eqwyjy8m_config.json')
     self.client = Client(config)
     self.user_to_impersonate = self.client.user(user_id='226100449')
     self.user_client = self.client.as_user(self.user_to_impersonate)
     self.music_folder = self.user_client.root_folder().get()
     self.update_thread = UpdateThread(self.user_client, self.music_folder)
def set_connection():
    auth = JWTAuth.from_settings_file(
        'C:\\Users\\gwilliams\\Desktop\\Python Experiments\\work projects\\Working_with_Box\\Working_with_Box\\config_info\\keys_config.json'
    )

    client = Client(auth)

    return client
Beispiel #5
0
 def __init__(self):
     #p=Proxy()
     #p.URL='https://bcpxy.nycnet:8080'
     #p.AUTH={'user': '******', 'password':'******'}
     #self.session=Session(proxy_config=p)
     self.session=Session()
     self.sdk = JWTAuth.from_settings_file('/code/mocj_porter/config/box_config.json')
     self.client=Client(self.sdk,self.session)
Beispiel #6
0
 def __init__(self, path_to_config):
     print("box_config", path_to_config)
     if os.path.isfile(path_to_config) == False:
         raise ValueError(
             "configPath must be a path to the JSON config file for your Box JWT app"
         )
     auth = JWTAuth.from_settings_file(path_to_config)
     logger.info("Authenticating BoxAdaptor...")
     auth.authenticate_instance()
     self.client = Client(auth)
Beispiel #7
0
def upload_files(file_paths, dir_name):
    """ TODO """
    config = JWTAuth.from_settings_file('static/secrets/config.json')

    try:
        client = Client(config)
        content = Folder(client.folder('0'))
        user = client.user().get()
        print(content)
        print(content.get_items())
        print('The current user ID is {0}'.format(user.id))
    except (BoxOAuthException, BoxException) as e:
        # logging.warn()
        raise e
def get_box_authenticated_client(box_json_config_path):
    """
    Get an authenticated Box client for a JWT service account

    :param box_json_config_path:
    :return:
    """
    if not os.path.isfile(box_json_config_path):
        raise ValueError(
            "`box_json_config_path` must be a path to the JSON config file for your Box JWT app"
        )
    auth = JWTAuth.from_settings_file(box_json_config_path)
    auth.authenticate_instance()
    return Client(auth)
Beispiel #9
0
    def get_conn(self):
        """
        :return:
        """
        if self._box_client:
            return self._box_client

        key_path = os.environ.get('BOX_AUTH_LOCATION', False)

        if key_path:
            self.log.info('Getting connection using a JSON key file.')
            self._box_client = Client(JWTAuth.from_settings_file(key_path))
            return self._box_client
        else:
            raise AirflowException("BOX JSON key file is missing")
Beispiel #10
0
    def get_client(self):
        auth = JWTAuth.from_settings_file(self.config_file)
        admin_client = Client(auth)

        lifespan_user = None
        # lifespan_user = client.create_user('Lifespan Automation')
        for user in admin_client.users():
            if user.name == self.user:
                lifespan_user = user

        if not lifespan_user:
            print(self.user + ' user was not found. Exiting...')
            sys.exit(-1)

        return admin_client.as_user(lifespan_user)
Beispiel #11
0
def update_file(file_id, file_path):
    """
    Updates a file (that must exist in Box folder) given its identifier.
    :param file_id: File identifier.
    :param file_path: File path.
    :return: File identifier if the update was successful, None otherwise.
    """
    box_client = Client(JWTAuth.from_settings_file(BOX_CONFIG_FILE_PATH))
    for i in range(0, BOX_RETRIES):
        try:
            return box_client.file(file_id).update_contents(file_path).id
        except Exception as e:
            time.sleep(BOX_RTM)
            if i == BOX_RETRIES - 1:
                print(f'Error calling Box API updating the file [{file_id}] with file [{file_path}]: {e}')
    return None
Beispiel #12
0
def create_folder(folder_name):
    """
    Creates a folder in the root folder given its name.
    :param folder_name: Folder name to create.
    :return: Folder identifier if the creation was successful, None otherwise.
    """
    box_client = Client(JWTAuth.from_settings_file(BOX_CONFIG_FILE_PATH))
    for i in range(0, BOX_RETRIES):
        try:
            sub_folder = box_client.folder(BOX_FOLDER_ROOT_ID).create_subfolder(folder_name)
            return sub_folder.id
        except Exception as e:
            time.sleep(BOX_RTM)
            if i == BOX_RETRIES - 1:
                print(f'Error calling Box API creating the folder [{folder_name}] into folder root: {e}')
    return None
Beispiel #13
0
def upload_file(folder_id, file_path):
    """
    Uploads a file (that must not exist in Box folder) into a folder given its path.
    :param folder_id: Folder identifier.
    :param file_path: File path.
    :return: File identifier if the upload was successful, None otherwise.
    """
    box_client = Client(JWTAuth.from_settings_file(BOX_CONFIG_FILE_PATH))
    for i in range(0, BOX_RETRIES):
        try:
            file_name = file_path.split('/')[-1]
            return box_client.folder(folder_id).upload(file_path, file_name).id
        except Exception as e:
            time.sleep(BOX_RTM)
            if i == BOX_RETRIES - 1:
                print(f'Error calling Box API uploading the file [{file_path}] to folder with id [{folder_id}]: {e}')
    return None
Beispiel #14
0
def download_file(file_id, file_path):
    """
    Downloads a Box file given its identifier to a specific path.
    :param file_id: File identifier.
    :param file_path: File path.
    :return: True if the download was successful, False otherwise.
    """
    box_client = Client(JWTAuth.from_settings_file(BOX_CONFIG_FILE_PATH))
    for i in range(0, BOX_RETRIES):
        try:
            with open(file_path, 'wb') as file:
                box_client.file(file_id).download_to(file)
            return True
        except Exception as e:
            time.sleep(BOX_RTM)
            if i == BOX_RETRIES - 1:
                print(f'Error calling Box API downloading the file [{file_id}] to file [{file_path}]: {e}')
    return False
Beispiel #15
0
    def __init__(self):
        # Local
        self.CONFIG_PATH = "/home/pi/Activity_Monitor_Base_Station/box/config.json"
        self.FILE_READ_PATH = "/home/pi/Activity_Monitor_Base_Station/box/read.txt"
        self.FILE_WRITE_PATH = "/home/pi/Activity_Monitor_Base_Station/box/write.txt"
        self.FILE_ERROR_PATH = "/home/pi/Activity_Monitor_Base_Station/box/error.txt"

        # Remote
        self.DATA_FOLDER = "75253867312"  # CHANGE THIS
        self.ERROR_FOLDER = "78605578754"  # CHANGE THIS
        self.client = ""

        # Retrieve authentication information from config file
        auth = JWTAuth.from_settings_file(self.CONFIG_PATH)
        # Authenticate applications token
        access_token = auth.authenticate_instance()
        # Authorize application client
        self.client = Client(auth)
def get_authenticated_client(config_path):
    """Get an authenticated Box client for a JWT service account

    Arguments:
        configPath {str} -- Path to the JSON config file for your Box JWT app

    Returns:
        Client -- A Box client for the JWT service account

    Raises:
        ValueError -- if the configPath is empty or cannot be found.
    """
    if not os.path.isfile(config_path):
        raise ValueError(f"configPath must be a path to the JSON config file for your Box JWT app")
    auth = JWTAuth.from_settings_file(config_path)
    print("Authenticating...")
    auth.authenticate_instance()
    return Client(auth)
Beispiel #17
0
def get_client(service_account):
    """
    Attempts to create the Box Client with the associated with the credentials.
    """
    try:
        if os.path.isfile(service_account):
            auth = JWTAuth.from_settings_file(service_account)
        else:
            service_dict = json.loads(service_account)
            auth = JWTAuth.from_settings_dictionary(service_dict)

        client = Client(auth)
        client.user().get()
        return client
    except BoxOAuthException as e:
        print(f'Error accessing Box account with pervice account ' \
              f'developer_token={developer_token}; client_id={client_id}; ' \
              f'client_secret={client_secret}')
        raise (e)
Beispiel #18
0
def search_file(folder_id, file_name):
    """
    Finds a file into a folder given its identifier and a query string.
    :param folder_id: Folder identifier.
    :param file_name: File name.
    :return: File identifier if the file exists, None otherwise.
    """
    box_client = Client(JWTAuth.from_settings_file(BOX_CONFIG_FILE_PATH))
    for i in range(0, BOX_RETRIES):
        try:
            for result in box_client.folder(folder_id).get_items():
                if result.name == file_name:
                    return result.id
            return None
        except Exception as e:
            time.sleep(BOX_RTM)
            if i == BOX_RETRIES - 1:
                print(f'Error calling Box API searching files into folder [{folder_id}] with name [{file_name}]: {e}')
    return None
Beispiel #19
0
    def load_mentors_spreadsheet(self, auth):
        ''' Load the feline foster spreadsheet
        '''
        try:
            Log.success(
                f'Loading mentors spreadsheet from Box (id = {auth["box_file_id"]})...'
            )

            jwt_path = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), auth['box_jwt'])
            client = Client(JWTAuth.from_settings_file(jwt_path))
            box_file = client.as_user(
                client.user(user_id=auth['box_user_id'])).file(
                    file_id=auth['box_file_id']).get()
            xlxs_workbook = xlrd.open_workbook(
                file_contents=box_file.content())

            config_yaml = xlxs_workbook.sheet_by_name(
                self._CONFIG_SHEET_NAME).row_values(1)[0]

            for sheet_name in xlxs_workbook.sheet_names():
                if not self._is_reserved_sheet(sheet_name):
                    sheet = xlxs_workbook.sheet_by_name(sheet_name)
                    self._mentor_sheets.append(sheet)
                    all_values = [
                        sheet.row_values(i) for i in range(1, sheet.nrows)
                    ]
                    self._mentor_match_values[Utils.utf8(sheet_name)] = [
                        Utils.utf8(str(item)).lower() for sublist in all_values
                        for item in sublist
                    ]

        except Exception as e:
            Log.error(
                f'ERROR: Unable to load Feline Foster spreadsheet!\r\n{str(e)}, {repr(e)}'
            )
            return None

        print(
            f'Loaded {len(self._mentor_sheets)} mentors from \"{box_file["name"]}\"'
        )
        return config_yaml
def main(box_config, parent_folder_id, day_lookback, start_date_str,
         end_date_str):
    # Get the Box service account client
    auth = JWTAuth.from_settings_file(box_config)
    client = Client(auth)
    current_enterprise = client.get_current_enterprise()
    global current_enterprise_id
    current_enterprise_id = current_enterprise.id

    service_account = client.user().get()
    print(
        'Found Service Account with name: {0}, id: {1}, and login: {2}'.format(
            service_account.name, service_account.id, service_account.login))

    start_date = None
    end_date = None
    if day_lookback is not None:
        # Get the current date and the date for one month ago
        start_date = end_date - relativedelta.relativedelta(days=day_lookback)
        end_date = datetime.utcnow()
    elif (start_date_str is not None) and (end_date_str is not None):
        date_format = '%Y-%m-%d'
        start_date = datetime.strptime(start_date_str, date_format)
        end_date = datetime.strptime(end_date_str, date_format)
    else:
        raise Exception(
            '--day_lookback OR --start_date AND --end_date are required parameters!'
        )
    print('Using date range for events - start date: {0} and end date: {1}'.
          format(start_date, end_date))

    # Create a collaboration dictionary
    traverse_folder_tree(client, parent_folder_id)
    print('Found collab count: {0}'.format(len(folder_collaborations_dict)))

    # Get Box events
    get_box_events(client, limit, 0, start_date, end_date)
    print('Found event count: {0}'.format(len(events_dict)))

    # Generate Excel report
    create_excel_report()
    print('Finished!')
Beispiel #21
0
def create_shared_link(folder_id):
    """
    Creates an Internet accessible shared link of folder given its identifier.
    :param folder_id: Folder identifier.
    :return: Shared link if the creation was successful, None otherwise.
    """
    box_client = Client(JWTAuth.from_settings_file(BOX_CONFIG_FILE_PATH))
    for i in range(0, BOX_RETRIES):
        try:
            shared_link = box_client.folder(folder_id).get_shared_link(
                access=BOX_LINK_OPEN_ACCESS,
                allow_download=BOX_LINK_ALLOW_DOWNLOAD,
                allow_preview=BOX_LINK_ALLOW_PREVIEW
            )
            return shared_link
        except Exception as e:
            time.sleep(BOX_RTM)
            if i == BOX_RETRIES - 1:
                print(f'Error calling Box API creating a shared link for folder [{folder_id}]: {e}')
    return None
Beispiel #22
0
    def __init__(self, path_to_config=DEFAULT_CONFIG_FP, user_agent="Luigi"):
        """
        :param str path_to_config: path to Box JWT config.json file
        """
        if not path_to_config:
            raise ValueError(
                "The path_to_config parameter must contain a valid Box JWT config.json file"
            )

        self.path_to_config = path_to_config

        try:
            config = JWTAuth.from_settings_file(path_to_config)
            self.client = Client(config)
            self.conn = self.client
        except Exception as e:
            raise Exception(
                "Cannot connect to Box. Check your Internet connection and the token. \n"
                + repr(e))

        self.token = path_to_config
Beispiel #23
0
def box_auth():
    uid = g.user.id

    # Instantiate Box Client instance
    auth = JWTAuth.from_settings_file('../config.json')
    box_client = Client(auth)

    # Validate is user exists
    url = f'https://api.box.com/2.0/users?external_app_user_id={uid}'
    response = box_client.make_request('GET', url)
    user_info = response.json()

    # If user not found, create user, otherwise fetch user token
    if (user_info['total_count'] == 0):
        user_name = f'{g.user.profile.firstName} {g.user.profile.lastName}'
        space = 1073741824

        # Create app user
        user = box_client.create_user(user_name,
                                      None,
                                      space_amount=space,
                                      external_app_user_id=uid)
        print('user {name} created')
    else:
        # Create user client based on discovered user
        user = user_info['entries'][0]
        user_to_impersonate = box_client.user(user_id=user['id'])
        user_client = box_client.as_user(user_to_impersonate)

        # Get current user
        current_user = box_client.user().get()
        print(current_user.id)

        # Get all items in a folder
        items = user_client.folder(folder_id='0').get_items()
        for item in items:
            print('{0} {1} is named "{2}"'.format(item.type.capitalize(),
                                                  item.id, item.name))

        return 'Test complete'
Beispiel #24
0
    def downloadcsv(
            self, authPath: "path to your box config file, a json file",
            folderID:
        "the id of the folder on box drive containing the csv files",
            date: "the date taht the csv file was created"):
        """Download the csv file from box."""
        from boxsdk import JWTAuth
        from boxsdk import Client
        import os

        sdk = JWTAuth.from_settings_file(authPath)
        client = Client(sdk)
        items = client.folder(folder_id=folderID).get_items()
        dir = os.getcwd()
        for item in items:
            if date in item.name:
                item_id = item.id
                box_file = client.file(file_id=item_id).get()
                output_file = open(f'{os.getcwd()}/raw_csv/{box_file.name}',
                                   'wb')
                box_file.download_to(output_file)
                output_file.close()
Beispiel #25
0
def get_box_authenticated_client(box_json_config_path, is_verbose=False):
    """Get an authenticated Box client for a JWT service account

    :param box_json_config_path: A path to the JSON config file for your Box JWT app
    :type  box_json_config_path: str
    :param is_verbose: A flag for turning print statements on/off, optional
    :type  is_verbose: bool, optional

    :raises ValueError: if the box_json_config_path is empty or cannot be found

    :return: A Box client for the JWT service account
    :rtype: Client
    """
    if not os.path.isfile(box_json_config_path):
        raise ValueError(
            f"`box_json_config_path` must be a path to the JSON config file for your Box JWT app"
        )
    auth = JWTAuth.from_settings_file(box_json_config_path)
    if is_verbose:
        print(f"Authenticating...")
    auth.authenticate_instance()
    return Client(auth)
def createBoxUserClient(userId):
    user = client.user(user_id=userId)
    configJson = os.getenv('BoxConfigJson')
    auth = JWTAuth.from_settings_file(configJson)
    auth.authenticate_user()
    user_client = Client(auth)
def createBoxClient():
    configJson = os.getenv('BoxConfigJson')
    auth = JWTAuth.from_settings_file(configJson)
    return Client(auth)
Beispiel #28
0
from boxsdk import JWTAuth, Client
from box_api import get_child_items, get_folder_information

if __name__ == '__main__':
    # see: https://developer.box.com/guides/authentication/jwt/with-sdk/
    config = JWTAuth.from_settings_file('./config.json')
    client = Client(config)

    root_folder_id = '123456789'
    root_folder = get_folder_information(client, root_folder_id)
    root_folder = get_child_items(client, root_folder)
from boxsdk import JWTAuth, Client

auth = JWTAuth.from_settings_file('box_config.json')
client = Client(auth)
service_account = client.user().get()
print(
    'Service Account user email is {0}\nShare your root folder with this address for the script to be able to access the subfolders.'
    .format(service_account.login))
    def __init__(self, service=None, config="~/.cloudmesh/cloudmesh4.yaml"):

        super().__init__(service=service, config=config)
        self.sdk = JWTAuth.from_settings_file(self.credentials['config_path'])
        self.client = Client(self.sdk)