[PYTHON] Creating an authentication function

# Introduction We use Flask to create an application from scratch and organize it so that you can learn the necessary technology.

-Creating a simple app with flask -Try to create a Home screen --Try to create an authentication function ← ★ Currently here -Try working with the database -Try to create CRUD function

Creating an authentication function

Creating a navigation bar

Add a navigation bar (login, logout) link to index.html. Add a navigation bar while changing to the jinja template.

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" 
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
          integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
          crossorigin="anonymous">
    <title>Flask App</title>
</head>
<body>
    <div class="container">
        <nav class='navbar navbar-expand-lg navbar-light bg-light'>
 <a class="navbar-brand" href="/"> Title </a>
            <button 
                class="navbar-toggler" 
                type="button" 
                data-toggle="collapse" 
                data-target="#nabvarNav"
                aria-controls="navbarNav"
                aria-expanded="false"
                aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
    
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="nav navbar-nav navbar-lighy">
                    <li class="nav-item">
                        <a class="nav-link" href="/login">LogIn</a>
                    </li>
                </ul>
            </div>
        </nav>
        {% block body %}{% endblock %}
        <div class="blog-body">
 There are no posts.
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
            integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
            crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
            integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" 
            crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" 
            integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" 
            crossorigin="anonymous"></script>
</body>
</html>

Creating a login form

{% extends "./index.html" %}

{% block body %}

<div class="blog-body">
    <form action="/login" method="POST">
        <div class="form-group">
 <label for = "InputTitle"> username </label>
            <input type="text" class="form-control" id="InputTitle" name="username">
        </div>
        <div class="form-group">
 <label for = "InputPassword"> Password </label>
            <input type="password" class="form-control" id="InputPassword" name="password">
        </div>
 <button type = "submit" class = "btn btn-primary"> Login </button>
    </form>
</div>
{% endblock %}
from src import app
from flask import render_template

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login')
def login():
    return render_template('login.html')

I think I was able to create a screen like this. python-flask3.png

Creating an authentication function

We will implement the process of creating user information appropriately on the code, transitioning the screen when logged in as that user, and returning to the signin screen as it is if it fails.

--Add session

In this session you will:

  1. When login is successful, session information is returned from the server side to the front end.
  2. The front end stores session information in the cookie area.
  3. After that, the front end makes a request with the session information, and the server side determines whether or not it is logged in by checking whether the information is correct.

By setting session ['logged_in'] = True after successful login, the value of logged_in in session is set to true. After that, by checking this value in the request trip, you can determine whether you are logged in.

After signing out, delete the session information.

--session key setting

Session information is encrypted using secretkey. (* This time, it is a simple one, but please set it randomly in the production environment etc.)

from flask import Flask

app = Flask(__name__)
app.config["SECRET_KEY"] = b'_5#y2L"F4Q8z\n\xec]dasfe/'

import src.views

--Adding flash on the API side

A feature called flash is used to display the action result as a message for each action such as sign-in success, failure, and sign-out.

--Using url_for

The url currently describes the link path directly, such as ['/ login']. This may change the path of the link as development progresses. At that time, the number of parts to be corrected will increase and it will be difficult. Therefore, use the [url_for] method. If you use this, it will automatically link just by specifying the method name instead of direct linking.

from src import app
from flask import flash
from flask import redirect
from flask import request
from flask import render_template
from flask import url_for
from flask import session


User = {
    'username': 'test',
    'password': 'testpass'
}

@app.route('/')
def index():
    if not session.get('logged_in'):
        return redirect('/login')
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if request.form['username'] != User['username']:
 flash (f'username is different')
        elif request.form['password'] != User['password']:
 flash (f'password is different')
        else:
            session['logged_in'] = True
 flash ('logged in')
            return redirect('/')
    return render_template('login.html')

@app.route('/logout', methods=['GET'])
def logout():
    session.pop('logged_in', None)
 flash ('logged out')
    return redirect('/')
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" 
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
          integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
          crossorigin="anonymous">
    <title>Flask App</title>
</head>
<body>
    <div class="container">
        <nav class='navbar navbar-expand-lg navbar-light bg-light'>
 <a class="navbar-brand" href="{{url_for('index')}}"> Title </a>
            <button 
                class="navbar-toggler" 
                type="button" 
                data-toggle="collapse" 
                data-target="#nabvarNav"
                aria-controls="navbarNav"
                aria-expanded="false"
                aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
    
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="nav navbar-nav navbar-lighy">
                    {% if not session.logged_in %}
                    <li class="nav-item">
                        <a class="nav-link" href="{{ url_for('login') }}">LogIn</a>
                    </li>
                    {% else %}
                    <li class="nav-item">
                        <a class="nav-link" href="{{ url_for('logout') }}">Logout</a>
                    </li>
                    {% endif %}
                </ul>
            </div>
        </nav>
        {% for message in get_flashed_messages() %}
        <div class="alert alert-info" role="alert">
            {{ message }}
        </div>
        {% endfor %}
        <div>
            {% block body %}{% endblock %}
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
            integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
            crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
            integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" 
            crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" 
            integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" 
            crossorigin="anonymous"></script>
</body>
</html>
{% extends "./index.html" %}

{% block body %}

<div class="blog-body">
    <form action="{{ url_for('login') }}" method="POST">
        <div class="form-group">
 <label for = "InputTitle"> username </label>
            <input type="text" class="form-control" id="InputTitle" name="username">
        </div>
        <div class="form-group">
 <label for = "InputPassword"> Password </label>
            <input type="password" class="form-control" id="InputPassword" name="password">
        </div>
 <button type = "submit" class = "btn btn-primary"> Login </button>
    </form>
</div>
{% endblock %}

【Typing error】 スクリーンショット 2020-12-03 23.49.48.png

スクリーンショット 2020-12-03 23.52.45.png

[When sign-in is successful] スクリーンショット 2020-12-03 23.53.40.png

[When signing out] スクリーンショット 2020-12-03 23.54.01.png

Recommended Posts

Creating an authentication function
Creating an egg with python
Try creating a CRUD function
Creating an HTTP Get box
Create user authentication function in Airflow
Studying Python Part.1 Creating an environment
Get an access token by OAuth authentication
Creating an Ubuntu 18.04 + MAAS2.4 environment starting from 0
Creating an unknown Pokemon with StyleGAN2 [Part 1]
Creating an image splitting app with Tkinter
Note when creating an environment with python
Creating an unknown Pokemon with StyleGAN2 [Part 2]
Easily implement login authentication function with Laravel
Creating a virtual environment in an Anaconda environment