• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python security.generate_password_hash函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中webapp2_extras.security.generate_password_hash函数的典型用法代码示例。如果您正苦于以下问题:Python generate_password_hash函数的具体用法?Python generate_password_hash怎么用?Python generate_password_hash使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: find_or_update

 def find_or_update(self, request):
     """Find  User or update password"""
     account = User.get_by_email(self.email)
     logging.error('Ther You go hiud')
     if request == 'GET':
         if account is not None:
             if account.password == ceaser_cipher(self.password):
                 return account.email, 0
             else:
                 return None, 404
         else:
             return None, 404
     else:
         if account is not None:
             if self.password is None:
                 Password = id_generator()
                 account.password = security.generate_password_hash(
                     Password, length=12)
                 account.active = False
                 return account.email, 406
             else:
                 account.password = security.generate_password_hash(
                     self.Password, length=12)
                 account.active = True
                 return account.email, 407
         else:
             return None, 405
开发者ID:AnikChat,项目名称:EngineApp,代码行数:27,代码来源:forms.py


示例2: test_create_check_password_hash

    def test_create_check_password_hash(self):
        self.assertRaises(TypeError, security.generate_password_hash, 'foo',
                          'bar')

        password = 'foo'
        hashval = security.generate_password_hash(password, 'sha1')
        self.assertTrue(security.check_password_hash(password, hashval))

        hashval = security.generate_password_hash(password, 'sha1', pepper='bar')
        self.assertTrue(security.check_password_hash(password, hashval,
                                                     pepper='bar'))

        hashval = security.generate_password_hash(password, 'md5')
        self.assertTrue(security.check_password_hash(password, hashval))

        hashval = security.generate_password_hash(password, 'plain')
        self.assertTrue(security.check_password_hash(password, hashval))

        hashval = security.generate_password_hash(password, 'plain')
        self.assertFalse(security.check_password_hash(password, ''))

        hashval1 = security.hash_password(unicode(password), 'sha1', u'bar')
        hashval2 = security.hash_password(unicode(password), 'sha1', u'bar')
        self.assertTrue(hashval1 is not None)
        self.assertEqual(hashval1, hashval2)

        hashval1 = security.hash_password(unicode(password), 'md5', None)
        hashval2 = security.hash_password(unicode(password), 'md5', None)
        self.assertTrue(hashval1 is not None)
        self.assertEqual(hashval1, hashval2)
开发者ID:AgentJay,项目名称:webapp-improved,代码行数:30,代码来源:extras_security_test.py


示例3: post

    def post(self, code):
        errors = []
        data = {
            'page_title': 'Reset Password',
            'errors': errors,
        }

        password = self.request.get('password')
        password_verify = self.request.get('password-verify')
        if not password or password != password_verify:
            errors.append(
                "Missing password or both passwords didn't match. Please try "
                "again."
            )
        else:
            user = User.user_from_reset_code(code)
            if not user:
                errors.append(
                    'No account for this reset code! Please contact admin.'
                )
            else:
                hash_pass = generate_password_hash(password)
                user.password = hash_pass
                user.pass_reset_code = None
                user.pass_reset_expire = None
                user.put()
                self.redirect('/login')
                return

        # reach here when there is an error to report
        self.render('password.html', **data)
开发者ID:PreludeAndFugue,项目名称:prelude-hmpc,代码行数:31,代码来源:user_admin.py


示例4: post

	def post(self):
		username = self.request.get('username')
		email = self.request.get('email')
		password = self.request.get('password')

		test_key = db.Key.from_path('User',email)
		test_user = db.get(test_key)
		if test_user == None:
			newUser = User(key_name = email)
			newUser.email = email
			newUser.name = username
			newUser.password = security.generate_password_hash(password,length=12)
			newUser.friends_list = []
			newUser.event_key_list = []
			newUser.auth_id = email
			newUser.all_start = []
			newUser.all_end = []
			newUser.all_content = []
			newUser.all_group = []
			newUser.all_className = []
			newUser.total_events = 0
			newUser.put()

			# user_id = newUser.get_id()

			# token = self.user_model.create_signup_token(user_id)

			u = self.auth().get_user_by_password(email,password,remember=True)

			self.redirect('/home')
		else:
			self.redirect('/?src=fail_signup')
