[PYTHON] I was able to implement web app authentication with flask-login

Overview

I am creating a web application using flask. I was able to implement it with almost the README copy and paste of the site I referred to below. The code in this article needs to write the logic for password matching.

The site that I used as a reference

https://github.com/maxcountryman/flask-login

Official documentation for flask-login https://flask-login.readthedocs.io/en/latest/

Description of flask-login

Flask-Login provides Flask user session management. Handles common tasks such as login, logout, and long-term user session memory.

Implementation

$ 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 = {'[email protected]': {'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)

test

You may want to implement it based on the following. https://github.com/maxcountryman/flask-login/blob/master/test_login.py

Recommended Posts

I was able to implement web app authentication with flask-login
I tried to implement CVAE with PyTorch
I was addicted to not being able to get an email address from google with django-allauth authentication
I was able to recurse in Python: lambda
I was able to mock AWS-Batch with python, moto, so I will leave it
I tried to implement and learn DCGAN with PyTorch
I tried to implement Minesweeper on terminal with python
I was addicted to scraping with Selenium (+ Python) in 2020
I tried to implement an artificial perceptron with python
I tried to implement time series prediction with GBDT
I tried to implement Grad-CAM with keras and tensorflow
I tried to implement SSD with PyTorch now (Dataset)
I was able to repeat it in Python: lambda
Deploy a web app created with Streamlit to Heroku
A beginner tried coloring line art with chainer. I was able to do it.
How to deploy a web app made with Flask to Heroku
I want to be able to analyze data with Python (Part 3)
[IOS] GIF animation with Pythonista3. I was addicted to it.
I want to be able to analyze data with Python (Part 1)
I tried to implement breakout (deception avoidance type) with Quantx
I tried to implement PCANet
I want to be able to analyze data with Python (Part 4)
I want to be able to analyze data with Python (Part 2)
I tried to implement ListNet of rank learning with Chainer
I tried to implement Harry Potter sort hat with CNN
I tried to implement StarGAN (1)
I tried to implement SSD with PyTorch now (model edition)
Note that I was addicted to accessing the DB with Python's mysql.connector using a web application.
I made a web server with Raspberry Pi to watch anime
What I was addicted to with json.dumps in Python base64 encoding
I tried to summarize what was output with Qiita with Word cloud
A note I was addicted to when creating a table with SQLAlchemy
I tried to implement sentence classification by Self Attention with PyTorch
I tried to implement Deep VQE
I tried web scraping with python.
I tried to implement adversarial validation
I tried to implement hierarchical clustering
I want to do ○○ with Pandas
I tried to implement Realness GAN
I want to debug with Python
I was addicted to multiprocessing + psycopg2
I was able to print the thermal printer "PAPERANG" from Python (Windows10, Python3.6)
I tried to implement deep learning that is not deep with only NumPy
I tried to implement a blockchain that actually works with about 170 lines
I was addicted to running tensorflow on GPU with NVIDIA driver 440 + CUDA 10.2
I was addicted to creating a Python venv environment with VS Code
A story I was addicted to trying to get a video url with tweepy
Use Python from Java with Jython. I was also addicted to it.
I tried to get the authentication code of Qiita API with Python.
I was addicted to not being able to use Markdown on pypi's long_description
I was addicted to trying Cython with PyCharm, so make a note
I was able to machine learn the sorting algorithm (with variable length & order flag) with RNN that manipulates memory!
I tried to implement PLSA in Python
I want to detect objects with OpenCV
I tried to implement permutation in Python
I tried to visualize AutoEncoder with TensorFlow
Play like a web app with ipywidgets
I tried to get started with Hy
I want to blog with Jupyter Notebook
I tried to implement PLSA in Python 2
I was addicted to pip install mysqlclient