Exemplo n.º 1
0
def create_user():
    if not request.form['name']:
        flash("Name required for user creation.", "error")
        return redirect(url_for('index'))
    client = Client(g.auth, network_layer=customLogger)
    new_user = client.create_user(request.form['name'],
                                  job_title=request.form['job'],
                                  phone=request.form['phone'],
                                  address=request.form['address'])
    if request.form.get('initialize'):
        # User init scripts go here
        add_user_to_group(client, new_user, "SuchGroup")
        flash("Initialized user: {0}".format(request.form['name']))
    else:
        flash("Created new user: {0} ".format(request.form['name']))

    return redirect(url_for('index'))
Exemplo n.º 2
0
def box_auth():
    uid = g.user.id

    # Instantiate Box Client instance
    auth = JWTAuth.from_settings_file('../config.json')
    box_client = Client(auth)

    # Validate is user exists
    url = f'https://api.box.com/2.0/users?external_app_user_id={uid}'
    response = box_client.make_request('GET', url)
    user_info = response.json()

    # If user not found, create user, otherwise fetch user token
    if (user_info['total_count'] == 0):
        user_name = f'{g.user.profile.firstName} {g.user.profile.lastName}'
        space = 1073741824

        # Create app user
        user = box_client.create_user(user_name,
                                      None,
                                      space_amount=space,
                                      external_app_user_id=uid)
        print('user {name} created')
    else:
        # Create user client based on discovered user
        user = user_info['entries'][0]
        user_to_impersonate = box_client.user(user_id=user['id'])
        user_client = box_client.as_user(user_to_impersonate)

        # Get current user
        current_user = box_client.user().get()
        print(current_user.id)

        # Get all items in a folder
        items = user_client.folder(folder_id='0').get_items()
        for item in items:
            print('{0} {1} is named "{2}"'.format(item.type.capitalize(),
                                                  item.id, item.name))

        return 'Test complete'
Exemplo n.º 3
0
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)

#phil_fry_user = client.create_user('Phil Fry',user_id='10000')
Exemplo n.º 4
0
from boxsdk import JWTAuth
from boxsdk import Client

auth = JWTAuth(
    client_id='2xld7m3w2j9hvjy60aq951lc68u2ocfv',
    client_secret='gFZg7dhe4Rr2eSIW1D7aZJs6WjXSGI2J',
    enterprise_id='15270599',
    jwt_key_id='qtm1mgfu',
    rsa_private_key_file_sys_path='loans/private_key.pem',
    rsa_private_key_passphrase='nb062795',
)

access_token = auth.authenticate_instance()

client = Client(auth)

