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
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
def get_box_client(): """BoxSDKの初期化 """ secret = get_secret() client_id = secret["boxAppSettings"]["clientID"] client_secret = secret["boxAppSettings"]["clientSecret"] jwt_key_id = secret["boxAppSettings"]["appAuth"]["publicKeyID"] rsa_private_key_data = secret["boxAppSettings"]["appAuth"]["privateKey"] rsa_private_key_passphrase = secret["boxAppSettings"]["appAuth"]["passphrase"] enterprise_id = secret["enterpriseID"] webhook_signature_key = secret["webhookPrimaryKey"] auth = JWTAuth( client_id=client_id, client_secret=client_secret, jwt_key_id=jwt_key_id, rsa_private_key_data=rsa_private_key_data, rsa_private_key_passphrase=rsa_private_key_passphrase, enterprise_id=enterprise_id ) auth.authenticate_instance() client = Client(auth) return client, webhook_signature_key
class BoxClient(object): def __init__(self): self.client_id = os.environ['BOX_CLIENT_ID'] self.client_secret = os.environ['BOX_CLIENT_SECRET'] self.enterprise_id = os.environ['BOX_ENTERPRISE_ID'] self.rsa_private_key_pass = os.environ['BOX_RSA_PRIVATE_KEY_PASS'] self.rsa_private_key_path = os.environ['BOX_RSA_PRIVATE_KEY_PATH'] self.jwt_key_id = os.environ['BOX_JWT_KEY_ID'] self.folder_id = os.environ['BOX_FOLDER_ID'] self.access_token = None self.refresh_token = None self.client = self.authenticate_box_client() def store_tokens(self, access_token, refresh_token): self.access_token = access_token if refresh_token: self.refresh_token = refresh_token def authenticate_box_client(self): self.auth = JWTAuth( client_id=self.client_id, client_secret=self.client_secret, enterprise_id=self.enterprise_id, jwt_key_id=self.jwt_key_id, rsa_private_key_passphrase=self.rsa_private_key_pass, rsa_private_key_file_sys_path=self.rsa_private_key_path, store_tokens=self.store_tokens) self.auth.authenticate_instance() return Client(self.auth) def upload(self, stream, filename): self.client.folder(folder_id=self.folder_id).upload_stream( stream, filename)
def user_detail(user_id): print '### Sending detail view ###' client = Client(g.auth, network_layer=customLogger) user = client.user(user_id=user_id).get() # As an admin, we can act on behalf of other users by creating new auth and client objects. # We should also be caching this token. For the purposes of this quickstart # we only cache access for one user (the admin). print "AUTHENTICATING USER: "******" (" + user.name + ")" user_auth = JWTAuth(client_id=app.config['CLIENT_ID'], client_secret=app.config['CLIENT_SECRET'], enterprise_id=app.config['EID'], jwt_key_id=app.config['KEY_ID'], rsa_private_key_file_sys_path=os.path.join(os.path.dirname(__file__),'rsakey.pem')) user_auth.authenticate_app_user(user) # <--- Authenticate as the user user_client = Client(user_auth) # Make API calls as the user by using the user_client object files = user_client.folder(folder_id='0').get_items(limit=100) # Build the preview link into any files sent to the client for f in files: if f._item_type=="file": f.preview_url = f.get(fields=['expiring_embed_link']).expiring_embed_link['url'] token = user_auth.access_token return render_template("user_detail.html", user=user, files_list=files, token=token)
def authenticate_box_client(self): self.auth = JWTAuth( client_id=self.client_id, client_secret=self.client_secret, enterprise_id=self.enterprise_id, jwt_key_id=self.jwt_key_id, rsa_private_key_passphrase=self.rsa_private_key_pass, rsa_private_key_file_sys_path=self.rsa_private_key_path, store_tokens=self.store_tokens) self.auth.authenticate_instance() return Client(self.auth)
def box_auth(user_id): auth = JWTAuth(client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', enterprise_id='YOUR_ENTERPRISE_ID', jwt_key_id='YOUR_JWT_KEY_ID', rsa_private_key_passphrase='RSA_PRIVATE_KEY_PASSPHRASE', rsa_private_key_file_sys_path='PATH_TO_KEY_FILE') access_token = auth.authenticate_instance() client = Client(auth) user = client.user(user_id) return (client, user)
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 __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 authenticate(self): ''' JWT authentication ''' auth = JWTAuth.from_settings_file(self.config_filename) access_token = auth.authenticate_instance() self.client = Client(auth)
def get_conn(self): """ Returns an authentication with app in box. """ try: client = CerberusClient('https://prod.cerberus.nikecloud.com') sdk = JWTAuth( client_id=client.get_secrets_data( "shared/ngap-box/client_id")["client_id"], client_secret=client.get_secrets_data( "shared/ngap-box/client_secret")["client_secret"], enterprise_id=client.get_secrets_data( "shared/ngap-box/enterprise_id")["enterprise_id"], jwt_key_id=client.get_secrets_data( "shared/ngap-box/jwt_key_id")["jwt_key_id"], rsa_private_key_data=((client.get_secrets_data( "shared/ngap-box/boxpemkey")["pemkey"]).replace( '\\n', '\n')), rsa_private_key_passphrase=bytes( (client.get_secrets_data( "shared/ngap-box/rsa_private_key_passphrase") ["rsa_private_key_passphrase"]).encode('utf-8'))) client = Client(sdk) return client except TypeError as e: print(e)
def get_auth(): auth = JWTAuth( client_id='37vdfnknzax5htrkiler5xkphbxs6f4s', client_secret='pMUwYf2g1iAsvFDnCA08ASa1oHwYj3Ut', enterprise_id="849101", jwt_key_id='h4qpyf9b', rsa_private_key_file_sys_path='private_key.pem', rsa_private_key_passphrase=b'datos1234', ) access_token = auth.authenticate_instance() client = Client(auth) print("Upload authenticated successfully") return client
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
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)
def upload_to_box(report_path, deployment): box_auth_string = environment.get_env(environment.BOX_AUTH_JSON) box_auth_json = json.loads(box_auth_string.replace("'", "")) box_sdk = JWTAuth.from_settings_dictionary(box_auth_json) client = BoxClient(box_sdk) file_name = create_file_name(deployment) # Folder id 0 is the root folder box_file = client.folder('0').upload(report_path, file_name) return box_file.get_shared_link(access='open')
def get_box_connection(target_config): from boxsdk import JWTAuth, Client, BoxAPIException # Check to see if we have credentials valid_settings = [] for l in list(target_config.keys()): if target_config[l] is not None: if len(target_config[l]) > 0: valid_settings.append(l) if all(x in valid_settings for x in [ 'client_credential_username', 'client_credential_password', 'enterprise_id', 'public_key_id', 'private_key', 'passphrase_credential_password' ]): try: enterprise_id = target_config['enterprise_id'] client_id = target_config['client_credential_username'] client_secret = target_config['client_credential_password'] public_key_id = target_config['public_key_id'] private_key = target_config['private_key'].replace('\\n', '\n') passphrase = target_config['passphrase_credential_password'] box_authentication = { "enterpriseID": enterprise_id, "boxAppSettings": { "clientID": client_id, "clientSecret": client_secret, "appAuth": { "publicKeyID": public_key_id, "privateKey": private_key, "passphrase": passphrase } } } auth = JWTAuth.from_settings_dictionary(box_authentication) if auth is not None: # Use the credential to connect to Box try: return Client(auth) except BoxAPIException as be: raise Exception("Could not connect to Box: " + be.message) except BaseException as e: raise Exception("Could not connect to Box: " + repr(e)) else: raise Exception("Box credential not configured.") except AttributeError: logger.critical("Error ") raise Exception("Could not connect to Box (AttributeError) ") except BaseException as e: logger.exception("Could not connect to Box: " + repr(e)) raise Exception("Could not connect to Box: " + repr(e)) else: raise Exception("Could not find required configuration settings")
def download_from_box(shared_link, filename, save_path): print("Searching for %s in %s" % (filename, shared_link)) sdk = JWTAuth.from_settings_dictionary({ "boxAppSettings": { "clientID": "ind0ahpt188454gosng4g7ya6l5lmsq1", "clientSecret": "Dk74vXtPYzK4sYwMQh3n90XGwMzdiaH3", "appAuth": { "publicKeyID": "kt1mdzwh", "privateKey": "-----BEGIN ENCRYPTED PRIVATE KEY-----\n" "MIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIAa1gdYCiysUCAggA\n" "MBQGCCqGSIb3DQMHBAjbV5j2FCE5RgSCBMjpKnSsHXzW9S5ivkAgf/3Neg1AJNGu\n" "RFXbcw/iZZMRl+jb5Q6O+eOH9Ofz7okEg3MIHeN0vb5TcDI1VwtBHsdMs9gChKei\n" "K+XrY6g2VWInYprk4egaZHZ89lQl744OEY0o6FRyggQkFX2nfkVevV/UNC4LYM/n\n" "P/0q2AWzSx3Yb9i/aB2xQcQAquGQ3qtZomuJHzghFLioiVDKIyy+Ol2hUdi9VYM9\n" "na8iI5gl9NujcUvVVuD7oH56BzYEC1Rtz+dDIfHEOjM1PollKRSdzVEf93zD90vT\n" "PMVV63gM7dL8qalgJOCNlThld5AHZ5qCXuTdLv5Ly/4/uIztjbj810Uvl2PziXyb\n" "oaP4FEhIu6YNSEPG7hWm4XMKdm2OFZzzPlaBGWpfN5MXhTc1cIvRjqKndAFGThg5\n" "FO+B893ViwyGYBvMPYXvR/8VJaQXkPSbb401x+rt8Xb7CkYFKskRCJYknc9fhPgL\n" "VljSzk2eZMyYYkF1FNjWhe/EmUpnxzW+frqbIOyCM6LNDYr4PdoHG5n2DdwxJQ9L\n" "ClpXaKpFuRAT4nMabkzZk7oyfxeUL1raWk41kBlx2X4XWoWAJcZbqI40qkiWx4Q4\n" "oHhjINH9Vn3r0YbkUh2603QRvNcJ8HQnAaEM+zRQz2M+8NpXqF/4j+sYzEU4pniW\n" "QQRQTDunyBkPNJzL//g1yZONubbHqX28FN6qNdsFxa/HqHHh9hy973KbipaIqkY9\n" "RgAkpnmT1DKLOuh7cxoTxfrJWk3fqxszxakv9vcFBDK9ADA/JSLlnhAkKYI9Wokx\n" "DmdG7f0QnJgHcIXATlLoQeCAh4xG/nIM25EnUty84ojm74odSzv7y0DXUVj4zak2\n" "ZBkd3h52r6ybqSZEKtP3qQzjt6NB/XtjSGM8xl56et5rDqgtrs/+To6GT6qaOLoE\n" "SokrdB+tv+BBrRNXZAoIR3rb6oiOPEoysTEF4HumkWG4RPjigr0jqf3CX97CKpHm\n" "ZQdqzsqK8SM1M1OBXUZdE9cqlEa052o86bp3P0RUUYb9qqxEPScb9qDJGGdhKSLo\n" "VoA2nmADTmisoOWIaytJfSQDyZcGEX/0IJDSWKFOP1kvz8FaopPekY3URxScy5Yb\n" "ge5lAJRX5ZQM7RSV5FoMSGX92E2BOeYLLmWd5WKyw3HIoYC3ScJYZOqJCZl0TeN5\n" "/OGaMFttF3foHb2aiLq7nhPyVajw8B+3DVayCQQLIh0+zAeieke8UaPHnNIcCO9W\n" "ndwtOVXS4KslfxA6EcXK4W5cseJRbGx/8fcUZOwZ+xLN5wcr3jwmHnIivCRU1Fl4\n" "QnBww6jGeiwDntrt3ZeSpB2GYA6NbiBDkzbveLomLX4+Ok0PreuiR5PhhnPK0mLu\n" "GE2R2uEPwfIsHky/UEi8LI3zh3KjrCcHG2Kx89iBXYA+XUmBh+1Oh/t8MR7jYdBN\n" "GO2HG2LIV29koChcNsY/ml2ex/nFO8iMnm8kQCy1bD1If6wApwBeJrFdS9wDkKca\n" "f6EtaG1RLiqhA1iCITLxTE1QxCniirRCyq6UX5EOXQzcQt0bPRlXtcZba9dDn7H0\n" "6WHJ+9LAz8C5lDAY89DRJ1yOxs/AEa/h+yDlhCxg23knNY0rlY4Y0AI4+VoTe0Op\n" "RcE=\n" "-----END ENCRYPTED PRIVATE KEY-----\n", "passphrase": "b6c4dd684581a9ce00dc97abab73357c" } }, "enterpriseID": "197930301" }) client = Client(sdk) root = client.get_shared_item(shared_link) fobj = find(root, filename) if fobj is None: print("File not found: %s" % filename) else: print("Start to download: %s" % filename) output_file = open(join(save_path, filename), 'wb') fobj.download_to(output_file) print("Download done")
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)
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)
def connect_impl(self, creds): log.debug('Connecting to box') if not self.__client or creds != self.__creds: try: if creds: self.__creds = creds else: raise CloudTokenError("no creds") jwt_token = creds.get('jwt_token') access_token = creds.get('access_token') refresh_token = creds.get('refresh_token') if not jwt_token: if not ((self._oauth_config.app_id and self._oauth_config.app_secret) and (refresh_token or access_token)): raise CloudTokenError("require app_id/secret and either access_token or refresh token") with self._mutex: box_session = Session() box_kwargs = box_session.get_constructor_kwargs() box_kwargs["api_config"] = boxsdk.config.API box_kwargs["default_network_request_kwargs"] = {"timeout": 60} if jwt_token: jwt_dict = json.loads(jwt_token) user_id = creds.get('user_id') auth = JWTAuth.from_settings_dictionary(jwt_dict, user=user_id, store_tokens=self._store_refresh_token) else: if not refresh_token: raise CloudTokenError("Missing refresh token") auth = OAuth2(client_id=self._oauth_config.app_id, client_secret=self._oauth_config.app_secret, access_token=access_token, refresh_token=refresh_token, store_tokens=self._store_refresh_token) box_session = AuthorizedSession(auth, **box_kwargs) self.__client = Client(auth, box_session) with self._api(): self.__access_token = auth.access_token self._long_poll_manager.start() except BoxNetworkException as e: log.exception("Error during connect %s", e) self.disconnect() raise CloudDisconnectedError() except (CloudTokenError, CloudDisconnectedError): raise except Exception as e: log.exception("Error during connect %s", e) self.disconnect() raise CloudTokenError() with self._api() as client: return client.user(user_id='me').get().id
def create_user_auth(app_user): app_user_auth = JWTAuth( client_id=settings.box_client_id, client_secret=settings.box_secret, user=app_user, enterprise_id=settings.box_enterprise_id, jwt_key_id=settings.box_jwt_key_id, rsa_private_key_file_sys_path=settings.rsa_private_key_file_sys_path, rsa_private_key_passphrase=settings.rsa_private_key_passphras) print(f"user account - {app_user_auth}") return app_user_auth
def create_service_auth(): service_account_auth = JWTAuth( client_id=settings.box_client_id, client_secret=settings.box_secret, enterprise_id=settings.box_enterprise_id, jwt_key_id=settings.box_jwt_key_id, rsa_private_key_file_sys_path=settings.rsa_private_key_file_sys_path, rsa_private_key_passphrase=settings.rsa_private_key_passphras) print(f"service account - {service_account_auth}") return service_account_auth
def connect(self, params={}): client_id = params.get("client_id") client_secret = params.get("client_secret").get("secretKey") enterprise_id = params.get("enterprise_id") jwt_key_id = params.get("jwt_key_id") password = params.get("rsa_password").get("secretKey").encode() private_key = params.get("private_key").get("secretKey") self.logger.info("Connect: Connecting..") # Fix escaping issues in private_key if "\\n" in private_key: private_key = private_key.replace("\\n", "\n", -1) # Try to connect with the legacy code try: # store private key parsed_private_key = urllib.parse.unquote_plus(private_key) f = tempfile.NamedTemporaryFile("w") f.write(parsed_private_key) f.seek(0) auth = JWTAuth( client_id=client_id, client_secret=client_secret, enterprise_id=enterprise_id, jwt_key_id=jwt_key_id, rsa_private_key_file_sys_path=f.name, store_tokens=self.store_tokens, rsa_private_key_passphrase=password, ) self.box_connection = Client(auth) access_token = auth.authenticate_instance() self.logger.info("Connect: Connection successful") f.close() # if legacy connection fails try to connect with new code except ValueError: # store private key f = tempfile.NamedTemporaryFile("w") f.write(private_key) f.seek(0) auth = JWTAuth( client_id=client_id, client_secret=client_secret, enterprise_id=enterprise_id, jwt_key_id=jwt_key_id, rsa_private_key_file_sys_path=f.name, rsa_private_key_passphrase=password, ) self.box_connection = Client(auth) access_token = auth.authenticate_instance() self.logger.info("Connect: Connection successful") f.close()
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 run(): boxClientId = "" boxClientSecret = "" boxEnterpriseId = "" boxJwtKeyId = "" boxPrivateKeyPath = os.getcwd() + "/" + "CERT.PEM" boxPrivateKeyPassphrase = b"" auth = JWTAuth(client_id=boxClientId, client_secret=boxClientSecret, enterprise_id=boxEnterpriseId, jwt_key_id=boxJwtKeyId, rsa_private_key_file_sys_path=boxPrivateKeyPath, rsa_private_key_passphrase=boxPrivateKeyPassphrase) access_token = auth.authenticate_instance() print(access_token) client = Client(auth) shared_link_url = "https://uc.box.com/v/estests-videos" local_path = "/Users/tylerestes/BoxSync/Media/TEST" download_files(client, shared_link_url, local_path)
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)
def get_box_client() -> Client: # pylint: disable=global-statement global BOX_ACCESS_AGE global BOX_CLIENT if not Client or not JWTAuth: raise Exception('Could not import necessary Box Library.') if BOX_CLIENT is not None and BOX_ACCESS_AGE is not None and datetime.now( ) - BOX_ACCESS_AGE < timedelta(minutes=MAX_BOX_ACCESS_AGE): return BOX_CLIENT response = boto3.client('secretsmanager').get_secret_value( SecretId=BOX_API_ACCESS_NAME) settings = build_jwt_settings(response) BOX_CLIENT = Client(JWTAuth.from_settings_dictionary(settings)) BOX_ACCESS_AGE = datetime.now() return BOX_CLIENT
def check_box_auth(secret): try: JWTAuth( 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"], ).authenticate_instance() except Exception as e: raise RuntimeError( "Box failed to authenticate, check credentials and try again" ) from e
def authorize_jwt_client_json(config, private_key_file): """ Function to obtain an authorised Box API Client using JWT """ if os.path.exists(config): with open(config, 'r') as json_file: config = json.load(json_file) else: raise IOError('Config file not found') jwt_auth = JWTAuth( client_id=config['boxAppSettings']['clientID'], client_secret=config['boxAppSettings']['clientSecret'], enterprise_id=config['enterpriseID'], jwt_key_id=config['boxAppSettings']['appAuth']['publicKeyID'], access_token=None, rsa_private_key_file_sys_path=private_key_file, rsa_private_key_passphrase=str( config['boxAppSettings']['appAuth']['passphrase']).encode('utf_8'), store_tokens=lambda acc, _: store_token(acc, _)) jwt_auth.authenticate_instance() return Client(jwt_auth)
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)
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")
def __init__(self): self._db_engine = sqlalchemy.create_engine('sqlite+pysqlite:///photobooth.db') self._session_maker = sessionmaker(bind=self._db_engine, autoflush=True) self._session = self._session_maker() DeclarativeBase.metadata.create_all(self._db_engine) self._auth = JWTAuth( client_id=self._CLIENT_ID, client_secret=self._CLIENT_SECRET, enterprise_id=self._ENTERPRISE_ID, rsa_private_key_file_sys_path='private_key.pem', rsa_private_key_passphrase=self._PASSPHRASE, ) self._client = Client(self._auth) try: user_id = self._session.query(PhotoBoothInfo).filter_by(key='user_id').one().value from boxsdk.object.user import User self._upload_user = User(None, user_id) except NoResultFound: self._upload_user = self._client.create_user('Photobooth Uploader') self._session.add(PhotoBoothInfo(key='user_id', value=self._upload_user.object_id)) self._session.commit() self._uploader_auth = JWTAuth( client_id=self._CLIENT_ID, client_secret=self._CLIENT_SECRET, enterprise_id=self._ENTERPRISE_ID, rsa_private_key_file_sys_path='private_key.pem', rsa_private_key_passphrase=self._PASSPHRASE, ) self._uploader_auth.authenticate_app_user(self._upload_user) self._uploader = Client(self._uploader_auth) try: folder_id = self._session.query(PhotoBoothInfo).filter_by(key='folder_id').one().value self._folder = self._uploader.folder(folder_id) except NoResultFound: self._folder = self._uploader.folder('0').create_subfolder('Photobooth Images') self._session.add(PhotoBoothInfo(key='folder_id', value=self._folder.object_id)) self._session.commit()
class Box(object): _CLIENT_ID = Configuration.CLIENT_ID _CLIENT_SECRET = Configuration.CLIENT_SECRET _ENTERPRISE_ID = Configuration.ENTERPRISE_ID _PASSPHRASE = Configuration.PASSPHRASE def __init__(self): self._db_engine = sqlalchemy.create_engine('sqlite+pysqlite:///photobooth.db') self._session_maker = sessionmaker(bind=self._db_engine, autoflush=True) self._session = self._session_maker() DeclarativeBase.metadata.create_all(self._db_engine) self._auth = JWTAuth( client_id=self._CLIENT_ID, client_secret=self._CLIENT_SECRET, enterprise_id=self._ENTERPRISE_ID, rsa_private_key_file_sys_path='private_key.pem', rsa_private_key_passphrase=self._PASSPHRASE, ) self._client = Client(self._auth) try: user_id = self._session.query(PhotoBoothInfo).filter_by(key='user_id').one().value from boxsdk.object.user import User self._upload_user = User(None, user_id) except NoResultFound: self._upload_user = self._client.create_user('Photobooth Uploader') self._session.add(PhotoBoothInfo(key='user_id', value=self._upload_user.object_id)) self._session.commit() self._uploader_auth = JWTAuth( client_id=self._CLIENT_ID, client_secret=self._CLIENT_SECRET, enterprise_id=self._ENTERPRISE_ID, rsa_private_key_file_sys_path='private_key.pem', rsa_private_key_passphrase=self._PASSPHRASE, ) self._uploader_auth.authenticate_app_user(self._upload_user) self._uploader = Client(self._uploader_auth) try: folder_id = self._session.query(PhotoBoothInfo).filter_by(key='folder_id').one().value self._folder = self._uploader.folder(folder_id) except NoResultFound: self._folder = self._uploader.folder('0').create_subfolder('Photobooth Images') self._session.add(PhotoBoothInfo(key='folder_id', value=self._folder.object_id)) self._session.commit() def upload_photo(self, name, message, photo_sys_path): print 'uploading photo ', photo_sys_path, ' to box' photo = self._folder.upload(photo_sys_path) photo.metadata().create({ 'name': name, 'message': message, }) def download_photo(self, file_id, photo_sys_path): print 'downloading photo ', photo_sys_path, ' from box' with open(photo_sys_path, 'wb') as file_handle: self._client.file(file_id).download_to(file_handle) def list_files(self): return self._folder.get_items(1000)
# Imports the necessary package to perform JWT Authentication from boxsdk import JWTAuth # Creates an auth object auth = JWTAuth( client_id='<my client_id>', client_secret='<my client secret>', enterprise_id='<my enterprise id>', jwt_key_id='<my public key id>', # System path to your private key file. rsa_private_key_file_sys_path='private_key.pem', # The password that the private key was generated with (comment out if none) #rsa_private_key_passphrase='' ) # generate an enterprise token for use with PostMan enterprise_token = auth.authenticate_instance() print enterprise_token; # Imports the package to create an authenticated Client from boxsdk import Client # Creates a client used for performing actions through the API client = Client(auth)