Exemplo n.º 1
0
def get_box_client():
    secret = _get_secret()

    client_id = secret["box_client_id"]
    client_secret = secret["box_client_secret"]
    enterprise_id = secret["box_enterprise_id"]
    jwt_key_id = secret["box_jwt_key_id"]
    rsa_private_key_data = secret["box_rsa_private_key_data"]
    rsa_private_key_passphrase = secret["box_rsa_private_key_passphrase"]
    webhook_signature_key = secret["box_webhook_signature_key"]

    auth = JWTAuth(
        client_id=client_id,
        client_secret=client_secret,
        enterprise_id=enterprise_id,
        jwt_key_id=jwt_key_id,
        rsa_private_key_data=rsa_private_key_data,
        rsa_private_key_passphrase=rsa_private_key_passphrase,
    )
    auth.authenticate_instance()

    client = Client(auth)

    users = client.users()
    try:
        app_user = users.next()
    except StopIteration:
        LOGGER.warning(
            "no app user exists, so the service account will be used as the box api client"
        )
        return client, webhook_key

    app_client = client.as_user(app_user)

    return app_client, webhook_signature_key
Exemplo n.º 2
0
def upload():
    auth = JWTAuth(client_id='t7o9oknjyfmavpz2vq8qyeh2tq3bgwkc',
                   client_secret='tYjGJzz1iMiPA2JBW6csMyAFEXPrUj2c',
                   enterprise_id='511092066',
                   jwt_key_id='u4zebqgi',
                   rsa_private_key_file_sys_path='private.pem')

    access_token = auth.authenticate_instance()

    client = Client(auth)

    user_to_impersonate = client.user(user_id='13315944066')
    client = client.as_user(user_to_impersonate)

    user = client.user().get()
    print('The current user ID is {0}'.format(user.id))

    subfolder = client.folder('0').create_subfolder(str(Supportid))
    print('Created subfolder with ID {0}'.format(subfolder.id))

    cmdfile = client.folder(subfolder.id).upload('specs-cmd.txt')
    print(
        'File "{0}" uploaded to Circuit Technical Spec Storage with file ID {1}'
        .format(cmdfile.name, cmdfile.id))

    psfile = client.folder(subfolder.id).upload('specs-ps.txt')
    print(
        'File "{0}" uploaded to Circuit Technical Spec Storage with file ID {1}'
        .format(psfile.name, psfile.id))
    pass
Exemplo n.º 3
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)
Exemplo n.º 4
0
class BoxHelper:
    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 getFullList(self):
        items = self.music_folder.get_items()
        with open("lista.csv", 'w') as f:
            for item in items:
                if item.type == "file":
                    f.write(item.name + ";" + item.id + "\n")
                    #print('{0} {1} is named "{2}"'.format(item.type.capitalize(), item.id, item.name))

    def upload(self, filepath):
        self.update_thread.filepath = filepath
        self.update_thread.start()

    def remove(self, file_id):
        self.user_client.file(file_id=file_id).delete()

    def getEvents(self):
        events = self.user_client.events().get_admin_events(
            created_after='2021-03-01T22:02:24+01:00')
        for event in events['entries']:
            print('Got {0} event that occurred at {1}'.format(
                event.event_type, event.created_at))

    def getMostRecent(self, limit=10):
        items = self.music_folder.get_items(limit=limit,
                                            sort='date',
                                            direction='DESC',
                                            fields=["modified_at", "name"])
        for i, item in enumerate(items):
            if item.type == 'folder':
                continue
            if i > 2:
                break
            print(dir(item.metadata()))
            print('{0} {1} is named "{2}"'.format(item.type.capitalize(),
                                                  item.modified_at, item.name))

    def url(self, file_id):
        return self.user_client.file(file_id).get_download_url()
Exemplo n.º 5
0
def fill_folder_path_map(
    box_client: boxsdk.Client,
    folder_id: str,
    seed_root_folder_id: str,
    box_user: Optional[boxsdk.object.user.User] = None,
    map_key_root: Optional[str] = None,
    folder_path_map: Optional[dict] = None,
):
    if not folder_path_map:
        folder_path_map = dict()

    if box_user:
        folder = box_client.as_user(box_user).folder(folder_id).get()
    else:
        folder = box_client.folder(folder_id).get()

    log.debug(f"got Box folder {folder}")

    if folder_id != seed_root_folder_id:
        folder_name = folder.response_object["name"]

        if map_key_root:
            map_key_root = f"{map_key_root}|{folder_name}"
        else:
            map_key_root = folder_name

        folder_path_map[map_key_root] = folder

        log.debug(
            f"added folder map key {map_key_root} with value {folder_id} to Box folder path id map"
        )

    for folder_item in folder.get_items():
        if folder_item.response_object["type"] == "folder":
            folder_path_map = {
                **folder_path_map,
                **fill_folder_path_map(
                    box_client,
                    folder_item.response_object["id"],
                    seed_root_folder_id,
                    box_user,
                    map_key_root,
                    folder_path_map,
                ),
            }

    return folder_path_map