ned_stark_user = client.create_user('Ned Stark')
Exemplo n.º 5
0
class BoxClient():
    def __init__(self):
        self.client = Client(auth)
        self.client_creator = self.client.user()
        self.client_created_time = datetime.datetime.now()
        self.as_users = as_users
        self.logger = logging.getLogger(__name__)

    # Common User Methods

    def get_users(self):
        """
        Return a dictionary with users and their ids
        :return:
        """

        users_dict = dict()
        users = self.client.users(user_type='all')

        for user in users:
            users_dict[user.id] = user.name

        return users_dict

    def get_user_by_email(self, login):
        """
        Searches for a user by email and returns a Box User Object
        :param login:
        :return:
        """

        user = None
        users = self.client.users(filter_term=login)

        for user in users:
            if user.login == login:
                return user

        return user

    def create_users(self, upload_method, file, group_name, query):
        """
        Create users at scale

        :param upload_method:
        :param file:
        :param group_name:
        :return: a dictionary containing on how many users were created and how many failed to be created
        """

        success_count = 0
        fail_count = 0

        group_id = self.get_group_id(group_name)

        # If the group doesn't exist, create it.
        if not group_id:
            user_input = input(
                "The group %s doesn't exist. Would you like to create it (yes/no)? "
                % group_name)

            if user_input == "yes":
                group_response = self.create_groups(logger, group_name)

                msg = "Group '%s' successfully created" % group_name
                logger.info(msg)

            elif user_input == "no":

                msg = "No users were added because user opted to not create a new group"
                logger.warning(msg)

                return {
                    'success_count': success_count,
                    'fail_count': fail_count
                }

        # Excel Handler
        if upload_method == 'excel':
            # create a Pandas Dataframe to store Excel Data
            df = pd.read_excel(file)

            row_count = len(df)

            user_input = input(
                "You are about to create %s new user accounts. Are you sure you'd like to continue? (yes/no): "
                % row_count)
            if user_input == "yes":

                if row_count > 10:
                    payload = list()
                    # generate payload

                    for row in df.itertuples():
                        payload_tuple = (row._1 + ' ' + row._2, row.Email,
                                         group_name)
                        payload.append(payload_tuple)

                    self.create_users_with_thread(payload)

                else:
                    # Todo: is there a better way to iterate through DataFrame rows?
                    for row in df.itertuples():
                        create_user_response = self.create_user(
                            row._1 + row._2, row.Email, group_name)

                        if create_user_response:
                            success_count += 1
                        else:
                            fail_count += 1
            else:
                logger.info("User chose not to create accounts")

        # JSON Handler
        elif upload_method == 'json':
            with open(file) as json_file:
                data = json.load(json_file)

                row_count = len(data)

                user_input = input(
                    "You are about to create %s new user accounts. Are you sure you'd like to continue? (yes/no): "
                    % row_count)
                if user_input == "yes":

                    if row_count > 10:
                        payload = list()
                        for current_user in data:
                            payload_tuple = (current_user['first_name'] + ' ' +
                                             current_user['last_name'],
                                             current_user['email'], group_name)
                            payload.append(payload_tuple)

                            self.create_users_with_thread(payload)

                    else:
                        for current_user in data:
                            create_user_response = self.create_user(
                                (current_user['first_name'] + ' ' +
                                 current_user['last_name'],
                                 current_user['email'], group_name))

                            if create_user_response:
                                success_count += 1
                            else:
                                fail_count += 1

                else:
                    logger.info("User chose not to create accounts")

        # PostgreSQL Handler
        elif upload_method == 'db':

            db = DB()

            with db.conn.cursor() as cursor:
                cursor.execute(query)
                records = cursor.fetchall()

                num_rows = cursor.rowcount

                user_input = input(
                    "You are about to create %s new user accounts. Are you sure you'd like to continue? (yes/no): "
                    % num_rows)
                if user_input == "yes":

                    if num_rows > 10:
                        payload = list()
                        for row in records:
                            payload_tuple = (row[1] + row[2], row[3],
                                             group_name)
                            payload.append(payload_tuple)

                            self.create_users_with_thread(payload)

                    else:
                        for row in records:
                            login = row[3]
                            create_user_response = self.create_user(
                                row[1] + row[2], login, group_name)

                            if create_user_response:
                                success_count += 1
                            else:
                                fail_count += 1
                else:
                    logger.info("User chose not to create accounts")

        return {'success_count': success_count, 'fail_count': fail_count}

    def create_user(self, payload):
        """
        Creates a single user

        :param name: Name of the user
        :param login: what's the login for the user you are creating
        :param group_name: which group do you want the user to be assigned to
        :return:
        """

        # Payload Unpacking
        name = payload[0]
        login = payload[1]
        group_name = payload[2]

        success = False
        group_id = None

        if name == None or login == None: return success

        if group_name == None:
            group_id = self.get_group_id(group_name)

        try:
            user = self.client.create_user(name, login)

            # TODO: Deal with this later
            if group_id != None:
                membership_response = self.client.group(
                    group_id=group_id).add_member(user)

        # if an error is throw by the API, handle it by sending to failed_array
        # the most common error is that user already exists
        except exception.BoxAPIException as e:

            msg = "Status Code: %s. %s: <%s>" % (e.status, e.message, login)
            logger.error(msg)

            return success

        else:
            msg = "User was successfully created:  %s " % user
            logger.info(msg)

            success = True
            return success

    def delete_all_users(self, force):
        """
        Delete all users at scale. Can not be undone.

        :param force:
        :return:
        """

        success_count = 0
        fail_count = 0
        users = self.client.users(user_type='all')

        for user in users:
            # if the current user is accessed, which is also the admin, don't delete it.
            if user == self.client.user().get() or user.id in admins: continue

            delete_response = self.client.user(user.id).delete(force=force)

            if delete_response == True:
                msg = 'Deleted: {0} (User ID: {1})'.format(user.name, user.id)
                logger.info(msg)
                success_count += 1
            else:
                msg = 'Unable to delete user. %s : %s' % (user.id, user.login)
                logger.error(msg)
                fail_count += 1

        return {'success_count': success_count, 'fail_count': fail_count}

    def delete_user(self, email, force):
        """
        Delete a single user

        :param email:
        :param force:
        :return:
        """

        success = False

        user = self.get_user_by_email(email)
        if user == None: return success

        success = self.client.user(user.id).delete(force=force)

        if success:
            msg = 'Deleted: {0} (User ID: {1})'.format(user.name, user.id)
            logger.info(msg)

        else:
            msg = 'Unable to delete user. %s : %s' % (user.id, user.login)
            logger.error(msg)

        return success

    def generate_payload(self, upload_method, file, group_name, query):

        # Excel Handler
        if upload_method == 'excel':
            # create a Pandas Dataframe to store Excel Data
            df = pd.read_excel(file)

            row_count = len(df)

            if row_count > 10:
                payload = list()
                # generate payload

                for row in df.itertuples():
                    payload_tuple = (row._1 + ' ' + row._2, row.Email,
                                     group_name)
                    payload.append(payload_tuple)

                # self.create_users_with_thread(payload)

        # JSON Handler
        elif upload_method == 'json':
            with open(file) as json_file:
                data = json.load(json_file)

                row_count = len(data)

                if row_count > 10:
                    payload = list()
                    for current_user in data:
                        payload_tuple = (current_user['first_name'] + ' ' +
                                         current_user['last_name'],
                                         current_user['email'], group_name)
                        payload.append(payload_tuple)

                        # self.create_users_with_thread(payload)

        # PostgreSQL Handler
        elif upload_method == 'db':

            db = DB()

            with db.conn.cursor() as cursor:
                cursor.execute(query)
                records = cursor.fetchall()

                num_rows = cursor.rowcount

                if num_rows > 10:
                    payload = list()
                    for row in records:
                        payload_tuple = (row[1] + row[2], row[3], group_name)
                        payload.append(payload_tuple)

                        # self.create_users_with_thread(payload)

        return payload

    def create_users_with_thread(self, payload):

        print("Begin Threading Operation")

        with ThreadPoolExecutor(max_workers=3) as executors:
            for _ in executors.map(self.create_user, payload):
                print("Thread Executor")

    # Common Group Methods
    def create_groups(self, logger, group_name):

        if self.is_a_group(self.client, group_name):
            logger.warning('Group already exists.')
        else:
            response = self.client.create_group(group_name)

    def is_a_group(self, group_to_check):
        """
        returns whether a group is a present in the enterprise

        :param group_to_check:
        :return:
        """

        groups = self.client.get_groups(group_to_check)
        list_of_groups = []

        for group in groups:
            list_of_groups.append(group.name)

        if group_to_check in list_of_groups:
            return True
        else:
            return False

    def get_group_id(self, group_name):
        """
        Returns the group id as an int by searching for the group name

        :param group_name:
        :return: int
        """

        group_id = None
        groups = self.client.get_groups(group_name)

        for group in groups:
            if group.name == group_name:
                group_id = group.id
                return group_id

        return group_id

    # Common Upload Methods

    def upload_single_file(self, source, destination_folder_id):

        response = self.client.folder(
            folder_id=destination_folder_id).upload(source)

        return response

    def upload_all_files_from_directory(self, source, destination_folder_id):

        # 1. Check if the path exists
        if not (os.path.exists(source)):
            print("Path doesn't exist.")
            return 0

        content = []
        # 2. Get all files in directory
        for path, subdirs, files in os.walk(source):
            for name in files:
                content.append(os.path.join(path, name))

        for file in content:
            print(file)
            self.upload_single_file(
                source=file, destination_folder_id=destination_folder_id)

    # Common Folder Methods

    def get_items_in_folder(self, folder_id):

        items_dict = dict()

        items = self.client.folder(folder_id).get_items()

        for item in items:
            items_dict[item.id] = item.name

        return items_dict
