Exemplo n.º 1
0
    def post(self, username):
        active_user = self.get_current_user()
        active_customer = (get_user_property(username,
                                             UserKeys.CurrentCustomer))
        uri = self.request.uri
        method = self.request.method
        results = None
        try:
            customer_context = (self.arguments.get(
                ApiArguments.CUSTOMER_CONTEXT, active_customer))
            action = self.arguments.get(ApiArguments.ACTION, ApiValues.ADD)

            ###Update Groups###
            group_ids = self.arguments.get(ApiArguments.GROUP_IDS, None)
            if group_ids and isinstance(group_ids, list):
                if action == ApiValues.ADD:
                    results = (add_user_to_groups(username, customer_context,
                                                  group_ids, username, uri,
                                                  method))
                if action == ApiValues.DELETE:
                    results = (remove_groups_from_user(username, group_ids,
                                                       username, uri, method))
            ###Update Customers###
            customer_names = self.arguments.get('customer_names')
            if customer_names and isinstance(customer_names, list):
                if action == 'add':
                    results = (add_user_to_customers(username, customer_names,
                                                     username, uri, method))

                elif action == 'delete':
                    results = (remove_customers_from_user(
                        username, customer_names, username, uri, method))

            if results:
                self.set_status(results['http_status'])
                self.set_header('Content-Type', 'application/json')
                self.write(json.dumps(results, indent=4))

            else:
                results = (GenericResults(active_user, uri,
                                          method).incorrect_arguments())

                self.set_status(results['http_status'])
                self.set_header('Content-Type', 'application/json')
                self.write(json.dumps(results, indent=4))

        except Exception as e:
            results = (GenericResults(active_user, uri,
                                      method).something_broke(
                                          active_user, 'User', e))
            logger.exception(e)
            self.set_status(results['http_status'])
            self.set_header('Content-Type', 'application/json')
            self.write(json.dumps(results, indent=4))
Exemplo n.º 2
0
    def post(self, username):
        active_user = self.get_current_user()
        active_customer = (
            get_user_property(username, UserKeys.CurrentCustomer)
        )
        uri = self.request.uri
        method = self.request.method
        results = None
        try:
            customer_context = (
                self.arguments.get(ApiArguments.CUSTOMER_CONTEXT, active_customer)
            )
            action = self.arguments.get(ApiArguments.ACTION, ApiValues.ADD)

            ###Update Groups###
            group_ids = self.arguments.get(ApiArguments.GROUP_IDS, None)
            if group_ids and isinstance(group_ids, list):
                if action == ApiValues.ADD:
                    results = (
                        add_user_to_groups(
                            username, customer_context, group_ids,
                            username, uri, method
                        )
                    )
                if action == ApiValues.DELETE:
                    results = (
                        remove_groups_from_user(
                            username, group_ids,
                            username, uri, method
                        )
                    )
            ###Update Customers###
            customer_names = self.arguments.get('customer_names')
            if customer_names and isinstance(customer_names, list):
                if action == 'add':
                    results = (
                        add_user_to_customers(
                            username, customer_names,
                            username, uri, method
                        )
                    )

                elif action == 'delete':
                    results = (
                        remove_customers_from_user(
                            username, customer_names,
                            username, uri, method
                        )
                    )

            if results:
                self.set_status(results['http_status'])
                self.set_header('Content-Type', 'application/json')
                self.write(json.dumps(results, indent=4))

            else:
                results = (
                    GenericResults(
                        active_user, uri, method
                    ).incorrect_arguments()
                )

                self.set_status(results['http_status'])
                self.set_header('Content-Type', 'application/json')
                self.write(json.dumps(results, indent=4))

        except Exception as e:
            results = (
                GenericResults(
                    active_user, uri, method
                ).something_broke(active_user, 'User', e)
            )
            logger.exception(e)
            self.set_status(results['http_status'])
            self.set_header('Content-Type', 'application/json')
            self.write(json.dumps(results, indent=4))
