def get_folders(self, **kwargs): folder_id = kwargs.get('folder_id') if folder_id is None: return [{ 'id': '0', 'path': '/', 'addon': 'box', 'kind': 'folder', 'name': '/ (Full Box)', 'urls': { # 'folders': node.api_url_for('box_folder_list', folderId=0), 'folders': api_v2_url('nodes/{}/addons/box/folders/'.format( self.owner._id), params={'id': '0'}) } }] try: Provider(self.external_account).refresh_oauth_key() oauth = OAuth2(client_id=settings.BOX_KEY, client_secret=settings.BOX_SECRET, access_token=self.external_account.oauth_key) client = Client(oauth) except BoxAPIException: raise HTTPError(http_status.HTTP_403_FORBIDDEN) try: metadata = client.folder(folder_id).get() except BoxAPIException: raise HTTPError(http_status.HTTP_404_NOT_FOUND) except MaxRetryError: raise HTTPError(http_status.HTTP_400_BAD_REQUEST) folder_path = '/'.join( [x['name'] for x in metadata['path_collection']['entries']] + [metadata['name']]) return [{ 'addon': 'box', 'kind': 'folder', 'id': item['id'], 'name': item['name'], 'path': os.path.join(folder_path, item['name']).replace('All Files', ''), 'urls': { 'folders': api_v2_url('nodes/{}/addons/box/folders/'.format( self.owner._id), params={'id': item['id']}) } } for item in metadata['item_collection']['entries'] if item['type'] == 'folder']
def initialize_token(request): oauth = OAuth2(client_id=settings.BOX_APP_CLIENT_ID, client_secret=settings.BOX_APP_CLIENT_SECRET) redirect_uri = reverse('box_integration:oauth2_callback') logger.debug(request.build_absolute_uri(redirect_uri)) auth_url, state = oauth.get_authorization_url( request.build_absolute_uri(redirect_uri)) request.session['box'] = {'state': state} return HttpResponseRedirect(auth_url)
def __init__(self): oauth = OAuth2( client_id=config.BOX_CLIENT_ID, client_secret=config.BOX_CLIENT_SECRET, access_token=config.BOX_ACCESS_TOKEN, ) self.client = Client(oauth) self.local_job_saver = LocalJobSaver() self.root_folder = self.client.folder(folder_id='0')
def get_dev_client(self): # Dev access token, active for 1 hour. Get new token here: # https://wustl.app.box.com/developers/console auth = OAuth2( client_id='', client_secret='', access_token='' ) return Client(auth)
def list_all(args, user_integration): #print("LIST") bxc = BOX_Credentials.objects.get(user_integration_id=user_integration) ACCESS_TOKEN = bxc.BOX_ACCESS_TOKEN #print(ACCESS_TOKEN) REFRESH_TOKEN = bxc.BOX_REFRESH_TOKEN #print(REFRESH_TOKEN+" refreshtoken") # Log the token we're using & starting call logging.info('Using Refresh Token: %s' % REFRESH_TOKEN) # Get new access & refresh tokens #print("logged") getTokens = requests.post(oauth2URL, data={ 'grant_type': 'refresh_token', 'refresh_token': REFRESH_TOKEN, 'client_id': clientId, 'client_secret': clientSecret }) #print("GOT TOKENS") # If the above gives a 4XX or 5XX error #getTokens.raise_for_status() # Get the JSON from the above newTokens = getTokens.json() #print("GOT NEW TOKEN") # Get the new access token, valid for 60 minutes accessToken = newTokens['access_token'] refreshToken = newTokens['refresh_token'] # print("New accessToken " + accessToken) # print("New refreshToken " + refreshToken) bxc.BOX_REFRESH_TOKEN = refreshToken bxc.BOX_ACCESS_TOKEN = accessToken bxc.save() # Get the new access token, valid for 60 minutes CLIENT_ID = settings.CLIENT_ID CLIENT_SECRET = settings.CLIENT_SECRET oauth2 = OAuth2(CLIENT_ID, CLIENT_SECRET, access_token=accessToken) #print("listing...") client = Client(oauth2, LoggingNetwork()) items = client.folder(folder_id='0').get_items(limit=1000, offset=0) #print("List of all files and folders\n") attachment = MessageAttachmentsClass() m = MessageClass() x = '' for item in items: field = AttachmentFieldsClass() field.title = item['name'] field.value = item['id'] #print("Name: "+item['name']+" ID: "+item['id']) x = x + "Name: " + item['name'] + " ID: " + item['id'] + "\n" attachment.attach_field(field) m.attach(attachment) return m
def __init__(self, json_event_body): self.request_id = json_event_body['id'] self.skill_id = json_event_body['skill']['id'] self.file_id = json_event_body['source']['id'] self.file_write_token = json_event_body['token']['write'][ 'access_token'] self.file_write_client = Client( OAuth2(self.BOXSDK_CLIENT_ID, self.BOXSDK_CLIENT_SECRET, access_token=self.file_write_token))
def mystuff(): # TODO extract this to a method so all routes can call it oauth = OAuth2( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, access_token=session['access_token'], refresh_token=session['refresh_token'], ) client = Client(oauth) return mystuff_guts(client) + GOHOME
def authenticate(self): print("Using simple authentication method.") print("Will use access_token as " + self.config["access_token"]) print("Will use refresh_token as " + self.config["refresh_token"]) oauth = OAuth2(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, refresh_token=self.config["refresh_token"], access_token=self.config["access_token"], store_tokens=self.store_tokens) return oauth
def get_box_client(self): access_token, refresh_token = self.get_box_access_tokens() oauth = OAuth2(client_id = "nzcw2drgf4qrlhirjcjs0efqt61ilull", client_secret = "3dqQWFx4ei0GMErDZkYFJ7V9t3JAXb63", access_token = access_token, refresh_token = refresh_token, store_tokens = self.store_tokens) return Client(oauth)
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 user_details(args, user_integration): bxc = BOX_Credentials.objects.get(user_integration_id=user_integration) ACCESS_TOKEN = bxc.BOX_ACCESS_TOKEN REFRESH_TOKEN = bxc.BOX_REFRESH_TOKEN bxc = BOX_Credentials.objects.get(user_integration_id=user_integration) ACCESS_TOKEN = bxc.BOX_ACCESS_TOKEN #print(ACCESS_TOKEN) REFRESH_TOKEN = bxc.BOX_REFRESH_TOKEN #print(REFRESH_TOKEN + " refreshtoken") # Log the token we're using & starting call logging.info('Using Refresh Token: %s' % REFRESH_TOKEN) # Get new access & refresh tokens getTokens = requests.post(oauth2URL, data={ 'grant_type': 'refresh_token', 'refresh_token': REFRESH_TOKEN, 'client_id': clientId, 'client_secret': clientSecret }) # If the above gives a 4XX or 5XX error # getTokens.raise_for_status() # Get the JSON from the above newTokens = getTokens.json() # Get the new access token, valid for 60 minutes accessToken = newTokens['access_token'] refreshToken = newTokens['refresh_token'] #print("New accessToken " + accessToken) #print("New refreshToken " + refreshToken) bxc.BOX_REFRESH_TOKEN = refreshToken bxc.BOX_ACCESS_TOKEN = accessToken bxc.save() CLIENT_ID = settings.CLIENT_ID CLIENT_SECRET = settings.CLIENT_SECRET oauth2 = OAuth2(CLIENT_ID, CLIENT_SECRET, access_token=accessToken) attachment = MessageAttachmentsClass() client = Client(oauth2, LoggingNetwork()) items = client.folder(folder_id='0').get_items(limit=1000, offset=0) # print("List of all files and folders\n") m = MessageClass() #print("The users are:\n") my = client.user(user_id='me').get() field = AttachmentFieldsClass() field.title = "LOGIN ID" field.value = my['login'] attachment.attach_field(field) m.attach(attachment) #print(my) return m
def main(): oauth = OAuth2( client_id='<CLIENT_ID>', client_secret='<CLIENT_SECRET>', access_token='<ACCESS_TOKEN>'# manual input ) client = Client(oauth=oauth) box_contentlists = client.folder('0').get_items(100, 0, None) print(box_contentlists) return (box_contentlists)
def whoami(): # TODO extract this to a method so all routes can call it # IDEA flask has a 'run-method-pre-this-route' annotation... oauth = OAuth2( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, access_token=session['access_token'], refresh_token=session['refresh_token'], ) client = Client(oauth) return whoami_guts(client) + GOHOME
def boot(self, credentials): with open(os.path.join(credentials, 'credentials.txt')) as file: self.account = file.readline() # build credentials oauth = OAuth2( client_id='x5jgd9owo4utthuk6vz0qxu3ejxv2drz', client_secret='icDxjMAFSuERimeonuwQEiutp696b2wb', store_tokens=self.store_tokens, access_token=keyring.get_password('Box_Auth', self.account), refresh_token=keyring.get_password('Box_Refresh', self.account)) return oauth
def __init__(self): self.client = None self.refresh_token = None self.authorization_url = None self.authorization_code = None self.access_token = None self.user = None self.oauth = OAuth2(client_id=config['the_box']['client_id'], client_secret=config['the_box']['client_secret']) self.redirect_url = config['redirect']['url'] self.root_directory = config['the_box']['root_directory']
def get_oauth(cls): """ Creates an Oauth object :return: oauth object. :rtype: :class:`boxsdk.Oauth2` """ box_token = REDIS_DB.hgetall('box') if 'accessToken' in box_token.keys(): oauth = OAuth2(client_id=BOX_CLIENT_ID, client_secret=BOX_CLIENT_SECRET, store_tokens=cls._store_tokens, access_token=box_token['accessToken'], refresh_token=box_token['refreshToken']) else: oauth = OAuth2(client_id=BOX_CLIENT_ID, client_secret=BOX_CLIENT_SECRET, store_tokens=cls._store_tokens) return oauth
def connect(self, token: str) -> 'Client': """Connect to box using a bearer token Args: token: The bearer token to use for this connection """ if self.config['storage'] == 'box': auth = OAuth2(None, None, access_token=token) return Client(auth) else: raise Exception('Invalid Storage Option: ' + self.config['storage'])
def get_items_in_Box_folder(self, box_folder=None): oauth2 = OAuth2(self.clientId, self.clientSecret, access_token=self.accessToken) client = Client(oauth2) my = client.user(user_id='me').get() if box_folder is None: target_folder = client.folder(self.box_folder_id) else: target_folder = client.folder(box_folder) items_in_Box_folder = target_folder.get_items(limit=None, offset=0) return items_in_Box_folder
def add_api(self): #App key and secret CLIENT_ID = '' CLIENT_SECRET = '' #Start a temporary server to catch the GET request when the URL redirects to the localhost. class StoppableWSGIServer(bottle.ServerAdapter): def __init__(self, *args, **kwargs): super(StoppableWSGIServer, self).__init__(*args, **kwargs) self._server = None def run(self, app): server_cls = self.options.get('server_class', WSGIServer) handler_cls = self.options.get('handler_class', WSGIRequestHandler) self._server = make_server(self.host, self.port, app, server_cls, handler_cls) self._server.serve_forever() def stop(self): self._server.shutdown() auth_code = {} auth_code_is_available = Event() local_oauth_redirect = bottle.Bottle() @local_oauth_redirect.get('/') def get_token(): auth_code['auth_code'] = bottle.request.query.code auth_code['state'] = bottle.request.query.state auth_code_is_available.set() local_server = StoppableWSGIServer(host='localhost', port=8080) server_thread = Thread( target=lambda: local_oauth_redirect.run(server=local_server)) server_thread.start() oauth = OAuth2( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, ) auth_url, csrf_token = oauth.get_authorization_url( 'http://localhost:8080') webbrowser.open(auth_url) auth_code_is_available.wait() local_server.stop() #If the CSRF matches, finish the authorization and save the access_token. assert auth_code['state'] == csrf_token access_token, refresh_token = oauth.authenticate( auth_code['auth_code']) #Return the client to use in the future. return Client(oauth)
def downloadPatientDataFromBox(pList, config): auth = OAuth2(client_id=config['boxKeys']['CLIENT_ID'], client_secret=config['boxKeys']['CLIENT_SECRET'], access_token=config['boxKeys']['CLIENT_ACCESS_TOKEN']) client = Client(auth) for ptID in pList: npdh.NPdownloadNewBoxData(ptID, config, client) return
def create_Box_folder(self, box_folder, folder_array): oauth2 = OAuth2(self.clientId, self.clientSecret, access_token=self.accessToken) client = Client(oauth2) my = client.user(user_id='me').get() target_folder = client.folder(box_folder) if isinstance(folder_array, str): target_folder.create_subfolder(folder_array) else: for folder in folder_array: target_folder.create_subfolder(folder)
def main(): """ Dictates what is to be done for the current process. Current steps: -Connect to s3 and download specified files to tempdir -Generate Refresh token and store in logs -Retrieve token from logs and authenticate -Process files by renaming them -Upload files to Box -Remove the locally stored files """ downloadFilesFromS3(files_to_download_array=files_to_download, s3Bucket_name=bucket_name) accessToken = str(getToken()) oauth2 = OAuth2(clientId, clientSecret, access_token=accessToken) client = Client(oauth2) my = client.user(user_id='me').get() print('connected to Box as ' + my.login) target_folder = client.folder(box_folder_id) # target_folder = client.folder('0') target_folder_info = target_folder.get() items_in_Box_folder = target_folder.get_items(limit=None, offset=0) # Grab all of the files in the temp dir files = listdir(temp_file_dir) files_to_download_set = set(files_to_download) # Start to upload the files to Box print('uploading files to folder - ' + target_folder_info.name) upload_array = [] for filename in files: # Check to see if the file is one that exists in files_to_download if filename in files_to_download_set: filename_path = temp_file_dir + filename # Drop the 000's from the end of the filename new_filename = filename[:-3] rename(filename_path, temp_file_dir + new_filename) # Check the Box folder to see if the files exist for item in items_in_Box_folder: # If the file does already exist, use update_contents if item.name == new_filename: box_file = item.update_contents(filename_path[:-3]) print(item.name + ' updated') upload_array.append(new_filename) break # If the file did not exist, use upload if new_filename not in set(upload_array): box_file = target_folder.upload(filename_path[:-3], new_filename) print(new_filename + ' uploaded') os.remove(temp_file_dir + new_filename) print('all files uploaded')
def authenticate(self): class StoppableWSGIServer(bottle.ServerAdapter): def __init__(self, *args, **kwargs): super(StoppableWSGIServer, self).__init__(*args, **kwargs) self._server = None def run(self, app): server_cls = self.options.get('server_class', WSGIServer) handler_cls = self.options.get('handler_class', WSGIRequestHandler) self._server = make_server(self.host, self.port, app, server_cls, handler_cls) self._server.serve_forever() def stop(self): self._server.shutdown() auth_code = {} auth_code_is_available = Event() local_oauth_redirect = bottle.Bottle() @local_oauth_redirect.get('/') def get_token(): auth_code['auth_code'] = bottle.request.query.code auth_code['state'] = bottle.request.query.state auth_code_is_available.set() local_server = StoppableWSGIServer(host='localhost', port=8080) server_thread = Thread( target=lambda: local_oauth_redirect.run(server=local_server)) server_thread.start() oauth = OAuth2( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, ) auth_url, csrf_token = oauth.get_authorization_url( 'http://localhost:8080') webbrowser.open(auth_url) auth_code_is_available.wait() local_server.stop() assert auth_code['state'] == csrf_token access_token, refresh_token = oauth.authenticate( auth_code['auth_code']) print("Will use access_token as " + self.config["access_token"]) print("Will use refresh_token as " + self.config["refresh_token"]) self.config["access_token"] = access_token self.config["refresh_token"] = refresh_token return oauth
def create_session(config_file): """Authenticates to the Box API and creates a client session. Docs: https://developer.box.com/ Parameters ---------- config_file : str Path to the configuration file containing the Box API client id, client secret, and access token. Returns ------- client : boxsdk.client.client.Client object Box API client session associated with authentication credentials. Example ------- >>> >>> >>> >>> """ # Read Box application info from text file if os.path.exists(config_file): with open(config_file, "r") as app_cfg: CLIENT_ID = app_cfg.readline().rstrip("\n") CLIENT_SECRET = app_cfg.readline().rstrip("\n") ACCESS_TOKEN = app_cfg.readline().rstrip("\n") # Authenticate to the Box API auth = OAuth2( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, ) # Create client session client = Client(auth) # Get user user = client.user().get() print((f"Authenticated to Box API with user {user.name} and created a" "client session.")) else: print("Could not find configuration file.") client = None return client
def authorize_with_oauth2(): """ Uses a developer token to authenticate the app.""" credentials = get_credentials() client_id = credentials['clientID'] client_secret = credentials['clientSecret'] auth = OAuth2( client_id = client_id, client_secret = client_secret, access_token = DEVELOPER_TOKEN ) return auth
def get_client(): oauth = OAuth2( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, store_tokens=save_tokens, ) auth_url, csrf_token = oauth.get_authorization_url("https://epignatelli.com") auth_code = input("Application requires authorization. Visit {} and paste the part of the url after '&code':\n".format(auth_url)) auth_code = str(auth_code) access_token, refresh_token = oauth.authenticate(auth_code) save_tokens(access_token, refresh_token) oauth = OAuth2( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, access_token=access_token, refresh_token=refresh_token, ) client = Client(oauth) return client
def box_client(): config = _config_get() if config.get('box_refresh_token') and config.get('box_access_token'): oauth = OAuth2( client_id=config.get('box_client_ID'), client_secret=config.get('box_client_secret'), store_tokens=_store_tokens, access_token=config.get('box_access_token'), refresh_token=config.get('box_refresh_token'), ) else: oauth = _oauth_flow() return Client(oauth)
def __init__(self, credential_dir, credential_filename=CREDENTIAL_FILENAME): super(BoxAPI, self).__init__(credential_dir) self.auth_file = join(credential_dir, credential_filename) self.oauth = OAuth2(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, store_tokens=self.write_access_token) try: self.get_tokens_from_file() self.authorize() except IOError: pass
def authorize_box_client(self): print(LOG_PREFIX, 'Box Client 設定中') try: config = json.load(open(CONFIG_PATH)) appAuth = config["boxAppSettings"]["appAuth"] privateKey = appAuth["privateKey"] passphrase = appAuth["passphrase"] key = load_pem_private_key( data=privateKey.encode('utf8'), password=passphrase.encode('utf8'), backend=default_backend(), ) AUTHENTICATE_URL = 'https://api.box.com/oauth2/token' claims = { 'iss': config['boxAppSettings']['clientID'], 'sub': '8808713318', 'box_sub_type': 'user', 'aud': AUTHENTICATE_URL, 'jti': secrets.token_hex(64), 'exp': round(time.time()) + 45 } keyId = config['boxAppSettings']['appAuth']['publicKeyID'] assertion = jwt.encode(claims, key, algorithm='RS512', headers={ 'kid': keyId }) params = { 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion': assertion, 'client_id': config['boxAppSettings']['clientID'], 'client_secret': config['boxAppSettings']['clientSecret'] } response = requests.post(AUTHENTICATE_URL, params) access_token = response.json()['access_token'] auth = OAuth2( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', access_token= access_token, ) client = Client(auth) return client except Exception as ex: print('ERR MSG: {}',format(ex))
def main(args): settings = config.load_settings( Path.home().joinpath(args.config) if Path.home().joinpath(args.config). exists() else Path(__file__).parent.joinpath(args.config)) # connect (this can fail if access token) oauth = OAuth2(client_id=settings['client_id'], client_secret=settings['client_secret'], access_token=settings['access_token']) client = DeveloperTokenClient(oauth) my = client.user(user_id='me').get() #print(my) boxgetfile(args.input, args.output, client)