Exemple #1
0
    def _login(self):
        access_token, refresh_token = read_tokens()

        if access_token is None or refresh_token is None:
            oauth = bx.OAuth2(
                client_id=self.client_id,
                client_secret=self.client_secret,
                store_tokens=store_tokens,
            )
            self.auth_url, csrf_token = oauth.get_authorization_url(
                self.redirect_url)
            webbrowser.open(self.auth_url)
            global _access_code
            while _access_code is None:
                log.debug(_access_code)
                time.sleep(1)

            if _access_code == "denied":
                raise PermissionError("Failed to authenticate to Box.")

            access_token, refresh_token = authenticate(oauth, _access_code)

        oauth = bx.OAuth2(
            client_id=self.client_id,
            client_secret=self.client_secret,
            access_token=access_token,
            refresh_token=refresh_token,
        )
        self._client = bx.Client(oauth)
Exemple #2
0
 def _init_client(self):
     oauth = boxsdk.OAuth2(client_id=self.creds["client_id"],
                           client_secret=self.creds["client_secret"],
                           store_tokens=self._store_tokens,
                           access_token=self.creds["user_access_token"],
                           refresh_token=self.creds["user_refresh_token"])
     client = boxsdk.Client(oauth)
     return client
Exemple #3
0
def get_box_client():
    oauth = boxsdk.OAuth2(
        client_id='f5qebb99vwnebdrdok3wv7ew4pk84nl3',
        client_secret='cLwt5hj96589T15SG6lAp11fZYBsqyel',
        access_token='rVSyiCPelJx3hPYPquM8Gy9ZRuLvoCHl',
    )
    client = boxsdk.Client(oauth)
    return client
Exemple #4
0
    def __init__(self, client_id=None, client_secret=None, access_token=None):
        client_id = check_env('BOX_CLIENT_ID', client_id)
        client_secret = check_env('BOX_CLIENT_SECRET', client_secret)
        access_token = check_env('BOX_ACCESS_TOKEN', access_token)

        oauth = boxsdk.OAuth2(client_id=client_id,
                              client_secret=client_secret,
                              access_token=access_token)
        self.client = boxsdk.Client(oauth)
Exemple #5
0
 def __init__(self, archive, settings):
     self.archive = archive
     self.client_id = settings.get('box.client_id')
     self.client_secret = settings.get('box.client_secret')
     self.oauth = boxsdk.OAuth2(client_id=self.client_id,
                                client_secret=self.client_secret,
                                access_token=archive.access_token,
                                refresh_token=archive.refresh_token,
                                store_tokens=archive.store)
     self.client = boxsdk.Client(self.oauth)
Exemple #6
0
def authenticate(identifier, secret, token): 
    '''identifier: client_id, provided in config.py
    secret: client_secret, provided in config.py
    token: developer token, accessed from box developer console
    '''
    oauth = boxsdk.OAuth2(
        client_id=identifier, 
        client_secret=secret, 
        access_token=token
    )
    client = boxsdk.Client(oauth)
    return client
Exemple #7
0
def start_session():
    """Initialize a Box session using Box API.  """
    global access_token, refresh_token, server_thread, httpd
    # Try to retrieve tokens from keychain
    #   If error during OAuth or no tokens, re-authenticate
    try:
        access_token, refresh_token = retrieve_tokens()
        oauth = boxsdk.OAuth2(client_id=BOX_CLIENT_ID,
                              access_token=access_token,
                              refresh_token=refresh_token,
                              client_secret=BOX_CLIENT_SECRET,
                              store_tokens=store_tokens)
        if None in (access_token, refresh_token):
            raise boxsdk.exception.BoxOAuthException('No Tokens')
    except boxsdk.exception.BoxOAuthException:
        # Authenticate with OAuth
        print("\nAuthenticating...".ljust(71), end="", flush=True)
        oauth = boxsdk.OAuth2(client_id=BOX_CLIENT_ID,
                              client_secret=BOX_CLIENT_SECRET,
                              store_tokens=store_tokens)

        # Start HTTP server to get auth token from Box.com redirect
        server_thread = threading.Thread(target=run_server)
        server_thread.start()
        auth_url, csrf = oauth.get_authorization_url('http://127.0.0.1:7777')

        # Open browser and wait for user authentification
        webbrowser.open(auth_url)
        while not auth_code:
            pass

        # Shutdown HTTP Server
        httpd.shutdown()
        server_thread.join()
        access_token, refresh_token = oauth.authenticate(auth_code)
        httpd.shutdown()
        print("Complete!")

    # Return authenticated client
    return boxsdk.Client(oauth)