开发者ID:JishnuM,项目名称:Demeetr,代码行数:32,代码来源:demeetr.py


示例5: __init__

 def __init__(self,hs=None, pw=None,pepper=None):
     if hs is None and  pw is None:
         self.hs=None
     elif hs:
         self.hs=hs
     else:
         self.hs=security.generate_password_hash(pw,pepper=pepper)
开发者ID:danielmsilverio,项目名称:danielaap,代码行数:7,代码来源:property.py


示例6: create_user

    def create_user(cls, auth_id, **user_values):
        assert user_values.get('password') is None, \
            'Use password_raw instead of password to create new users.'

        assert not isinstance(auth_id, list), \
            'Creating a user with multiple auth_ids is not allowed, ' \
            'please provide a single auth_id.'

        if 'password_raw' in user_values:
            user_values['password'] = security.generate_password_hash(
                user_values.pop('password_raw'), length=12)

        user_values['auth_ids'] = [auth_id]
        user = cls(**user_values)

        # Set up unique properties
        uniques = []
        user_values['auth_id'] = auth_id
        for name in cls.unique_properties:
            key = '%s.%s:%s' % (cls.__name__, name, user_values[name])
            uniques.append((key, name))

        ok, existing = cls.unique_model.create_multi(k for k, v in uniques)
        if ok:
            user.put()
            return True, user
        else:
            properties = [v for k, v in uniques if k in existing]
            return False, properties
开发者ID:gsakkis,项目名称:webapp2-user-accounts,代码行数:29,代码来源:models.py


示例7: changeNPass

def changeNPass(email, passW):
    print email
    user = Users.query(Users.email == email).get()
    
    pwEncrypt = security.generate_password_hash(passWord, 'sha1').strip()
    user.pw = pwEncrypt
    user.put()
开发者ID:dsn9,项目名称:Fashion-Share,代码行数:7,代码来源:userModel.py


示例8: create

    def create(cls, id=None, parent=None, key=None, **user_values):
        """Create a new user and add it to the datastore.

        The user can be given either by setting id and possibly parent, or by
        setting key, but not both. If id is set, then the new user gets a key
        based on id, a string or int, and parent, which should be an ndb.Key.
        If key is set, then it becomes the new key of the entity.
        
        Return the new user, or None if the user already exists. May throw an
        ndb.TransactionFailedError.

        """
        assert user_values.get('password') is None, \
               "Use password_raw instead of password to create new users."

        assert (id or key) and not (id and key), \
               "Give an id or a key, but not both."
        
        if 'password_raw' in user_values:
            user_values['password'] = security.generate_password_hash(
                user_values.pop('password_raw'), length=12)
            
        user = cls(id=id, parent=parent, key=key, **user_values)

        if put_if_not_present(user):
            return user
        return None
开发者ID:tobiasljohnson,项目名称:registry,代码行数:27,代码来源:models.py


示例9: post

    def post(self):

        password1 = self.request.get('password1').encode('utf-8')
        password2 = self.request.get('password2').encode('utf-8')
        key = self.request.get('key').encode('utf-8')
        email = self.request.get('email').encode('utf-8')

        if not hasNumbersAndLetters.match(password1):
            self.response.write(html.password_reset(key, numbers_and_letters=True))
            return
        if not correctLength.match(password1):
            self.response.write(html.password_reset(key, password_length=True))
            return
        if password1 != password2:
            self.response.write(html.password_reset(key, passwords_different=True))
            return

        passwordReset = db.get(key)
        if not passwordReset: #or passwordReset expired
            self.redirect(REDIRECT + "?token_expired=true&email=" + email)
            return

        user = my_db.get(passwordReset.email)
        if user.password:
            user.previous_passwords.append(user.password)
        user.password_resets += 1

        user.password = security.generate_password_hash(password1)
        user.login_attempts = 0
        user.put()
        passwordReset.delete()
        self.response.write('Password reset.')
