当前位置: 首页>>代码示例>>Python>>正文


Python sha256_crypt.verify方法代码示例

本文整理汇总了Python中passlib.hash.sha256_crypt.verify方法的典型用法代码示例。如果您正苦于以下问题:Python sha256_crypt.verify方法的具体用法?Python sha256_crypt.verify怎么用?Python sha256_crypt.verify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在passlib.hash.sha256_crypt的用法示例。


在下文中一共展示了sha256_crypt.verify方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: authenticate_user

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def authenticate_user(username, password):
    """ Authenticate a user """

    try:
        user = User.query.filter_by(username=username).first()
    except OperationalError:
        db.create_all()
        user = User.query.filter_by(username=username).first()


    authenticated = False

    if user:
        authenticated = sha256_crypt.verify(password, user.password)
    else:
        time.sleep(1)
        logger.info("Authentication Error: User not found in DB: %s", username)
        return False
    
    if authenticated:
        logger.debug("Successfully Authenticated user: %s", username)
    else:
        logger.info("Authentication Failed: %s", username)

    return authenticated 
开发者ID:yantisj,项目名称:netgrph,代码行数:27,代码来源:user.py

示例2: setUp

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def setUp(self):
        super(_ExtensionTest, self).setUp()

        self.require_TEST_MODE("default")

        if not DJANGO_VERSION:
            raise self.skipTest("Django not installed")
        elif not has_min_django:
            raise self.skipTest("Django version too old")

        # reset to baseline, and verify it worked
        self.unload_extension()

        # and do the same when the test exits
        self.addCleanup(self.unload_extension)

#=============================================================================
# extension tests
#============================================================================= 
开发者ID:haynieresearch,项目名称:jarvis,代码行数:21,代码来源:test_ext_django.py

示例3: authenticate_user

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def authenticate_user(username, passwd):
    """ Authenticate a user """

    user = User.query.filter_by(username=username).first()

    authenticated = False

    if user:
        authenticated = sha256_crypt.verify(passwd, user.password)
    else:
        time.sleep(1)
        logger.info("Authentication Error: User not found in DB: %s", username)
        return False

    if authenticated:
        logger.debug("Successfully Authenticated user: %s", username)
    else:
        logger.info("Authentication Failed: %s", username)

    return authenticated 
开发者ID:yantisj,项目名称:apisrv,代码行数:22,代码来源:user.py

示例4: login

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def login(username, password):
    user = User.objects(username=username).first()
    if user is None:
        raise AuthenticationError("Invalid user")

    elif not sha256_crypt.verify(password, user.sha256_hash):
        raise AuthenticationError("Invalid password")

    else:
        return user.login() 
开发者ID:mitre,项目名称:cascade-server,代码行数:12,代码来源:users.py

示例5: post

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def post(self):
        getusername = self.get_argument("username")
        getpassword = self.get_argument("password")
        user_data = self.database.get_user_data(getusername)
        if user_data and user_data["password"] and crypt.verify(getpassword, user_data["password"]):
            self.set_secure_cookie("user", self.get_argument("username"))
            self.redirect(self.get_argument("next",
                                            self.reverse_url("main")))
        else:
            self.redirect(self.reverse_url("login")) 
开发者ID:GenealogyCollective,项目名称:gprime,代码行数:12,代码来源:handlers.py

示例6: verify

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def verify(txt, hash):
    return sha256_crypt.verify(txt, hash) 
开发者ID:datacats,项目名称:ckan-multisite,代码行数:4,代码来源:pw.py

示例7: place_login_cookie

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def place_login_cookie(pw):
    if verify(pw, ADMIN_PW):
        session['pwhash'] = _xor_encrypt(ADMIN_PW, SECRET_KEY)
        return True
    else:
        return False 
开发者ID:datacats,项目名称:ckan-multisite,代码行数:8,代码来源:pw.py

示例8: check_credentials

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def check_credentials(db_engine, username, password):
    async with db_engine.acquire() as conn:
        where = sa.and_(db.users.c.login == username,
                        sa.not_(db.users.c.disabled))
        query = db.users.select().where(where)
        ret = await conn.execute(query)
        user = await ret.fetchone()
        if user is not None:
            hashed = user[2]
            return sha256_crypt.verify(password, hashed)
    return False 
开发者ID:aio-libs,项目名称:aiohttp-security,代码行数:13,代码来源:db_auth.py

示例9: _iter_patch_candidates

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def _iter_patch_candidates(cls):
        """helper to scan for monkeypatches.

        returns tuple containing:
        * object (module or class)
        * attribute of object
        * value of attribute
        * whether it should or should not be patched
        """
        # XXX: this and assert_unpatched() could probably be refactored to use
        #      the PatchManager class to do the heavy lifting.
        from django.contrib.auth import models, hashers
        user_attrs = ["check_password", "set_password"]
        model_attrs = ["check_password", "make_password"]
        hasher_attrs = ["check_password", "make_password", "get_hasher", "identify_hasher",
                        "get_hashers"]
        objs = [(models, model_attrs),
                (models.User, user_attrs),
                (hashers, hasher_attrs),
        ]
        for obj, patched in objs:
            for attr in dir(obj):
                if attr.startswith("_"):
                    continue
                value = obj.__dict__.get(attr, UNSET) # can't use getattr() due to GAE
                if value is UNSET and attr not in patched:
                    continue
                value = get_method_function(value)
                source = getattr(value, "__module__", None)
                if source:
                    yield obj, attr, source, (attr in patched)

    #===================================================================
    # verify current patch state
    #=================================================================== 
