當前位置: 首頁>>代碼示例>>Python>>正文


Python security.generate_password_hash方法代碼示例

本文整理匯總了Python中werkzeug.security.generate_password_hash方法的典型用法代碼示例。如果您正苦於以下問題:Python security.generate_password_hash方法的具體用法?Python security.generate_password_hash怎麽用?Python security.generate_password_hash使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在werkzeug.security的用法示例。


在下文中一共展示了security.generate_password_hash方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: add_user

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def add_user(cls, identifier: str, password: str, password_encrypted: bool = False) -> None:
        """新增用戶。當用戶已存在時,拋出ValueError。

        :param identifier: 學號或教工號
        :param password: 密碼
        :param password_encrypted: 密碼是否已經被加密過了(否則會被二次加密)
        """
        if not password_encrypted:
            password_hash = generate_password_hash(password)
        else:
            password_hash = password

        user = User(identifier=identifier, password=password_hash, create_time=datetime.datetime.now())

        db_session.add(user)
        try:
            db_session.commit()
        except IntegrityError as e:
            raise AlreadyRegisteredError from e 
開發者ID:everyclass,項目名稱:everyclass-server,代碼行數:21,代碼來源:user.py

示例2: _new_request

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def _new_request(cls, identifier: str, verification_method: str, status: str, password: str = None) -> str:
        """
        新增一條注冊請求

        :param identifier: 學號/教工號
        :param verification_method: password or email
        :param status: status of the request
        :param password: if register by password, fill everyclass password here
        :return: the `request_id`
        """
        if verification_method not in (cls.METHOD_PASSWORD, cls.METHOD_EMAIL):
            raise ValueError("verification_method must be one of email and password")

        request_id = uuid.uuid4()

        extra_doc = {}
        if password:
            extra_doc.update({"password": generate_password_hash(password)})

        request = VerificationRequest(request_id=request_id, identifier=identifier, method=verification_method,
                                      status=status, extra=extra_doc)
        db_session.add(request)
        db_session.commit()

        return str(request_id) 
開發者ID:everyclass,項目名稱:everyclass-server,代碼行數:27,代碼來源:verification_request.py

示例3: create_user

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def create_user(**data):
    """Creates user with encrypted password"""
    if 'username' not in data or 'password' not in data:
        raise ValueError('username and password are required.')

    # Hash the user password
    data['password'] = generate_password_hash(
        data.pop('password'),
        method='pbkdf2:sha256'
    )

    # Here you insert the `data` in your users database
    # for this simple example we are recording in a json file
    db_users = json.load(open('users.json'))
    # add the new created user to json
    db_users[data['username']] = data
    # commit changes to database
    json.dump(db_users, open('users.json', 'w'))
    return data


# [--- Flask Factories  ---] 
開發者ID:flask-extensions,項目名稱:flask_simplelogin,代碼行數:24,代碼來源:manage.py

示例4: reset_token

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    user = User.verify_reset_token(token)
    if user is None:
        flash("That is an invalid or expired token", "warning")
        return redirect(url_for("users.reset_request"))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hash = generate_password_hash(form.password.data)
        user.password = hash
        db.session.commit()
        flash("Your password has been updated! You are now able to log in",
              "success")
        return redirect(url_for("users.login"))
    return render_template("reset_token.html",
                           title="Reset Password",
                           form=form) 
開發者ID:pxsocs,項目名稱:thewarden,代碼行數:20,代碼來源:routes.py

示例5: user_create

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def user_create():
    """
    Create users.
    :return:
    """
    form = UserForm()

    if form.validate_on_submit():
        user = User()
        user.name = form.name.data
        user.hash_pass = generate_password_hash(form.password.data)
        user.role = form.role.data
        user.email = form.email.data
        db.session.add(user)
        db.session.commit()

        return redirect(url_for('.user'))

    return render_template('admin/user_create.html', form=form) 
開發者ID:Tianny,項目名稱:incepiton-mysql,代碼行數:21,代碼來源:views.py

示例6: register

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = User()
        user.name = form.username.data
        user.hash_pass = generate_password_hash(form.password.data)
        user.email = form.email.data

        # Register user's role is dev, by default.
        user.role = 'dev'

        db.session.add(user)
        db.session.commit()

        flash('You have registered successfully. Please login! ', category='success')

        return redirect(url_for('auth.login'))

    return render_template('auth/register.html', form=form) 
開發者ID:Tianny,項目名稱:incepiton-mysql,代碼行數:21,代碼來源:views.py

示例7: register

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def register():
    """Render the register page."""
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        c = mongo.db[app.config['USERS_COLLECTION']]
        user = {
            "username": form.username.data,
            "email": form.email.data,
            "first_name": form.first_name.data,
            "last_name": form.last_name.data,
            "password": generate_password_hash(form.password.data),
            "groups": [],
            "first_active": now_time(),
            "last_active": now_time()
        }
        logger.debug("User: %s" % user)
        user_count = c.count(dict())
        if user_count == 0:  # Make the first user an administrator
            user['groups'] = ['admin']
        _id = c.insert(user)
        next = request.args.get('next')
        return redirect(next or url_for('core.login'))
    errors = ','.join([value[0] for value in form.errors.values()])
    return render_template('register.html', message=errors) 
