def authenticate_account(name=None, password=''): if name: user = Hierarchy.get_user(name) if user: hash_password = user.password.encode('utf-8') if Crypto.verify_bcrypt_hash(password, hash_password): return True return False
def authenticate_user(username, password): authenticated = False try: user_exist = retrieve_object(username, UserCollections.Users) if user_exist: if user_exist[UserKeys.Enabled] == CommonKeys.YES: original_encrypted_password = ( user_exist[UserKeys.Password].encode('utf-8')) password_verified = (Crypto().verify_bcrypt_hash( password, original_encrypted_password)) if password_verified: authenticated = True except Exception as e: logger.exception(e) return (authenticated)
def edit_user(user=None, mod_data=None): """Edit user properties. Args: user: Name of the user. mod_data: A dic of UserKeys as the key with the new values. Returns: True if successful, False otherwise. """ if not user and not mod_data: return False user = Hierarchy.get_user(user) if not user: return False password = mod_data.get(UserKey.Password) if password: password = password.encode('utf-8') user.password = Crypto.hash_bcrypt(password) full_name = mod_data.get(UserKey.FullName) if full_name: user.full_name = full_name email = mod_data.get(UserKey.Email) if email: user.email = email current_customer = mod_data.get(UserKey.CurrentCustomer) if current_customer: customer = Hierarchy.get_customer(current_customer) if customer: user.current_customer = current_customer default_customer = mod_data.get(UserKey.DefaultCustomer) if default_customer: customer = Hierarchy.get_customer(default_customer) if customer: user.default_customer = default_customer customers = mod_data.get(UserKey.Customers) if customers: for customer in customers: c = Hierarchy.get_customer(customer) if c: Hierarchy.toggle_user_from_customer( user, c, ) groups = mod_data.get(UserKey.Groups) if groups: customer_context = mod_data.get('customer_context') if customer_context: c = Hierarchy.get_customer(customer_context) else: c = Hierarchy.get_customer(user.current_customer) if c: for group in groups: g = Hierarchy.get_group(group) if g: Hierarchy.toggle_group_of_user( user, g, c ) if Hierarchy.save_user(user): return True return False
def create_user( user_name=None, full_name=None, email=None, password=None, groups=None, default_customer=None, customers=None ): """Create a new User and save it. All parameters are required *except* groups and customers. Args: name: Name of the user. full_name: Full name of the user (ie First and last name). email: User's email address. password: User's plain text password. groups: A list of dicts consisting of either an id key or name key describing the group. customers: Customers this user should be added to. List of customer names. default_customer: The default customer for this user. Will be the first data available to the user. Returns: The newly created User if added successfully, None otherwise. """ if ( not user_name ): return False, "Username/password is needed." try: if Hierarchy.get_user(user_name): return False, ( "Username `%s` already exist." % user_name ) # Get the Customer(s) that will be added to this user. customers_to_add = [] if customers: for customer_name in customers: c = Hierarchy.get_customer(customer_name) if c: customers_to_add.append(c) if default_customer: defult_cusomter = Hierarchy.get_customer(default_customer) add_customer = True if default_customer: for c in customer_to_add: if c.customer_name == dc.customer_name: add_customer = False break if add_customer: customers_to_add.append(default_cusotmer) else: if customers_to_add: default_customer = customers_to_add[0] else: default_customer = Hierarchy.get_customer(DefaultCustomer) customers_to_add.append(default_customer) #if not customers: # customers = [default_customer] #if added_default: # if DefaultCustomer not in customers: # customers.append(DefaultCustomer) # Now a Customer type. #default_customer = Hierarchy.get_customer(default_customer) #if not customers_to_add: # customers_to_add.append(default_customer) ############################################################# # Get the Group(s) that will be added to this user. groups_to_add = [] if groups: groups_list = [] for group_name in groups: g = Hierarchy.get_group( group_name, default_customer.customer_name ) if g: groups_list.append(g) groups_to_add.extend(groups_list) else: g = Hierarchy.get_group( DefaultGroup.ReadOnly, default_customer.customer_name ) if g: groups_to_add.append(g) ############################################################# user_name = user_name.strip() full_name = full_name.strip() if not password: password = generate_pass() password = Crypto.hash_bcrypt(password.encode('utf-8')) user = User( user_name, password, full_name, email, default_customer.customer_name, default_customer.customer_name ) saved = Hierarchy.save_user(user) if saved: for group in groups_to_add: Hierarchy.toggle_group_of_user( group=group, user=user, customer=default_customer ) for customer in customers_to_add: Hierarchy.toggle_user_from_customer( user=user, customer=customer ) return user, '' except Exception as e: logger.error("Unable to create user `%s`." % user_name) logger.exception(e) return None
def edit_user(user=None, mod_data=None): """Edit user properties. Args: user: Name of the user. mod_data: A dic of UserKeys as the key with the new values. Returns: True if successful, False otherwise. """ if not user and not mod_data: return False user = Hierarchy.get_user(user) password = mod_data.get(UserKey.Password) if password: user.password = Crypto.hash_bcrypt(password) full_name = mod_data.get(UserKey.FullName) if full_name: user.full_name = full_name email = mod_data.get(UserKey.Email) if email: user.email = email current_customer = mod_data.get(UserKey.CurrentCustomer) if current_customer: customer = Hierarchy.get_customer(current_customer) if customer: customer_name = '' current_customer = user.get_current_customer() if current_customer: customer_name = current_customer.name if not customer.name == customer_name: user.set_current_customer(customer) default_customer = mod_data.get(UserKey.DefaultCustomer) if default_customer: customer = Hierarchy.get_customer(default_customer) if customer: user.set_current_customer(customer) customers = mod_data.get(UserKey.Customers) if customers: for customer in customers: c = Hierarchy.get_customer(customer) if c: user, c = Hierarchy.toggle_user_from_customer( user, c, both=True ) _db.save_customer(c) groups = mod_data.get(UserKey.Groups) if groups: for group in groups: g = Hierarchy.get_group(group) if g: user, g = Hierarchy.toggle_user_from_group(user, g, both=True) _db.save_group(g) if _db.save_user(user): return True return False
def create_user(name=None, full_name=None, email=None, password=None, groups=None, customers=None, default_customer=None): """Create a new User and save it. All parameters are required *except* groups and customers. Args: name: Name of the user. full_name: Full name of the user (ie First and last name). email: User's email address. password: User's plain text password. groups: A list of dicts consisting of either an id key or name key describing the group. customers: Customers this user should be added to. List of customer names. default_customer: The default customer for this user. Will be the first data available to the user. Returns: The newly created User if added successfully, None otherwise. """ if ( not name or not password ): return False # Get the Group instances that will be added to this user. if groups: groups_list = [] for group in groups: g = Hierarchy.get_group(group) if g: groups_list.append(g) groups = groups_list else: groups = [] g = Hierarchy.get_group({GroupKey.Name: 'Read Only'}) if g: groups.append(g) # Get the Customer instances that will be added to this user. if customers: customers_list = [] for customer in customers: c = Hierarchy.get_customer(customer) if c: customers_list.append(c) if customers_list: customers = customers_list else: customers = [Hierarchy.get_customer(DefaultCustomer)] else: customers = [Hierarchy.get_customer(DefaultCustomer)] if default_customer: default_customer = Hierarchy.get_customer(default_customer) else: default_customer = customers[0] name = name.strip() full_name = full_name.strip() password = Crypto.hash_bcrypt(password) user = User(name, full_name, email, password, groups, customers, default_customer=default_customer, current_customer=default_customer) _id = _db.save_user(user) if _id == '': user.id = user.name for g in groups: _, mod_group = Hierarchy.toggle_user_from_group(user, g) _db.save_group(mod_group) for c in customers: _, mod_customer = Hierarchy.toggle_user_from_customer(user, c) _db.save_customer(mod_customer) return user return None
def edit_user(user=None, mod_data=None): """Edit user properties. Args: user: Name of the user. mod_data: A dic of UserKeys as the key with the new values. Returns: True if successful, False otherwise. """ if not user and not mod_data: return False user = Hierarchy.get_user(user) password = mod_data.get(UserKey.Password) if password: user.password = Crypto.hash_bcrypt(password) full_name = mod_data.get(UserKey.FullName) if full_name: user.full_name = full_name email = mod_data.get(UserKey.Email) if email: user.email = email current_customer = mod_data.get(UserKey.CurrentCustomer) if current_customer: customer = Hierarchy.get_customer(current_customer) if customer: customer_name = '' current_customer = user.get_current_customer() if current_customer: customer_name = current_customer.name if not customer.name == customer_name: user.set_current_customer(customer) default_customer = mod_data.get(UserKey.DefaultCustomer) if default_customer: customer = Hierarchy.get_customer(default_customer) if customer: user.set_current_customer(customer) customers = mod_data.get(UserKey.Customers) if customers: for customer in customers: c = Hierarchy.get_customer(customer) if c: user, c = Hierarchy.toggle_user_from_customer(user, c, both=True) _db.save_customer(c) groups = mod_data.get(UserKey.Groups) if groups: for group in groups: g = Hierarchy.get_group(group) if g: user, g = Hierarchy.toggle_user_from_group(user, g, both=True) _db.save_group(g) if _db.save_user(user): return True return False
def create_user(name=None, full_name=None, email=None, password=None, groups=None, customers=None, default_customer=None): """Create a new User and save it. All parameters are required *except* groups and customers. Args: name: Name of the user. full_name: Full name of the user (ie First and last name). email: User's email address. password: User's plain text password. groups: A list of dicts consisting of either an id key or name key describing the group. customers: Customers this user should be added to. List of customer names. default_customer: The default customer for this user. Will be the first data available to the user. Returns: The newly created User if added successfully, None otherwise. """ if (not name or not password): return False # Get the Group instances that will be added to this user. if groups: groups_list = [] for group in groups: g = Hierarchy.get_group(group) if g: groups_list.append(g) groups = groups_list else: groups = [] g = Hierarchy.get_group({GroupKey.Name: 'Read Only'}) if g: groups.append(g) # Get the Customer instances that will be added to this user. if customers: customers_list = [] for customer in customers: c = Hierarchy.get_customer(customer) if c: customers_list.append(c) if customers_list: customers = customers_list else: customers = [Hierarchy.get_customer(DefaultCustomer)] else: customers = [Hierarchy.get_customer(DefaultCustomer)] if default_customer: default_customer = Hierarchy.get_customer(default_customer) else: default_customer = customers[0] name = name.strip() full_name = full_name.strip() password = Crypto.hash_bcrypt(password) user = User(name, full_name, email, password, groups, customers, default_customer=default_customer, current_customer=default_customer) _id = _db.save_user(user) if _id == '': user.id = user.name for g in groups: _, mod_group = Hierarchy.toggle_user_from_group(user, g) _db.save_group(mod_group) for c in customers: _, mod_customer = Hierarchy.toggle_user_from_customer(user, c) _db.save_customer(mod_customer) return user return None
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)
def change_password( username, password, new_password, user_name=None, uri=None, method=None ): """Change password for a user. Args: username (str): The name of the user you are deleteing. password (str): Original password. new_password (str): New password. 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. Return: Dictionary of the status of the operation. { 'uri': None, 'rv_status_code': 1008, 'http_method': None, 'http_status': 200, 'message': 'None - change_password - Password changed for user admin - admin was updated', 'data': [] } """ user_exist = get_user(username, without_fields=None) status = change_password.func_name + ' - ' try: generic_status_code = 0 vfense_status_code = 0 if user_exist: pass_strength = check_password(new_password) original_encrypted_password = user_exist[UserKeys.Password].encode('utf-8') original_password_verified = ( Crypto().verify_bcrypt_hash(password, original_encrypted_password) ) encrypted_new_password = Crypto().hash_bcrypt(new_password) new_password_verified_against_orignal_password = ( Crypto().verify_bcrypt_hash(new_password, original_encrypted_password) ) if (original_password_verified and pass_strength[0] and not new_password_verified_against_orignal_password): user_data = {UserKeys.Password: encrypted_new_password} object_status, _, _, _ = ( update_user(username, user_data) ) if object_status == DbCodes.Replaced: msg = 'Password changed for user %s - ' % (username) generic_status_code = GenericCodes.ObjectUpdated vfense_status_code = UserCodes.PasswordChanged elif new_password_verified_against_orignal_password: msg = 'New password is the same as the original - user %s - ' % (username) object_status = DbCodes.Unchanged generic_status_code = GenericFailureCodes.FailedToUpdateObject vfense_status_code = UserFailureCodes.NewPasswordSameAsOld elif original_password_verified and not pass_strength[0]: msg = 'New password is to weak for user %s - ' % (username) object_status = DbCodes.Unchanged generic_status_code = GenericFailureCodes.FailedToUpdateObject vfense_status_code = UserFailureCodes.WeakPassword elif not original_password_verified: msg = 'Password not verified for user %s - ' % (username) object_status = DbCodes.Unchanged generic_status_code = GenericFailureCodes.FailedToUpdateObject vfense_status_code = UserFailureCodes.InvalidPassword results = { ApiResultKeys.DB_STATUS_CODE: object_status, ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code, ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code, ApiResultKeys.UPDATED_IDS: [username], ApiResultKeys.MESSAGE: status + msg, ApiResultKeys.DATA: [], ApiResultKeys.USERNAME: user_name, ApiResultKeys.URI: uri, ApiResultKeys.HTTP_METHOD: method } else: msg = 'User %s does not exist - ' % (username) object_status = DbCodes.Skipped generic_status_code = GenericCodes.InvalidId vfense_status_code = UserFailureCodes.UserNameDoesNotExist 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.DATA: [], ApiResultKeys.USERNAME: user_name, ApiResultKeys.URI: uri, ApiResultKeys.HTTP_METHOD: method } except Exception as e: logger.exception(e) status_code = DbCodes.Errors generic_status_code = GenericFailureCodes.FailedToUpdateObject vfense_status_code = UserFailureCodes.FailedToUpdateUser msg = 'Failed to update password for user %s: %s' % (username, str(e)) 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.DATA: [], ApiResultKeys.USERNAME: user_name, ApiResultKeys.URI: uri, ApiResultKeys.HTTP_METHOD: method } return(results)