Python flask_security.utils.hash_password() Examples

The following are 20 code examples of flask_security.utils.hash_password(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_security.utils , or try the search function .
Example #1
Source File: test_hashing.py    From flask-security with MIT License 6 votes vote down vote up
def test_verify_password_single_hash_list(app, sqlalchemy_datastore):
    init_app_with_options(
        app,
        sqlalchemy_datastore,
        **{
            "SECURITY_PASSWORD_HASH": "bcrypt",
            "SECURITY_PASSWORD_SALT": "salty",
            "SECURITY_PASSWORD_SINGLE_HASH": ["django_pbkdf2_sha256", "plaintext"],
            "SECURITY_PASSWORD_SCHEMES": [
                "bcrypt",
                "pbkdf2_sha256",
                "django_pbkdf2_sha256",
                "plaintext",
            ],
        }
    )
    with app.app_context():
        # double hash
        assert verify_password("pass", hash_password("pass"))
        assert verify_password("pass", pbkdf2_sha256.hash(get_hmac("pass")))
        # single hash
        assert verify_password("pass", django_pbkdf2_sha256.hash("pass"))
        assert verify_password("pass", plaintext.hash("pass")) 
Example #2
Source File: security_utils.py    From cloudify-manager with Apache License 2.0 6 votes vote down vote up
def add_users_to_db(user_list):
    default_tenant = Tenant.query.get(DEFAULT_TENANT_ID)
    for user in user_list:
        role = user_datastore.find_role(user['role'])
        user_obj = user_datastore.create_user(
            username=user['username'],
            password=hash_password(user['password']),
            roles=[role]
        )

        default_tenant_role = user_datastore.find_role(DEFAULT_TENANT_ROLE)
        user_obj.active = user.get('active', True)
        user_tenant_association = UserTenantAssoc(
            user=user_obj,
            tenant=default_tenant,
            role=default_tenant_role,
        )
        user_obj.tenant_associations.append(user_tenant_association)
    user_datastore.commit() 
Example #3
Source File: admin.py    From SmartProxyPool with MIT License 5 votes vote down vote up
def create_admin_user(user_datastore, app):
    with app.app_context():    
        if user_datastore.get_user("admin"):
            pass
        else:
            user_role = user_datastore.find_role(role='user')
            super_user_role = user_datastore.find_role(role='superuser')
            user_datastore.create_user(name='admin', email='admin', password=hash_password('admin'), roles=[user_role, super_user_role]) 
Example #4
Source File: user_role_db_interface.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def change_password(self, user_name, password):
        user = self.find_user(email=user_name)
        user.password = hash_password(password)
        self.put(user) 
Example #5
Source File: user.py    From flask-react-spa with MIT License 5 votes vote down vote up
def __init__(self, hash_password=True, **kwargs):
        super().__init__(**kwargs)
        if 'password' in kwargs and hash_password:
            self.password = security_hash_password(kwargs['password']) 
Example #6
Source File: __init__.py    From CHN-Server with GNU Lesser General Public License v2.1 5 votes vote down vote up
def create_superuser_entry():
    # Creating superuser entry.
    superuser = user_datastore.create_user(
        email=mhn.config.get('SUPERUSER_EMAIL'),
        password=hash(mhn.config.get('SUPERUSER_ONETIME_PASSWORD')))
    adminrole = user_datastore.create_role(name='admin', description='')
    user_datastore.add_role_to_user(superuser, adminrole)
    user_datastore.create_role(name='user', description='')
    db.session.flush()

    apikey = ApiKey(user_id=superuser.id, api_key=str(uuid.uuid4()).replace("-", ""))
    db.session.add(apikey)
    db.session.flush()

    return superuser 
Example #7
Source File: manual_password_reset.py    From CHN-Server with GNU Lesser General Public License v2.1 5 votes vote down vote up
def main():

    args = parse_args()

    with mhn.test_request_context():

        if not args.username:
            email = input("Enter email address: ").strip()
        else:
            email = args.username

        if not args.password:
            password = getpass("Enter new password: ")
            password2 = getpass("Enter new password (again): ")

            if password != password2:
                sys.stderr.write("Passwords didn't match, try again\n")
                return 1
        else:
            password = args.password

        user = User.query.filter_by(email=email).first()
        if user:
            print("user found, updating password")
            user.password = hash_password(password)
            db.session.add(user)
            db.session.commit()
        else:
            sys.stderr.write("No user with that email address was found.\n")

    return 0 
Example #8
Source File: storage_utils.py    From cloudify-manager with Apache License 2.0 5 votes vote down vote up
def create_status_reporter_user_and_assign_role(username,
                                                password,
                                                role,
                                                user_id):
    """Creates a user and assigns its given role.
    """
    user = user_datastore.create_user(
        username=username,
        password=hash_password(password),
        roles=[role],
        id=user_id
    )

    default_tenant = Tenant.query.filter_by(
        id=constants.DEFAULT_TENANT_ID).first()
    reporter_role = user_datastore.find_role(role)
    if not reporter_role:
        raise NotFoundError("The username \"{0}\" cannot have the role \"{1}\""
                            " as the role doesn't exist"
                            "".format(username, role))
    user_tenant_association = UserTenantAssoc(
        user=user,
        tenant=default_tenant,
        role=reporter_role,
    )
    user.tenant_associations.append(user_tenant_association)
    user_datastore.commit()
    return user 
Example #9
Source File: storage_utils.py    From cloudify-manager with Apache License 2.0 5 votes vote down vote up
def create_default_user_tenant_and_roles(admin_username,
                                         admin_password,
                                         amqp_manager,
                                         authorization_file_path):
    """
    Create the bootstrap admin, the default tenant and the security roles,
    as well as a RabbitMQ vhost and user corresponding to the default tenant

    :return: The default tenant
    """
    admin_role = _create_roles(authorization_file_path)
    default_tenant = _create_default_tenant()
    amqp_manager.create_tenant_vhost_and_user(tenant=default_tenant)

    admin_user = user_datastore.create_user(
        id=constants.BOOTSTRAP_ADMIN_ID,
        username=admin_username,
        password=hash_password(admin_password),
        roles=[admin_role]
    )

    # The admin user is assigned to the default tenant.
    # This is the default role when a user is added to a tenant.
    # Anyway, `sys_admin` will be the effective role since is the system role.
    user_role = user_datastore.find_role(constants.DEFAULT_TENANT_ROLE)
    user_tenant_association = UserTenantAssoc(
        user=admin_user,
        tenant=default_tenant,
        role=user_role,
    )
    admin_user.tenant_associations.append(user_tenant_association)
    user_datastore.commit()
    return default_tenant 
Example #10
Source File: factories.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def _adjust_kwargs(cls, **kwargs):
        if 'password' in kwargs:
            # Password is stored hashed
            kwargs['password'] = hash_password(kwargs['password'])
        return kwargs 
Example #11
Source File: Users.py    From LuckyCAT with GNU General Public License v3.0 5 votes vote down vote up
def change_password(email, new_password):
    user = User.objects.get(email=email)
    user.update(password=utils.hash_password(new_password)) 
Example #12
Source File: view_scaffold.py    From flask-security with MIT License 5 votes vote down vote up
def add_user(ds, email, password, roles):
    pw = hash_password(password)
    roles = [ds.find_or_create_role(rn) for rn in roles]
    ds.commit()
    user = ds.create_user(
        email=email, password=pw, active=True, confirmed_at=datetime.datetime.utcnow()
    )
    ds.commit()
    for role in roles:
        ds.add_role_to_user(user, role)
    ds.commit() 
Example #13
Source File: test_utils.py    From flask-security with MIT License 5 votes vote down vote up
def create_users(app, ds, count=None):
    users = [
        ("matt@lp.com", "matt", "password", ["admin"], True, 123456, None),
        ("joe@lp.com", "joe", "password", ["editor"], True, 234567, None),
        ("dave@lp.com", "dave", "password", ["admin", "editor"], True, 345678, None),
        ("jill@lp.com", "jill", "password", ["author"], True, 456789, None),
        ("tiya@lp.com", "tiya", "password", [], False, 567890, None),
        ("gene@lp.com", "gene", "password", ["simple"], True, 889900, None),
        ("jess@lp.com", "jess", None, [], True, 678901, None),
        ("gal@lp.com", "gal", "password", ["admin"], True, 112233, "sms"),
        ("gal2@lp.com", "gal2", "password", ["admin"], True, 223311, "authenticator"),
        ("gal3@lp.com", "gal3", "password", ["admin"], True, 331122, "mail"),
    ]
    count = count or len(users)

    for u in users[:count]:
        pw = u[2]
        if pw is not None:
            pw = hash_password(pw)
        roles = [ds.find_or_create_role(rn) for rn in u[3]]
        ds.commit()
        totp_secret = None
        if app.config.get("SECURITY_TWO_FACTOR", None) and u[6]:
            totp_secret = app.security._totp_factory.generate_totp_secret()
        user = ds.create_user(
            email=u[0],
            username=u[1],
            password=pw,
            active=u[4],
            security_number=u[5],
            tf_primary_method=u[6],
            tf_totp_secret=totp_secret,
        )
        ds.commit()
        for role in roles:
            ds.add_role_to_user(user, role)
        ds.commit() 
Example #14
Source File: test_hashing.py    From flask-security with MIT License 5 votes vote down vote up
def test_argon2_speed(app, sqlalchemy_datastore):
    init_app_with_options(
        app,
        sqlalchemy_datastore,
        **{
            "SECURITY_PASSWORD_HASH": "argon2",
            "SECURITY_PASSWORD_HASH_PASSLIB_OPTIONS": {"argon2__rounds": 10},
        }
    )
    with app.app_context():
        print(
            "Hash time for {} iterations: {}".format(
                100, timeit.timeit(lambda: hash_password("pass"), number=100)
            )
        ) 
Example #15
Source File: test_hashing.py    From flask-security with MIT License 5 votes vote down vote up
def test_bcrypt_speed(app, sqlalchemy_datastore):
    init_app_with_options(
        app,
        sqlalchemy_datastore,
        **{
            "SECURITY_PASSWORD_HASH": "bcrypt",
            "SECURITY_PASSWORD_SALT": "salty",
            "SECURITY_PASSWORD_SINGLE_HASH": False,
        }
    )
    with app.app_context():
        print(timeit.timeit(lambda: hash_password("pass"), number=100)) 
Example #16
Source File: test_hashing.py    From flask-security with MIT License 5 votes vote down vote up
def test_verify_password_argon2(app, sqlalchemy_datastore):
    init_app_with_options(
        app, sqlalchemy_datastore, **{"SECURITY_PASSWORD_HASH": "argon2"}
    )
    with app.app_context():
        hashed_pwd = hash_password("pass")
        assert verify_password("pass", hashed_pwd)
        assert "t=10" in hashed_pwd

        # Verify double hash
        assert verify_password("pass", argon2.hash(get_hmac("pass"))) 
Example #17
Source File: test_hashing.py    From flask-security with MIT License 5 votes vote down vote up
def test_verify_password_backward_compatibility(app, sqlalchemy_datastore):
    init_app_with_options(
        app,
        sqlalchemy_datastore,
        **{
            "SECURITY_PASSWORD_HASH": "bcrypt",
            "SECURITY_PASSWORD_SINGLE_HASH": False,
            "SECURITY_PASSWORD_SCHEMES": ["bcrypt", "plaintext"],
        }
    )
    with app.app_context():
        # double hash
        assert verify_password("pass", hash_password("pass"))
        # single hash
        assert verify_password("pass", plaintext.hash("pass")) 
Example #18
Source File: test_hashing.py    From flask-security with MIT License 5 votes vote down vote up
def test_verify_password_bcrypt_single_hash(app, sqlalchemy_datastore):
    init_app_with_options(
        app,
        sqlalchemy_datastore,
        **{
            "SECURITY_PASSWORD_HASH": "bcrypt",
            "SECURITY_PASSWORD_SALT": None,
            "SECURITY_PASSWORD_SINGLE_HASH": True,
        }
    )
    with app.app_context():
        assert verify_password("pass", hash_password("pass")) 
Example #19
Source File: test_hashing.py    From flask-security with MIT License 5 votes vote down vote up
def test_verify_password_bcrypt_double_hash(app, sqlalchemy_datastore):
    init_app_with_options(
        app,
        sqlalchemy_datastore,
        **{
            "SECURITY_PASSWORD_HASH": "bcrypt",
            "SECURITY_PASSWORD_SALT": "salty",
            "SECURITY_PASSWORD_SINGLE_HASH": False,
        }
    )
    with app.app_context():
        assert verify_password("pass", hash_password("pass")) 
Example #20
Source File: 04_2a3fee7de8d4_.py    From betterlifepsi with MIT License 4 votes vote down vote up
def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    import flask_security.utils as security_utils
    role_table = op.create_table('role',
                                 sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
                                 sa.Column('name', sa.String(length=80), nullable=True),
                                 sa.Column('description', sa.String(length=255), nullable=True),
                                 sa.PrimaryKeyConstraint('id'),
                                 sa.UniqueConstraint('name')
                                 )
    op.bulk_insert(role_table, [
        {'id': 1, 'name': 'admin', 'description': 'admin role'},
    ], multiinsert=False)
    from sqlalchemy.sql import text
    op.get_bind().execute(text("ALTER SEQUENCE role_id_seq RESTART WITH 2;"))
    user_table = op.create_table('user',
                                 sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
                                 sa.Column('login', sa.String(length=64), nullable=False, unique=True),
                                 sa.Column('display', sa.String(length=255), nullable=False),
                                 sa.Column('email', sa.String(length=255), nullable=True),
                                 sa.Column('password', sa.String(length=255), nullable=True),
                                 sa.Column('active', sa.Boolean(), nullable=True),
                                 sa.PrimaryKeyConstraint('id'),
                                 sa.UniqueConstraint('email')
                                 )
    hashed_password = security_utils.hash_password('password')
    op.bulk_insert(user_table, [
        {'id': 1, 'login': 'admin', 'display': 'Administrator',
         'email': 'support@betterlife.io',
         'password': hashed_password,
         'active': True},
    ], multiinsert=False)
    op.get_bind().execute(text("ALTER SEQUENCE user_id_seq RESTART WITH 2;"))
    roles_users_table = op.create_table('roles_users',
                                        sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
                                        sa.Column('user_id', sa.Integer(), nullable=True),
                                        sa.Column('role_id', sa.Integer(), nullable=True),
                                        sa.ForeignKeyConstraint(['role_id'], ['role.id'], ),
                                        sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
                                        sa.PrimaryKeyConstraint('id'),
                                        )
    op.bulk_insert(roles_users_table, [
        {'id': 1, 'user_id': 1, 'role_id': 1},
    ], multiinsert=False)
    op.get_bind().execute(text("ALTER SEQUENCE roles_users_id_seq RESTART WITH 2;"))
    ### end Alembic commands ###