开发者ID:whamtet,项目名称:gae-webstore,代码行数:32,代码来源:reset.py


示例10: post

    def post(self, user_id, token):
        verify = models.User.get_by_auth_token(int(user_id), token)
        user = verify[0]
        password = str(self.request.POST.get('password')).strip()
        c_password = str(self.request.POST.get('c_password')).strip()
        if user:
            if password == "" or c_password == "":
                message = 'Password required.'
                self.add_message(message, 'error')
                return self.redirect_to('password-reset-check', user_id=user_id, token=token)

            if password != c_password:
                message = 'Sorry, Passwords are not identical, ' \
                          'you have to repeat again.'
                self.add_message(message, 'error')
                return self.redirect_to('password-reset-check', user_id=user_id, token=token)

            # Password to SHA512
            password = utils.encrypt(password, config.salt)
        
            user.password = security.generate_password_hash(password, length=12)
            user.put()
            # Delete token
            models.User.delete_auth_token(int(user_id), token)
            # Login User
            self.auth.get_user_by_password(user.auth_ids[0], password)
            self.add_message('Password changed successfully', 'success')
            return self.redirect_to('secure')

        else:
            self.add_message('Please correct the form errors.', 'error')
            return self.redirect_to('password-reset-check', user_id=user_id, token=token)
开发者ID:f1shear,项目名称:gae-boilerplate,代码行数:32,代码来源:handlers.py


示例11: create_user

    def create_user(cls, username=None, raw_password=None, email=None):
        """
        Create a Login instance, but method NOT PUT Login TO DB
        You must run _.put() manually after creating the instance.

        :param username:
            username string
        :param raw_password:
            raw_password string
        :param email:
            emal (optional)
        :return:
            Login instance or None
        """
        logging.info('LoginClass:create_user() => Start creating user')

        if not(username and raw_password):
            logging.error('LoginClass:create_user() => username or raw_password is empty, return None')
            return None

        salt = security.generate_random_string(length=30)
        logging.info('LoginClass:create_user() => Making salt for password hash ... < %s >' % salt)

        pw_hash = security.generate_password_hash(raw_password, pepper=PEPPER)
        logging.info('LoginClass:create_user() => Generatin password hash ... < %s >' % pw_hash)
        u = Login()
        u.populate(username=username,
                   pw_hash=pw_hash,
                   email=email)
        logging.info('LoginClass:create_user() => Make and return Login instance')
        return u
开发者ID:yurasid,项目名称:CS253-final-wiki,代码行数:31,代码来源:user_model.py


示例12: set_password

 def set_password(self, raw_password):
     """Sets the password for the current user
     
     :param raw_password:
         The raw password which will be hashed and stored
     """
     self.password = security.generate_password_hash(raw_password, length=12)
开发者ID:aaronlifshin,项目名称:howtosavedemocaracy,代码行数:7,代码来源:whysaurususer.py


示例13: post

    def post(self):
        form = forms.NewGameForm(self.request.POST)
        form.color1.choices = [(key, key) for key in _primaryColors.keys()]
        form.color2.choices = [(key, key) for key in _bonusColors.keys()]
        if form.validate():

            #player
            p = models.player()
            p.isAdmin = True
            p.score = 0
            p.primaryColor = form.color1.data
            p.bonusColor = form.color2.data
            p.put()
            
            #game
            g = models.game()
            g.name = form.name.data
            g.password =  security.generate_password_hash(form.password.data)
            g.primaryColorsChosen.append(form.color1.data)
            g.bonusColorsChosen.append(form.color2.data)
            g.players.append(p.key)
            g.put()

            #user
            
            self.user.players.append(p.key)
            self.user.put()

            self.redirect(self.uri_for('game', game_id=g.key.id()))

        context = {'form': form}
        self.render_response('NewGame.html', **context)
开发者ID:jpeepers,项目名称:jeeperspeepersgame,代码行数:32,代码来源:handlers.py