def create_and_cache_folder(
    box_client: boxsdk.Client,
    folder_path_map: dict,
    parent_folder_id: str,
    folder_name: str,
    folder_map_key: str,
    box_user: Optional[boxsdk.object.user.User],
) -> Dict[str, boxsdk.object.folder.Folder]:
    if box_user:
        folder = (box_client.as_user(box_user).folder(
            parent_folder_id).create_subfolder(folder_name))
    else:
        folder = box_client.folder(parent_folder_id).create_subfolder(
            folder_name)

    log.info(f"created new Box folder {folder} at path {folder_map_key}")
    folder_path_map[folder_map_key] = folder

    return folder_path_map
Exemplo n.º 7
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
Exemplo n.º 8
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'
Exemplo n.º 9
0
def get_client():
    '''
    Returns the client object for running Box commands
    '''
    try:
        auth = JWTAuth(
            client_id = box_config.CLIENT_ID,
            client_secret = box_config.CLIENT_SECRET,
            enterprise_id = box_config.ENTERPRISE_ID,
            jwt_key_id = box_config.JWT_KEY_ID,
            rsa_private_key_file_sys_path = box_config.CERT,
            rsa_private_key_passphrase = box_config.PASSPHRASE
        )
        client= Client(auth)
        #should only be one porter user. only app user in my account
        porter_user = client.users()[0]
        porter_client = client.as_user(porter_user)
    except Exception as e:
        log.info('FAILURE: get_client ')
        log.info(e)
    else:
        log.info('SUCCESS: get_client ')
        return porter_client
Exemplo n.º 10
0
def impersonate_mirror_user(box: BoxClient, login: str) -> BoxClient:
    mirror_user = [x for x in box.users() if x.login == login][0]
    LOG.info("Mirroring user: {}, login: {}".format(mirror_user,
                                                    mirror_user.login))
    return box.as_user(mirror_user)
Exemplo n.º 11
0
from flask import Flask
import config_jwt
import requests
import logging

app = Flask(__name__)

# Configure JWT auth and fetch access token
auth = JWTAuth(
  client_id=config_jwt.client_id,
  client_secret=config_jwt.client_secret,
  enterprise_id=config_jwt.enterprise_id,
  jwt_key_id=config_jwt.jwt_key_id,
  rsa_private_key_file_sys_path=config_jwt.private_key_path,
  rsa_private_key_passphrase=config_jwt.private_key_passphrase
)
access_token = auth.authenticate_instance()

BOX_USER_NAME = config_jwt.user_name
FOLDER_ID = config_jwt.folder_id

client = Client(auth)

users = client.users(filter_term=BOX_USER_NAME)
box_user = users[0] if users else client.create_user(BOX_USER_NAME)

root_folder = client.as_user(box_user).folder(folder_id=FOLDER_ID).get()
print 'folder owner: ' + root_folder.owned_by['login']
print 'folder name: ' + root_folder['name']

client.as_user(box_user).folder(folder_id=FOLDER_ID).rename('Tax Rename')
Exemplo n.º 12
0
from boxsdk import JWTAuth, Client

# Get config.json from box.com dev console
config = JWTAuth.from_settings_file('config.json')

client = Client(config)

user_to_impersonate = client.user(user_id='12687310242')
user_client = client.as_user(user_to_impersonate)


def upload_large_file(file, size):
    print("sdk_jwt")
    file_size = size
    upload_session = client.as_user(user_to_impersonate).folder(
        '112221918845').create_upload_session(file_size, file.filename)
    print('Created upload session {0} with chunk size of {1} bytes'.format(
        upload_session.id, upload_session.part_size))

    chunked_uploader = upload_session.get_chunked_uploader(file, file_size)
    uploaded_file = chunked_uploader.start()
    print('File "{0}" uploaded to Box with file ID {1}'.format(
        uploaded_file.name, uploaded_file.id))
    print(uploaded_file)
    return "done"

    # To commit the file - looks like it's not needed
    # print(chunked_uploader)
    # sha1 = hashlib.sha1()
    # file_attributes = {
    #     "description": "File has been uploaded via Chunked Upload"