18
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

flask-loginでWebアプリの認証を実装できた

Last updated at Posted at 2020-04-21

概要

flaskを使用したWebアプリを作成しています。
以下の参考にさせて頂いたサイトのREADMEコピペほぼで実装できました。
本記事のコードはpassword照合のロジックを書く必要があります。

参考にさせて頂いたサイト

flask-loginの公式ドキュメント
https://flask-login.readthedocs.io/en/latest/

flask-loginの説明

Flask-Loginは、Flaskのユーザーセッション管理を提供します。ログイン、ログアウト、長期間のユーザーセッションの記憶といった一般的なタスクを処理します。

実装

$ pip install flask flask-login
import flask
import flask_login


login_manager = flask_login.LoginManager()
login_manager.init_app(app)

app = flask.Flask(__name__)
app.secret_key = 'super secret string'  # Change this!

# Our mock database.
users = {'foo@bar.tld': {'password': 'secret'}}

class User(flask_login.UserMixin):
    pass


@login_manager.user_loader
def user_loader(email):
    if email not in users:
        return

    user = User()
    user.id = email
    return user


@login_manager.request_loader
def request_loader(request):
    email = request.form.get('email')
    if email not in users:
        return

    user = User()
    user.id = email

    # DO NOT ever store passwords in plaintext and always compare password
    # hashes using constant-time comparison!
    user.is_authenticated = request.form['password'] == users[email]['password']

    return user

@app.route('/login', methods=['GET', 'POST'])
def login():
    if flask.request.method == 'GET':
        return '''
               <form action='login' method='POST'>
                <input type='text' name='email' id='email' placeholder='email'/>
                <input type='password' name='password' id='password' placeholder='password'/>
                <input type='submit' name='submit'/>
               </form>
               '''

    email = flask.request.form['email']
    if flask.request.form['password'] == users[email]['password']:
        user = User()
        user.id = email
        flask_login.login_user(user)
        return flask.redirect(flask.url_for('protected'))

    return 'Bad login'


@app.route('/protected')
@flask_login.login_required
def protected():
    return 'Logged in as: ' + flask_login.current_user.id

@app.route('/logout')
def logout():
    flask_login.logout_user()
    return 'Logged out'

@login_manager.unauthorized_handler
def unauthorized_handler():
    return 'Unauthorized'

if __name__ == '__main__':
    app.run(host="0.0.0.0",port=8000,debug=True)

テスト

以下を元に実装してみるとよいかもしれません。
https://github.com/maxcountryman/flask-login/blob/master/test_login.py

18
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?