示例14: create_user

 def create_user(cls, username, password):
     password = generate_password_hash(password,
                                       method='sha1',
                                       length=22,
                                       pepper=config.pepper)
     user = cls(username=username, password=password)
     user.put()
     return user
开发者ID:soofaloofa-zz,项目名称:cloudpypi,代码行数:8,代码来源:main.py


示例15: create

 def create(cls, email, first_name, last_name, device_token, password=None):
     if not password:
         password = 'makethisrandom'
     password_hash = generate_password_hash(password, pepper=PEPPER)
     user = cls(key_name=email, first_name=first_name, last_name=last_name, device_token=device_token, password=password_hash)
     UserDocument().create(email, name="%s %s"%(first_name, last_name))
     user.put()
     return user
开发者ID:mschwalb,项目名称:photobout,代码行数:8,代码来源:user.py


示例16: post

    def post(self):

        name = self.request.get('name')
        email = self.request.get('email')
        password = self.request.get('password')

        fbauth = None

        if self.request.session:
            stored_fb  = self.request.session.data.get('facebook_appcenter',None)

            if stored_fb:
                fbauth = pickle.loads(str(stored_fb))
                email = fbauth['user_info']['email']
                fb_auth_id = authprovider.AuthProvider.generate_auth_id('facebook', fbauth['user_info']['id'])

        if not name or not email or not password:
            raise Exception('Error not all values passed')

        auth_id = authprovider.AuthProvider.generate_auth_id('password', email)

        matched_at = authprovider.AuthProvider.get_by_auth_id(auth_id)

        password_hash = security.generate_password_hash(password=password,pepper=shg_utils.password_pepper)

        if fbauth is None:

            if matched_at:
                return self.json_response(json.dumps({'failure':'Email already exists in system &raquo; <a href="#login" class="btn btn-small btn-success" data-toggle="modal" >Login or reset password</a>'}))

            token = _user.EmailVerify.get_or_create(name=name,email=email,password_hash=password_hash)

            reason = token.limited()

            if reason:
                return self.json_response(json.dumps({'failure':reason}))

            if token.send_email(self.request.host_url):
                return self.json_response(json.dumps({'success':'Validation email sent. Please check your inbox!'}))
            else:
                return self.json_response(json.dumps({'failure':'Unable to send email - please try again shortly'}))
        else:

            if not matched_at:
                new_user = _user.User._create(display_name=name,verified_email=email)
                auth_id = authprovider.AuthProvider.generate_auth_id('password', email)
                new_at = authprovider.AuthProvider._create(user=new_user,auth_id=auth_id,password_hash=password_hash)
            else:
                new_user = _user.User._get_user_from_id(matched_at.user_id)

            new_fb_at = authprovider.AuthProvider._create(user=new_user,
                auth_id=fb_auth_id,
                user_info=fbauth['user_info'],
                credentials=fbauth['credentials'])

            self.request.session.upgrade_to_user_session(new_user._get_id())

            return self.json_response(json.dumps({'success':'Thank you for registering','redirect':'/'}))
开发者ID:xlfe,项目名称:sharehousegame,代码行数:58,代码来源:auth.py