Exemplo n.º 3
0
def create_user(
    username, fullname, password, group_ids,
    customer_name, email, enabled=CommonKeys.YES, user_name=None,
    uri=None, method=None
    ):
    """Add a new user into vFense
    Args:
        username (str): The name of the user you are creating.
        fullname (str): The full name of the user you are creating.
        password (str): The unencrypted password of the user.
        group_ids (list): List of vFense group ids to add the user too.
        customer_name (str): The customer, this user will be part of.
        email (str): Email address of the user.
        enabled (str): yes or no
            Default=no

    Kwargs:
        user_name (str): The name of the user who called this function.
        uri (str): The uri that was used to call this function.
        method (str): The HTTP methos that was used to call this function.

    Basic Usage:
        >>> from vFense.user.users import create_user
        >>> username = '******'
        >>> fullname = 'testing 4 life'
        >>> password = '******'
        >>> group_ids = ['8757b79c-7321-4446-8882-65457f28c78b']
        >>> customer_name = 'default'
        >>> email = '*****@*****.**'
        >>> enabled = 'yes'
        >>> create_user(
                username, fullname, password,
                group_ids, customer_name, email, enabled
            )

    Return:
        Dictionary of the status of the operation.
        {
            'uri': None,
            'rv_status_code': 1010,
            'http_method': None,
            'http_status': 200,
            'message': 'None - create user testing123 was created',
            'data': {
                'current_customer': 'default',
                'full_name': 'tester4life',
                'default_customer': 'default',
                'password': '******',
                'user_name': 'testing123',
                'enabled': 'yes',
                'email': '*****@*****.**'
            }
        }
    """

    user_exist = get_user(username)
    pass_strength = check_password(password)
    status = create_user.func_name + ' - '
    generated_ids = []
    generic_status_code = 0
    vfense_status_code = 0
    user_data = (
        {
            UserKeys.CurrentCustomer: customer_name,
            UserKeys.DefaultCustomer: customer_name,
            UserKeys.FullName: fullname,
            UserKeys.UserName: username,
            UserKeys.Enabled: enabled,
            UserKeys.Email: email
        }
    )
    if enabled != CommonKeys.YES or enabled != CommonKeys.NO:
        enabled = CommonKeys.NO


    valid_user_name = (
        re.search('([A-Za-z0-9_-]{1,24})', username)
    )
    valid_user_length = (
        len(username) <= DefaultStringLength.USER_NAME
    )

    try:
        if (not user_exist and pass_strength[0] and
                valid_user_length and valid_user_name):
            encrypted_password = Crypto().hash_bcrypt(password)
            user_data[UserKeys.Password] = encrypted_password
            customer_is_valid = get_customer(customer_name)
            validated_groups, _, invalid_groups = validate_group_ids(
                group_ids, customer_name
            )

            if customer_is_valid and validated_groups:
                object_status, _, _, generated_ids = (
                    insert_user(user_data)
                )
                generated_ids.append(username)

                add_user_to_customers(
                    username, [customer_name],
                    user_name, uri, method
                )

                add_user_to_groups(
                    username, customer_name, group_ids,
                    user_name, uri, method
                )
                if object_status == DbCodes.Inserted:
                    msg = 'user name %s created' % (username)
                    generic_status_code = GenericCodes.ObjectCreated
                    vfense_status_code = UserCodes.UserCreated
                    user_data.pop(UserKeys.Password)

            elif not customer_is_valid and validated_groups:
                msg = 'customer name %s does not exist' % (customer_name)
                object_status = DbCodes.Skipped
                generic_status_code = GenericCodes.InvalidId
                vfense_status_code = CustomerFailureCodes.CustomerDoesNotExist

            elif not validated_groups and customer_is_valid:
                msg = 'group ids %s does not exist' % (invalid_groups)
                object_status = DbCodes.Skipped
                generic_status_code = GenericCodes.InvalidId
                vfense_status_code = GroupFailureCodes.InvalidGroupId

            else:
                group_error = (
                    'group ids %s does not exist' % (invalid_groups)
                )
                customer_error = (
                    'customer name %s does not exist' % (customer_name)
                )
                msg = group_error + ' and ' + customer_error
                object_status = DbCodes.Errors
                generic_status_code = GenericFailureCodes.FailedToCreateObject
                vfense_status_code = UserFailureCodes.FailedToCreateUser

        elif user_exist:
            msg = 'username %s already exists' % (username)
            object_status = GenericCodes.ObjectExists
            generic_status_code = GenericCodes.ObjectExists
            vfense_status_code = UserFailureCodes.UserNameExists

        elif not pass_strength[0]:
            msg = (
                    'password does not meet the min requirements: strength=%s'
                    % (pass_strength[1])
            )
            object_status = GenericFailureCodes.FailedToCreateObject
            generic_status_code = GenericFailureCodes.FailedToCreateObject
            vfense_status_code = UserFailureCodes.WeakPassword

        elif not valid_user_name or not valid_user_length:
            status_code = DbCodes.Errors
            msg = (
                'user name is not within the 24 character range '+
                'or contains unsupported characters :%s' %
                (username)
            )
            generic_status_code = GenericCodes.InvalidId
            vfense_status_code = UserFailureCodes.InvalidUserName

        results = {
            ApiResultKeys.DB_STATUS_CODE: object_status,
            ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code,
            ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code,
            ApiResultKeys.MESSAGE: status + msg,
            ApiResultKeys.GENERATED_IDS: generated_ids,
            ApiResultKeys.DATA: [user_data],
            ApiResultKeys.USERNAME: user_name,
            ApiResultKeys.URI: uri,
            ApiResultKeys.HTTP_METHOD: method
        }

    except Exception as e:
        logger.exception(e)
        msg = 'Failed to create user %s: %s' % (username, str(e))
        status_code = DbCodes.Errors
        generic_status_code = GenericFailureCodes.FailedToCreateObject
        vfense_status_code = UserFailureCodes.FailedToCreateUser

        results = {
            ApiResultKeys.DB_STATUS_CODE: status_code,
            ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code,
            ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code,
            ApiResultKeys.MESSAGE: status + msg,
            ApiResultKeys.GENERATED_IDS: [],
            ApiResultKeys.DATA: [user_data],
            ApiResultKeys.USERNAME: user_name,
            ApiResultKeys.URI: uri,
            ApiResultKeys.HTTP_METHOD: method
        }

    return(results)