Exemplo n.º 6
0
from flask import Flask
import config_jwt
import requests
import logging

app = Flask(__name__)

# Configure JWT auth and fetch access token
auth = JWTAuth(
  client_id=config_jwt.client_id,
  client_secret=config_jwt.client_secret,
  enterprise_id=config_jwt.enterprise_id,
  jwt_key_id=config_jwt.jwt_key_id,
  rsa_private_key_file_sys_path=config_jwt.private_key_path,
  rsa_private_key_passphrase=config_jwt.private_key_passphrase
)
access_token = auth.authenticate_instance()

BOX_USER_NAME = config_jwt.user_name
FOLDER_ID = config_jwt.folder_id

client = Client(auth)

users = client.users(filter_term=BOX_USER_NAME)
box_user = users[0] if users else client.create_user(BOX_USER_NAME)

root_folder = client.as_user(box_user).folder(folder_id=FOLDER_ID).get()
print 'folder owner: ' + root_folder.owned_by['login']
print 'folder name: ' + root_folder['name']

client.as_user(box_user).folder(folder_id=FOLDER_ID).rename('Tax Rename')
Exemplo n.º 7
0
    rsa_private_key_passphrase = app_auth['passphrase']
)

client = Client(sdk)

print("Client: " + str(client) + "\n")

current_user = client.user().get()

######################################################################
######################################################################
########	Enter a name for the app user.  This should match the
########	name of the app in the script is using from the
########	Box dev console

new_app_user = client.create_user('<name of app user>', login=None)

print(str(new_app_user) +"\n\n")



print("Current user login: "******"\n\n")

print("Current user id:" + str(new_app_user.id) + "\n\n")

output_file = open("New App user login info.txt", "w+")

output_file.write("User credentials for accessing Box folders.  Add this user by email as a collaborator in the Box folder you want your app to have access to\n")

output_file.write("App user login: "******"\n")
Exemplo n.º 8
0
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)