Exemple #8
0
    def _janky_auth_trick(self, log_path="/var/log/nginx/access.log"):
        """The most minimal sort of method of getting a Box API access token.

        Steps:
        1) set up App on box.com, pointing the redirect URL to your own web server
        2) run this function
        3) take app auth URL from standard output
        4) visit app auth URL in browser, triggering Box to contact your server
        5) take OAuth2 object as return value and/or auth text from standard output

        log_path should be the path to a readable web server log file in the Common
        Log Format.

        In more detail:

        1) First create an App at https://app.box.com/developers/console.  For
        Authentication Method use "Standard OAuth 2.0 (User Authentication)"
        Copy and paste the Client ID and Client Secret text into the
        credeitnals file.  Set Redirect URI to a HTTPS URL you control.  The
        destination doesn't much matter since it can just trigger a 404 error
        on your side that shows up in the log.  You must have control over an
        HTTPS-enabled web server to do this; I originally planned to use netcat
        on a high-numbered port and just read the text, but Box requires HTTPS.
        (All this, even though using the API doesn't actually require a web
        server running.)

        2) Now run this function and note the URL printed.

        3) Nothing much will happen at first.  Copy and paste the URL printed to
        standard output into a web browser.

        4) Say "yes" in the browser to give the app access to your account, and
        then watch for more lines on the terminal.  Box should connect, make an
        HTTP request with all the relevant info, and trigger a 404 error that ends
        up in the logs.  (There's a pretty short timeout -- sixty seconds? -- on
        the whole process, so as soon as Box sends the data to your web server this
        function needs to catch it.)

        5) Use the returned OAuth2 object and/or enter those extra lines into
        config.py as user_access_token and user_refresh_token.
        """
        oauth = boxsdk.OAuth2(client_id=self.creds["client_id"],
                              client_secret=self.creds["client_secret"])
        auth_url = oauth.get_authorization_url(self.creds["redirect_uri"])[0]
        LOGGER.critical("Auth URL: %s", auth_url)
        code = scrape_log_for_code(log_path)
        access_token, refresh_token = oauth.authenticate(code)
        self._store_tokens(access_token, refresh_token)
        return self._init_client()
Exemple #9
0
    def login_prompt(self):
        oauth = boxsdk.OAuth2(
            client_id=constants.client_id,
            client_secret=constants.client_secret,
            store_tokens=self.save_tokens
        )
        auth_url, csrf_token = oauth.get_authorization_url("http://localhost:8080/")

        logger.info("Auth url: {0}, csrf_token: {1}", auth_url, csrf_token)
        auth_code = TokenHandler().get_access_token(auth_url)

        logger.info("AUTH_CODE: {0}", auth_code)
        oauth.authenticate(auth_code)
        # Create the SDK client
        client = boxsdk.LoggingClient(oauth)

        #Get logged in user
        user = client.user(user_id='me').get()
        print(user)
        pass
Exemple #10
0
def get_access_token_from_file():
    data = get_token()
    return data['access_token']

def get_refresh_token_from_file():
    data = get_token()
    return data['refresh_token']

def get_access_token():
    secret_token(get_refresh_token_from_file())
    return get_access_token_from_file()

oauth = boxsdk.OAuth2(
    client_id=box_client_id,
    client_secret=box_client_secret,
    access_token=get_access_token(),
)

client = boxsdk.Client(oauth)
# root_folder = client.folder(folder_id='0').get_items(limit=100, offset=0)
list_to_create = []

def log(message):
    with open('log.txt', 'a') as f:
        f.write(message + '\n')

def sync_create_file(dropbox_path, box_folder_id):
    file_name = dropbox_path[1:].split('/')[-1]
    sys.stdout.write('Downloading from Dropbox -')
    sys.stdout.flush()