开发者ID:haynieresearch,项目名称:jarvis,代码行数:37,代码来源:test_ext_django.py

示例10: assert_patched

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def assert_patched(self, context=None):
        """helper to ensure django HAS been patched, and is using specified config"""
        # make sure we're currently patched
        mod = sys.modules.get("passlib.ext.django.models")
        self.assertTrue(mod and mod.adapter.patched, "patch should have been enabled")

        # make sure only the expected objects have been patched
        for obj, attr, source, patched in self._iter_patch_candidates():
            if patched:
                self.assertTrue(source == "passlib.ext.django.utils",
                                "obj=%r attr=%r should have been patched: %r" %
                                (obj, attr, source))
            else:
                self.assertFalse(source.startswith("passlib."),
                                "obj=%r attr=%r should not have been patched: %r" %
                                (obj, attr, source))

        # check context matches
        if context is not None:
            context = CryptContext._norm_source(context)
            self.assertEqual(mod.password_context.to_dict(resolve=True),
                             context.to_dict(resolve=True))

    #===================================================================
    # load / unload the extension (and verify it worked)
    #=================================================================== 
开发者ID:haynieresearch,项目名称:jarvis,代码行数:28,代码来源:test_ext_django.py

示例11: test_01_overwrite_detection

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def test_01_overwrite_detection(self):
        """test detection of foreign monkeypatching"""
        # NOTE: this sets things up, and spot checks two methods,
        #       this should be enough to verify patch manager is working.
        # TODO: test unpatch behavior honors flag.

        # configure plugin to use sample context
        config = "[passlib]\nschemes=des_crypt\n"
        self.load_extension(PASSLIB_CONFIG=config)

        # setup helpers
        import django.contrib.auth.models as models
        from passlib.ext.django.models import adapter
        def dummy():
            pass

        # mess with User.set_password, make sure it's detected
        orig = models.User.set_password
        models.User.set_password = dummy
        with self.assertWarningList("another library has patched.*User\.set_password"):
            adapter._manager.check_all()
        models.User.set_password = orig

        # mess with models.check_password, make sure it's detected
        orig = models.check_password
        models.check_password = dummy
        with self.assertWarningList("another library has patched.*models:check_password"):
            adapter._manager.check_all()
        models.check_password = orig 
开发者ID:haynieresearch,项目名称:jarvis,代码行数:31,代码来源:test_ext_django.py

示例12: test_02_handler_wrapper

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def test_02_handler_wrapper(self):
        """test Hasher-compatible handler wrappers"""
        from django.contrib.auth import hashers

        passlib_to_django = DjangoTranslator().passlib_to_django

        # should return native django hasher if available
        if DJANGO_VERSION > (1,10):
            self.assertRaises(ValueError, passlib_to_django, "hex_md5")
        else:
            hasher = passlib_to_django("hex_md5")
            self.assertIsInstance(hasher, hashers.UnsaltedMD5PasswordHasher)

        hasher = passlib_to_django("django_bcrypt")
        self.assertIsInstance(hasher, hashers.BCryptPasswordHasher)

        # otherwise should return wrapper
        from passlib.hash import sha256_crypt
        hasher = passlib_to_django("sha256_crypt")
        self.assertEqual(hasher.algorithm, "passlib_sha256_crypt")

        # and wrapper should return correct hash
        encoded = hasher.encode("stub")
        self.assertTrue(sha256_crypt.verify("stub", encoded))
        self.assertTrue(hasher.verify("stub", encoded))
        self.assertFalse(hasher.verify("xxxx", encoded))

        # test wrapper accepts options
        encoded = hasher.encode("stub", "abcd"*4, rounds=1234)
        self.assertEqual(encoded, "$5$rounds=1234$abcdabcdabcdabcd$"
                                  "v2RWkZQzctPdejyRqmmTDQpZN6wTh7.RUy9zF2LftT6")
        self.assertEqual(hasher.safe_summary(encoded),
            {'algorithm': 'sha256_crypt',
             'salt': u('abcdab**********'),
             'rounds': 1234,
             'hash': u('v2RWkZ*************************************'),
             })

    #===================================================================
    # PASSLIB_CONFIG settings
    #=================================================================== 
开发者ID:haynieresearch,项目名称:jarvis,代码行数:43,代码来源:test_ext_django.py

示例13: login

# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def login():
    if request.method == 'POST':
        # Get Form Fields
        username = request.form['username']
        password_candidate = request.form['password']

        # Create cursor
        cur = mysql.connection.cursor()

        # Get user by username
        result = cur.execute("SELECT * FROM users WHERE username = %s", [username])

        if result > 0:
            # Get stored hash
            data = cur.fetchone()
            password = data['password']

            # Compare Passwords
            if sha256_crypt.verify(password_candidate, password):
                # Passed
                session['logged_in'] = True
                session['username'] = username

                flash('You are now logged in', 'success')
                return redirect(url_for('dashboard'))
            else:
                error = 'Invalid login'
                return render_template('login.html', error=error)
            # Close connection
            cur.close()
        else:
            error = 'Username not found'
            return render_template('login.html', error=error)

    return render_template('login.html')

# Check if user logged in 
开发者ID:bradtraversy,项目名称:myflaskapp,代码行数:39,代码来源:app.py


注:本文中的passlib.hash.sha256_crypt.verify方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。