我使用Flask-Security来实现身份验证系统。
以下是我从文档中使用的代码,我只添加了SECURITY_PASSWORD_HASH和SECURITY_PASSWORD_SALT配置:
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, \
UserMixin, RoleMixin, login_required
# Create app
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
app.config['SECURITY_PASSWORD_SALT'] = 'mypasswordsaltis12characterslong'
# Create database connection object
db = SQLAlchemy(app)
# Define models
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# Create a user to test with
@app.before_first_request
def create_user():
db.create_all()
user_datastore.create_user(email='matt@nobien.net', password='password')
db.session.commit()
# Views
@app.route('/')
@login_required
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()
我真的不明白为什么我的密码在db中以纯文本格式存储。 此外,当我尝试显示受密码保护的视图并输入凭据时,我收到此错误消息
ValueError: expected des_crypt hash, got des_crypt config string instead
此时我真的感到困惑,看起来我的密码存储在纯文本中,我绝对不想这样做。
感谢您的帮助
答案 0 :(得分:1)
所以我不得不添加
from flask_security.utils import encrypt_password, verify_password
并且在密码存储级别我必须调用encrypt_password函数
user_datastore.create_user(email='email@email.com', password=encrypt_password("my_password"))