示例17: update

    def update( self, email, username, password ):
        """ Updates the User with new parameters.

        :param email:
            The new email_pending for the user
        :param username:
            The new username to assign to the user
        :param password:
            The new password to assign to the user
        :returns:
            A tuple (boolean, info) where on success, (True, user) is returned
            and on failure, (False, list) is returned where list gives names
            of the properties that conflict with existing unique properties.
        """
        # Set up unique properties
        uniques = [ ]
        if self.username_lower != username.lower( ):
            key = '%s.%s:%s' % ( self.__class__.__name__, 'username',
                                 username.lower( ) )
            uniques.append( ( key, 'username' ) )
        if( email
            and self.email_pending_lower != email.lower( )
            and self.email_verified_lower != email.lower( ) ):
            key = '%s.%s:%s' % ( self.__class__.__name__, 'email',
                                 email.lower( ) )
            uniques.append( ( key, 'email' ) )

        ok, existing = self.unique_model.create_multi( k for k, v in uniques )
        if ok:
            # No overlap with existing unique properties.
            # Remove the old unique values from the datastore.
            values = [ ]
            if self.username_lower != username.lower( ):
                key = '%s.%s:%s' % ( self.__class__.__name__, 'username',
                                     self.username_lower )
                values.append( key )
            if( self.email_pending
                and ( self.email_pending_lower != email.lower( ) )
                and ( self.email_pending_lower
                      != self.email_verified_lower ) ):
                key = '%s.%s:%s' % ( self.__class__.__name__, 'email',
                                     self.email_pending_lower )
                values.append( key )
            self.unique_model.delete_multi( values )

            # Update user
            self.username = username
            self.email_pending = email
            if password:
                self.password = security.generate_password_hash(
                    password, length=12 )
            self.put( )
            return True, self

        else:
            # Overlap with existing unique properties
            properties = [ v for k, v in uniques if k in existing ]
            return False, properties
开发者ID:rggibson,项目名称:Authtopus,代码行数:58,代码来源:models.py


示例18: register

def register():
	register_error = None
	form = RegisterFormExt(csrf_enabled=False)
	if request.method == 'POST' and form.validate():
		password = security.generate_password_hash(form.password.data, length=32)
		user = Users(username=form.username.data, password=password)
		user.put()
		return redirect(url_for('login'), code=302)
	return render_template('register.html', form=form, register_error=register_error)
开发者ID:jideobs,项目名称:flask-gae-ndb-starter,代码行数:9,代码来源:main.py


示例19: _set_password

    def _set_password(self, password):
        # TODO switch password encryption to bcrypt
        """
        Set the User's password attribute to the hashed password generated
        from the supplied password string

        :param password: a string representing the password
        """
        self.password = security.generate_password_hash(password, length=12)
开发者ID:russomi,项目名称:aecore,代码行数:9,代码来源:models.py


示例20: post

    def post(self):
        """
              Get fields from POST dict
        """
        if not self.form.validate():
            return self.get()
        current_password = self.form.current_password.data.strip()
        password = self.form.password.data.strip()

        try:
            user_info = models.User.get_by_id(long(self.user_id))
            auth_id = "own:%s" % user_info.username

            # Password to SHA512
            current_password = utils.encrypt(current_password, config.salt)
            try:
                user = models.User.get_by_auth_password(auth_id, current_password)
                # Password to SHA512
                password = utils.encrypt(password, config.salt)
                user.password = security.generate_password_hash(password, length=12)
                user.put()
                
                # send email
                subject = config.app_name + " Account Password Changed"

                # load email's template
                template_val = {
                    "app_name": config.app_name,
                    "first_name": user.name,
                    "username": user.username,
                    "email": user.email,
                    "reset_password_url": self.uri_for("password-reset", _full=True)
                }
                email_body_path = "emails/password_changed.txt"
                email_body = self.jinja2.render_template(email_body_path, **template_val)
                email_url = self.uri_for('taskqueue-send-email')
                taskqueue.add(url = email_url, params={
                    'to': user.email,
                    'subject' : subject,
                    'body' : email_body,
                    'sender' : config.contact_sender,
                    })

                #Login User
                self.auth.get_user_by_password(user.auth_ids[0], password)
                self.add_message(_('Password changed successfully'), 'success')
                return self.redirect_to('secure')
            except (InvalidAuthIdError, InvalidPasswordError), e:
                # Returns error message to self.response.write in
                # the BaseHandler.dispatcher
                message = _("Your Current Password is wrong, please try again")
                self.add_message(message, 'error')
                return self.redirect_to('edit-password')
        except (AttributeError,TypeError), e:
            login_error_message = _('Sorry you are not logged in!')
            self.add_message(login_error_message,'error')
            self.redirect_to('login')
开发者ID:mfkasim91,项目名称:gae-boilerplate,代码行数:57,代码来源:handlers.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python security.generate_random_string函数代码示例发布时间:2022-05-26
下一篇:
Python json.encode函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap