def get_oauth(cid, cs, *args): if (not args): # print("get_oauth. no access token or refresh token, only have cid,cs") oauth = OAuth2( client_id=cid, client_secret=cs, store_tokens=save_tokens, ) auth_url, csrf_token = oauth.get_authorization_url('https://localhost') print("LINK:\n " + auth_url) auth_code = input("\nCopy/paste your auth code: ") access_token, refresh_token = oauth.authenticate(auth_code) else: access_token = args[0] refresh_token = args[1] # print("get_oauth. reusing access_token: " + access_token + ", rt: " # + refresh_token) oauth = OAuth2( client_id=cid, client_secret=cs, access_token=access_token, refresh_token=refresh_token, store_tokens=save_tokens, ) return oauth
def authenticate(): if os.path.exists(_tokens_file): tokens = json.load(open(_tokens_file, 'r')) oauth = OAuth2( client_id=config.client_id, client_secret=config.client_secret, store_tokens=store_tokens, access_token=tokens['access_token'], refresh_token=tokens['refresh_token'], ) else: oauth = OAuth2( client_id=config.client_id, client_secret=config.client_secret, store_tokens=store_tokens, ) auth_url, csrf_token = oauth.get_authorization_url(redirect_server.url) print("Access " + auth_url + " and authorize.") auth_code = redirect_server.run() if auth_code == "": print("Aborted.") sys.exit(1) access_token, refresh_token = oauth.authenticate(auth_code) store_tokens(access_token, refresh_token) return oauth
def authorize_with_login() -> OAuth2: credentials = get_credentials() redirect_url = "https://migsapp.com/auth" client_id = credentials['clientID'] client_secret = credentials['clientSecret'] if not TOKEN_STORAGE.exists(): authorization = OAuth2( client_id = client_id, client_secret = client_secret, store_tokens = store_tokens ) auth_request_url, csrf_token = authorization.get_authorization_url(redirect_url) print("Enter this URL into a browser to authorize the app.") print(auth_request_url) access_code_url = input("Please enter the access code url: ") parameters = parse_url(access_code_url) access_code = parameters['code'] access_token, refresh_token = authorization.authenticate(access_code) #store_tokens(access_code, access_token, refresh_token) else: token_data = json.loads(TOKEN_STORAGE.read_text()) authorization = OAuth2( client_id = client_id, client_secret = client_secret, store_tokens = store_tokens, access_token = token_data['accessToken'], refresh_token = token_data['refreshToken'] ) authorization.refresh(token_data['accessToken']) return authorization
def auth(): # Read app info from text file try: with open('app.cfg', 'r') as app_cfg: client = app_cfg.readline().strip() secret = app_cfg.readline().strip() redir_uri = app_cfg.readline().strip() except: print 'Unable to read app.cfg file' sys.exit(1) if DEBUG: print 'clientID {0} sec {1} redir {2}'.format(client, secret, redir_uri) data = get_tokens( ) #checks of TOKENS is available and reads from there if so if data is not None: access_token = data['access_token'] refresh_token = data['refresh_token'] if DEBUG: print 'tokens: acc {0} ref {1}'.format(access_token, refresh_token) oauth = OAuth2( client_id=client, client_secret=secret, access_token=access_token, refresh_token=refresh_token, store_tokens=store_tokens, #this stores tokens back in TOKENS ) else: #create oauth from client, secret oauth = OAuth2( client_id=client, client_secret=secret, store_tokens=store_tokens, #this stores tokens back in TOKENS ) auth_url, csrf_token = oauth.get_authorization_url(redir_uri) print 'Cut/Paste this URI into the URL box in \ \na browser window and press enter:\n\n{0}\n'.format(auth_url) print 'You should login and authorize use of your account by this app' print 'You will then ultimately be redirected to a URL and a page \ that says "Connection Refused"' auth_code = raw_input('Type in the code that appears after \ "code="\nin the URL box in your browser window, and press enter: ') csrf_returned = raw_input('Type in the csrf in the URI: ') assert csrf_returned == csrf_token access_token, refresh_token = oauth.authenticate(auth_code) return oauth
def accessUploadFolder(year=2020): # Define client ID, client secret, and developer token.path = os.path.join(*[os.path.dirname(os.path.abspath(__file__)),"instance"]) # Read app info from text file config = ConfigObject( os.path.join(*[ os.path.dirname(os.path.abspath(__file__)), "instance", 'Boxapp.cfg' ])) CLIENT_ID = config['client_id'] CLIENT_FOLDER = config['client_folder' + str(year)] ACCESS_TOKEN = config['access_token'] # Create OAuth2 object. auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token=ACCESS_TOKEN) # Create the authenticated client client = Client(auth) # make sure we connected try: my = client.user(user_id='me').get() print(my.name) # developer name tied to the token except: sys.exit("ERROR: Invalid access token; try re-generating an " "access token from the app console on the web.") tfolder = client.folder(CLIENT_FOLDER) # 2020 scada data folder return tfolder
def get_fund_materials(): #authentication #link to get Box developer token: https://app.box.com/developers/console/app/524950/configuration dev_token = str(raw_input("Developer token: ")) oauth = OAuth2( client_id='l91tu18y9v1t9yth4w3xub87jbyln18k', client_secret='BYSJR7wr4Tl7Socbw3l87FYK01OOE91r', access_token=dev_token, ) #go to fund folder client = Client(oauth) root_folder = client.folder(folder_id='0') USIT_folder = root_folder.get_items(limit=100, offset=0)[0] fund_folder = USIT_folder.get_items(limit=100, offset=0)[1] #adds files in each fund folder to the database for item in fund_folder.get_items(limit=100, offset=0): folder_name = item.get()['name'] #print folder_name for file in item.get_items(limit=100, offset=0): try: download_url = file.get_shared_link_download_url() file_name = file.get()['name'] code = download_url.split("/static/")[1].split(".")[0] file_url = "https://app.box.com/embed/s/" + code print(file_url) file = FundFile(name = file_name, filePath=file_url, owner='Box', fund= folder_name) db.session.add(file) db.session.commit() print("I added " + file_name + " to the database!") except: print("Cannot add file!")
def get_ag_materials(): dev_token = str(raw_input("Developer token: ")) oauth = OAuth2( client_id='l91tu18y9v1t9yth4w3xub87jbyln18k', client_secret='BYSJR7wr4Tl7Socbw3l87FYK01OOE91r', access_token=dev_token ) client = Client(oauth) root_folder = client.folder(folder_id='0') USIT_folder = root_folder.get_items(limit=100, offset=0)[0] # for item in USIT_folder.get_items(limit=100, offset=0): # print item.get()['name'] ag_folder = USIT_folder.get_items(limit=100, offset=0)[0] for item in ag_folder.get_items(limit=100, offset=0): try: file_name = item.get()['name'] download_url = item.get_shared_link_download_url() code = download_url.split("/static/")[1].split(".")[0] file_url = "https://app.box.com/embed/s/" + code # print(file_url) file = AnalystFile(name = file_name, filePath = file_url, owner = 'Box') db.session.add(file) db.session.commit() print("I added " + file_name + " to the database!") except: print("Cannot add file!")
def get_authenticated_client(): """Returns an authenticated box client""" CLIENT_ID = None CLIENT_SECRET = None ACCESS_TOKEN = None # client and secret are in a config file with open('auth.cfg', 'r') as auth_cfg: # 100% guaranteed unhackable aes = AESDecrypt( base64.b64decode(codecs.decode('o2WzqKAwLKEco24u', 'rot_13')).decode('utf-8')) CLIENT_ID = aes.decrypt(auth_cfg.readline().strip()) CLIENT_SECRET = aes.decrypt(auth_cfg.readline().strip()) oauth = OAuth2(CLIENT_ID, CLIENT_SECRET) auth_url, csrf_token = oauth.get_authorization_url( "https://iastateboxbackup") # ask user to go to the url and authorize our app print("Please go to " + auth_url + " in your web browser.\n\n" + " You will be asked to authorize this app." + " Once you have done so you will be redirected to an invalid" + " webpage. Go to the address bar in your browser and copy" + " the string of random letters and numbers after 'code='" + " this is your access token. You will need to paste this" + " token here within 30 seconds.") ACCESS_TOKEN = input("Please paste your acccess token here:") access_token, refresh_token = oauth.authenticate(ACCESS_TOKEN) client = Client(oauth) return client
def _authenticate(force_reset=False, logger=None): # Config setup cfg = configparser.ConfigParser() cfg.read(CONFIG_FILE) # Verify if there is a valid token already if 'app_info' in cfg and not force_reset: if logger: logger.info('Using existing credentials') client = Client(OAuth2( client_id=cfg['client_info']['client_id'], client_secret=cfg['client_info']['client_secret'], access_token=cfg['app_info']['access_token'], refresh_token=cfg['app_info']['refresh_token'])) try: # Make a request to check it's authenticated if logger: logger.info('Testing existing connection') client.user(user_id='me').get() except exception.BoxOAuthException: if logger: logger.info('Resetting connection to Box') return _reset_authentication(cfg=cfg, logger=logger) return client return _reset_authentication(cfg=cfg, logger=logger)
def __init__(self, root, config, client): """ :param root: the root path for this provider :param config: the dict of the configuration of the object :param plugin_config: contains the plugin settings """ if len(root) > 0 and root[0] == '/': root = root[1:] self.root = root self.connection = client.get("box_com_connection") self.access_token = self.connection['access_token'] self.cache_enabled = config.get("cache_enabled") if self.cache_enabled: cache_file_name = hashlib.sha1(self.access_token.encode('utf-8')).hexdigest() else: cache_file_name = None auth = OAuth2( client_id="", client_secret="", access_token=self.access_token ) main_session = AuthorizedSession(auth, network_layer=LessVerboseLoggingNetwork()) self.client = Client(auth, main_session) self.user = self.client.user().get() self.box_item = BoxItem(cache_file_name, root, self.client) self.box_item.check_path_format(get_normalized_path(root))
def run(): oauth = OAuth2(client_id=None, client_secret=None, access_token="") client = Client(oauth) 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 _folder_data(self, folder_id): # Split out from set_folder for ease of testing, due to # outgoing requests. Should only be called by set_folder try: Provider(self.external_account).refresh_oauth_key(force=True) except InvalidGrantError: raise exceptions.InvalidAuthError() try: oauth = OAuth2(client_id=settings.BOX_KEY, client_secret=settings.BOX_SECRET, access_token=ensure_str( self.external_account.oauth_key)) client = Client(oauth) folder_data = client.folder(self.folder_id).get() except BoxAPIException: raise exceptions.InvalidFolderError() folder_name = folder_data['name'].replace('All Files', '') or '/ (Full Box)' folder_path = '/'.join([ x['name'] for x in folder_data['path_collection']['entries'] if x['name'] ] + [folder_data['name']]).replace('All Files', '') or '/' return folder_name, folder_path
def download_from_box(self, files_to_download, box_folder=None, use_dl_links=False): """ Downloads a list of files from a specified Box folder Optionally, you can simply grab the download link to send to another user """ oauth2 = OAuth2(self.clientId, self.clientSecret, access_token=self.accessToken) client = Client(oauth2) my = client.user(user_id='me').get() print('connected to Box as ' + my.login) if box_folder is None: target_folder = client.folder(self.box_folder_id) else: target_folder = client.folder(box_folder) if use_dl_links is True: link_array = [] target_folder_info = target_folder.get() items_in_Box_folder = target_folder.get_items(limit=None, offset=0) for file_name in files_to_download: # 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 == file_name and use_dl_links is False: with open(self.temp_file_dir + file_name, 'wb') as f: f.write(item.content()) print(file_name + ' downloaded') elif item.name == file_name and use_dl_links is True: box_link = item.get_shared_link_download_url() link_array.append(box_link) if use_dl_links is True: return link_array
def upload_to_box(self, files_to_upload, box_folder=None): """ Uploads a list of files to Box based on the folder id specified when FileMover is initialized """ oauth2 = OAuth2(self.clientId, self.clientSecret, access_token=self.accessToken) client = Client(oauth2) my = client.user(user_id='me').get() print('connected to Box as ' + my.login) if box_folder is None: target_folder = client.folder(self.box_folder_id) else: target_folder = client.folder(box_folder) target_folder_info = target_folder.get() items_in_Box_folder = target_folder.get_items(limit=None, offset=0) for file_name in files_to_upload: # 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 == file_name: box_file = item.update_contents(self.temp_file_dir + file_name) print(item.name + ' updated') break # If the file did not exist, use upload if file_name not in set(files_to_upload): box_file = target_folder.upload(self.temp_file_dir + file_name, file_name) print(file_name + ' uploaded') os.remove(self.temp_file_dir + file_name)
def initializeAPIConnection(): # If there is no configuration file with the previous token info, get the initial values and save them to file if not os.path.isfile(configfile_name): config = SafeConfigParser() if ACCESS_TOKEN is "": print "Initial Tokens not configured" config.add_section('boxCredentials') config.set('boxCredentials', 'clientID', CLIENT_ID) config.set('boxCredentials', 'clientSecret', CLIENT_SECRET) config.set('boxCredentials', 'accessToken', ACCESS_TOKEN) config.set('boxCredentials', 'refreshToken', REFRESH_TOKEN) with open(configfile_name, 'w') as f: config.write(f) # If the configuration file already exists, load the values else: config = SafeConfigParser() config.read(configfile_name) CLIENT_ID = config.get('boxCredentials', 'clientID') CLIENT_SECRET = config.get('boxCredentials', 'clientSecret') ACCESS_TOKEN = config.get('boxCredentials', 'accessToken') REFRESH_TOKEN = config.get('boxCredentials', 'refreshToken') return OAuth2(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN, store_tokens=APIRefreshListener)
def client(self): oauth = OAuth2(client_id=settings.BOX_APP_CLIENT_ID, client_secret=settings.BOX_APP_CLIENT_SECRET, access_token=self.access_token, refresh_token=self.refresh_token, store_tokens=self.update_tokens) return Client(oauth)
def get_box_client(): def list_folder(folder): for item in folder.get_items(): print(item.name, item.id) ## USE developer Token # auth = OAuth2( # client_id=client_id, # client_secret=client_secret, # access_token=developer_token, # ) #client = Client(auth) ## OAuth Login oauth = OAuth2( client_id=client_id, client_secret=client_secret, ) auth_url, csrf_token = oauth.get_authorization_url('http://localhost/') print("Open following url in browser to login Box") print("Copy and Paste Auth Code here, Press ENTER") print( "{}".format(auth_url) ) #http://localhost/?state=box_csrf_token_rbXM8snSTAgQQ8Kq&code=uK3QzvNIE5mA8iWSlxYyc9sYzMOX93vI auth_code = input("Auth Code:\n") access_token, refresh_token = oauth.authenticate(auth_code) client = Client(oauth) user = client.user().get() print('The current user ID is {0}'.format(user.id)) root = client.root_folder() list_folder(root) return client
def push_to_box(folderid, file_path): CLIENT_ID = Config.query.filter_by(key='boxclientid').value(Config.value) CLIENT_SECRET = Config.query.filter_by(key='boxclientsecret').value( Config.value) oauth = OAuth2(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, store_tokens=save_tokens) tokens = read_tokens() at = tokens['access_token'] rt = tokens['refresh_token'] oauth._access_token = at oauth._refresh_token = rt client = Client(oauth) archive = client.folder(folder_id=folderid) try: upload_file = archive.upload(file_path) try: file_url = upload_file.get_shared_link_download_url(access='open') return file_url except Exception as e: flash('Error getting shared link from Box: '.format(Exception), category='danger') return False except Exception as e: flash('Error uploading to Box: '.format(Exception), category='danger') return False
def main(): global client, oauth, verbose #parse command line arguments parser = argparse.ArgumentParser(description="Upload File to box") parser.add_argument("-v", "--verbose", help="activate verbose mode", action='store_true') parser.add_argument("-f", "--file", help="path to upload file", type=str, required=True) args = parser.parse_args(sys.argv[1:]) verbose = args.verbose # read config readCfg() # updtae auth if needed if expireTime < time.time(): refreshAuth() writeCfg() # Autenticate with box oauth = OAuth2(client_id=clientID, client_secret=clientSecret, access_token=accessToken) # Create client client = Client(oauth) # Upload file upload(args.file)
def oauth2_callback(request): auth_code = request.GET.get('code') state = request.GET.get('state') if 'box' in request.session: box = request.session['box'] else: return HttpResponseBadRequest('Unexpected request') if not (state == box['state']): return HttpResponseBadRequest('Request expired') try: oauth = OAuth2(client_id=settings.BOX_APP_CLIENT_ID, client_secret=settings.BOX_APP_CLIENT_SECRET) access_token, refresh_token = oauth.authenticate(auth_code) client = Client(oauth) # save the token box_user = client.user(user_id=u'me').get() token = BoxUserToken( user=request.user, access_token=access_token, refresh_token=refresh_token, box_user_id=box_user.id, ) token.save() except BoxException as e: logger.exception('Unable to complete Box integration setup: %s' % e) messages.error( request, 'Oh no! An unexpected error occurred while trying to set ' 'up the Box.com application. Please try again.') return HttpResponseRedirect(reverse('box_integration:index'))
def __init__(self, client_id, client_secret, access_token, config_fp): config = yaml.load(open(config_fp)) oauth = OAuth2( client_id = client_id or config['oauth']['client_id'], client_secret = client_secret or config['oauth']['client_secret'], access_token = access_token or config['oauth']['access_token'] ) self.client = Client(oauth)
def __init__(self): self.auth = OAuth2( client_id=boxconfig.CLIENT_ID, client_secret=boxconfig.CLIENT_SECRET, access_token=boxconfig.ACCESS_TOKEN, ) self._client = None self._fm = None
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=ensure_str( 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 get_oauth(): global session global config return OAuth2(client_id=config.get('main', 'CLIENT_ID'), client_secret=config.get('main', 'CLIENT_SECRET'), store_tokens=store_tokens, access_token=session.get('access_token'), refresh_token=session.get('refresh_token'))
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 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