FlaskにてFlask-loginを使用してsessionのタイムアウト設定を行いました。
パスワードのハッシュ化、セッションのタイムアウト後にログイン画面に推移します。
###app.py
#import
from flask import Flask, session, app
from flask import render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin, LoginManager, login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
#app
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SECRET_KEY'] = os.rundum
app.config['PERMANENT_SESSION_LIFETIME'] = timedalta(minutes=10)#session time(10分)
db.SQLAlchemy(app)
#flask-login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login' #redirect login
#user table
class User(UserMixin,db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
authority = db.Column(db.String(15), nullable=False)
password = db.Column(db.String(15), nullable=False)
#login_manager
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
#signup
@app.route("/signup", methods=['GET','POST'])
@login_required
def signup():
if request.method == 'POST':
authority = request.form.get('authority')
password = request.form.get('password')
if authority == '':
err_msg = "権限を入力してください"
return render_template('auth/signup.html', err_msg = err_msg)
elif password == '':
err_msg = "パスワードを入力してください"
return render_template('auth/signup.html', err_msg = err_msg)
else:
user = User(authority = authority, password = generate_password_hash(password, method='sha256')) #password hash
db.session.add(user)
db.session.commit()
return render_template('auth/signup.html', authority = authority, password = password)
else:
return render_template('auth/signup.html')
#login
@app.route("/login",methods=['GET','POST'])
def login():
session.permanent = True #make session permanent
if request.method == 'POST':
password = request.form.get('password')
user1 = User.query.filter_by(authority = "host").one_or_name()
user2 = User.query.filter_by(authority = "common").one_or_name()
if check_password_hash(user1.password, password):
login_user(user = user1)
next = request.args.get('next')
return redirect(next or url_for('search'))
elif check_password_hash(user2.password, password):
login_user(user = user2)
next = request.args.get('next')
return redirect(next or url_for('search'))
else:
err_msg = "パスワードがなし又は違います。"
return render_template('auth/login.html', err_msg = err_msg)
else:
return render_template('auth/login.html')