開發者ID:9b,項目名稱:chirp,代碼行數:26,代碼來源:auth.py

示例8: create_user

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def create_user(name, email, groups, default_sharing, permissions, password=None):
    user = User.get(email=email.lower())

    if user:
        print "/!\ User with this email address already exists."
    else:
        user = User({
            'name': name,
            'email': email.lower(),
            'groups': groups,
            'default_sharing': default_sharing,
            'permissions': permissions,
            'enabled': True
        })
        if password:
            user['pwd_hash'] = generate_password_hash(password)
        user.save()
        print "[+] User created."

        user.generate_avatar()
        print "[+] Downloaded avatar."

    return user 
開發者ID:certsocietegenerale,項目名稱:fame,代碼行數:25,代碼來源:user_management.py

示例9: setup

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def setup():
    """
    Called on a new install to setup an admin account
    """
    form = SetupForm(request.form)
    if form.validate_on_submit():
        # On submit, grab form information
        project_name = form.project_name.data
        password = form.password.data
        hashed_password = generate_password_hash(password)

        # Create the account
        db = DB()
        resp = db.create(project_name, password, hashed_password, admin=True)
        if resp['status']:
            flash(u'Project successfully created!')
            return redirect(url_for('index'))
        else:
            flash(resp['message'])

    return render_template('setup.html', form=form) 
開發者ID:bitslabsyr,項目名稱:stack,代碼行數:23,代碼來源:views.py

示例10: create

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def create():
    """
    Page to create a new project account
    """
    form = CreateForm(request.form)
    if form.validate_on_submit():
        # On submit, grab form information
        project_name = form.project_name.data
        email = form.email.data
        password = form.password.data
        hashed_password = generate_password_hash(password)
        description = form.description.data

        # Create the account
        db = DB()
        resp = db.create(project_name, password, hashed_password, description=description, email=email)
        if resp['status']:
            flash(u'Project successfully created!')
            return redirect(url_for('admin_home', admin_id=g.admin['project_id']))
        else:
            flash(resp['message'])

    return render_template('create.html', form=form) 
開發者ID:bitslabsyr,項目名稱:stack,代碼行數:25,代碼來源:views.py

示例11: make_account

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def make_account(name='test', fullname='Test User',
                 email='test@example.com', twitter='testuser',
                 admin=False, password='password'):
    from spendb.model.account import Account

    # First see if the account already exists and if so, return it
    account = Account.by_name(name)
    if account:
        return account

    # Account didn't exist so we create it and return it
    account = Account()
    account.name = name
    account.fullname = fullname
    account.email = email
    account.twitter_handle = twitter
    account.admin = admin
    account.password = generate_password_hash(password)
    db.session.add(account)
    db.session.commit()
    return account 
開發者ID:openspending,項目名稱:spendb,代碼行數:23,代碼來源:helpers.py

示例12: avatar

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def avatar(self, user_id):
        random = generate_password_hash(str(user_id))
        fname = random[-10:] + '.jpg'
        current_app.logger.info(fname)

        f = request.files['avatar']
        # todo rename to uid relation
        # fname = secure_filename(f.filename)
        # TODO try
        ret = f.save(os.path.join(current_app.config['UPLOAD_AVATAR'], fname))
        user = UserModel.query.get(user_id)
        user.avatar = fname
        user.save()
        return self.render_json(data={
            'avatar': UserModel.avatar_url(user.avatar),
        }) 
開發者ID:meolu,項目名稱:walle-web,代碼行數:18,代碼來源:user.py

示例13: __create

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def __create(self, args):
        result = {"status": "success", "msg": "創建用戶成功"}
        user_path = self.app.config["AUTO_HOME"] + "/users/%s" % (args["username"])
        if not exists_path(user_path):
            mk_dirs(user_path)

            make_nod(user_path + "/config.json")

            user = {"fullname": args["fullname"],
                    "email": args["email"],
                    "passwordHash": generate_password_hash(args["password"]),
                    "data": []}
            json.dump(user, codecs.open(user_path + '/config.json', 'w', 'utf-8'))
        else:
            result["status"] = "fail"
            result["msg"] = "用戶名稱重複,創建失敗"

        return result 
開發者ID:small99,項目名稱:AutoLink,代碼行數:20,代碼來源:user.py

示例14: set_password

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def set_password(self, password):
        self.password_hash = generate_password_hash(password) 
開發者ID:PacktPublishing,項目名稱:Mastering-Python-Networking-Second-Edition,代碼行數:4,代碼來源:chapter9_9.py

示例15: set_password

# 需要導入模塊: from werkzeug import security [as 別名]
# 或者: from werkzeug.security import generate_password_hash [as 別名]
def set_password(self, password):
        """Create hashed password."""
        self.password = generate_password_hash(password, method='sha256') 
開發者ID:hackersandslackers,項目名稱:flask-session-tutorial,代碼行數:5,代碼來源:models.py


注:本文中的werkzeug.security.generate_password_hash方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。