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
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
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 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(): 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 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 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_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 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 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)
from boxsdk import Client from StringIO import StringIO from boxsdk.object.collaboration import CollaborationRole from boxsdk.exception import BoxAPIException import os auth = JWTAuth( client_id='00000000', client_secret='00000000', enterprise_id='00000000', jwt_key_id='00000000', rsa_private_key_file_sys_path='loans/private_key.pem', rsa_private_key_passphrase='00000000', ) access_token = auth.authenticate_instance() client = Client(auth) ned_stark_user = client.create_user('Phillip Fry') ned_auth = JWTAuth( client_id='00000000', client_secret='00000000', enterprise_id='00000000', jwt_key_id='00000000', rsa_private_key_file_sys_path='loans/private_key.pem', rsa_private_key_passphrase='00000000', ) ned_auth.authenticate_app_user(ned_stark_user) ned_client = Client(ned_auth)
def pull(): # initialize paths for config file private_path = Path(__file__).resolve().parent config_path = private_path / "config.json" key_path = private_path / "private.pem" print('keypath = ' + str(key_path)) print('config = ' + str(config_path)) print('private = ' + str(private_path)) with config_path.open() as f: config = json.load(f) # initialize client variables from config tokens client_id = config["clientID"] client_secret = config["clientSecret"] enterprise_id = config["enterpriseID"] # initialize a new client auth = JWTAuth(client_id=client_id, client_secret=client_secret, enterprise_id=enterprise_id, jwt_key_id='0l74oi4p', rsa_private_key_file_sys_path="private.pem") access_token = auth.authenticate_instance() client = Client(auth) me = client.user(user_id='me').get() folderId = config["folderId"] # id of box folder to sync with # returns a list of all items inside box folder itemsToSync = client.folder(folder_id=folderId).get_items(limit=100, offset=0) # create a list of file names to parse and id number to identify and pull data nameList = [] idList = [] # counter variables i = 0 while i < len(itemsToSync): s = str(itemsToSync[i]) name = str(re.search('\(([^)]+)', s).group(1)) idNum = re.findall(r'\d{12}', s) # finds string of 12 digits as file id number # only searches for .png types # saves name and id number to separate lists if name.endswith('.png') or name.endswith('.jpg') or name.endswith( '.jpeg'): idList.append(idNum) nameList.append(name) else: pass i += 1 j = 0 destinationPath = config["destinationPath"] # path files will be saved to timelogPath = config["timelogPath"] now = datetime.datetime.now() # get current timestamp strNow = now.strftime("%Y-%m-%d %H:%M:%S") while j < len(nameList): print nameList[j] print idList[j] completeName = os.path.join( destinationPath, nameList[j]) # concatenates destination with name of file idNum = ''.join( idList[j]) # parses id number to be pulled from box folder filecontent = client.file( file_id=idNum).content() # saves file content as variable newfile = open(completeName, 'w') newfile.write(filecontent) newfile.close() j += 1 with open(timelogPath, "a") as f: # logs sync date and time in timelog.txt f.write("Last box sync at " + strNow + "\n")
def get_box_client(plaintext: str) -> BoxClient: auth_args = json_config_to_jwtauth(plaintext) auth = JWTAuth(**auth_args) access_token = auth.authenticate_instance() return BoxClient(auth)
# 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)