下面是我的代码,我试图让装饰器验证所需的flask角色,但似乎不起作用。我不确定自己做错了什么。我尝试了几种不同的方法,但似乎都没有效果。
有人可以使用基于角色的访问控制的经验或模板吗?
app= Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:admin@localhost/sys'
app.config['SECRET_KEY'] = 'mysecret'
db = SQLAlchemy(app)
login = LoginManager(app)
login.init_app(app)
login.login_view = 'login'
LOGIN_URL='/login'
@login.user_loader
def load_user(user_id):
return Users.query.get(user_id)
class Users(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20))
password = db.Column(db.String(200))
roles = db.Column(db.String(100))
def is_authenticated(self):
return True
def is_active(self):
return True
def has_roles(self):
return True
@app.route('/vendorreview')
@login_required
@roles_required('admin')
def vendorreview():
return render_template('review.html')
@app.route('/register')
@login_required
def register():
return render_template('register.html')
@app.route('/submit')
def submit():
if not session.get('logged_in'):
return render_template('login.html')
else:
return render_template('submit.html')
return render_template('submit.html')
@app.route('/error')
def error():
return render_template('error.html')
@app.route("/login", methods=['GET', 'POST'])
def login():
error = None
x='customer'
if request.method == 'POST':
if request.form['username'] == 'admin' and request.form['password'] == 'admin' and x == 'business':
session['logged_in'] = True
# get_role = 'admin'
return redirect(url_for('index'))
#for customers
elif request.form['username'] == 'admin' and request.form['password'] == 'admin' and x == 'customer':
session['logged_in'] = True
return redirect(url_for('index'))
else:
error = 'Invalid Credentials. Please try again.'
return render_template('login.html', error=error)
if __name__ == '__main__':
app.secret_key = os.urandom(12)
app.run(debug=True)