Make social media applications with Flask #5: Authentication during registration and User notification

in #utopian-io6 years ago

Repository

https://github.com/python

What Will I Learn?

  • Authentication during registration
  • User notification

Requirements

  • Basic Python
  • Install Python 3
  • Install Flask

Resources

Difficulty

Basic

Tutorial Content

Hey everyone, I will still discuss the social media application that we made in the previous tutorial. In the previous tutorial, I created a login and base layout system. You can see the previous tutorial in the curriculum section. We have successfully retrieved user data while logged in. Now I will use the same function to connect to the register function that we have created.

User authentication registered

We have created a login system in our previous tutorial, now I will make user authentication when the user registers. I want to type when the user registers automatically the user will be authenticated as a valid user. So I will use the same function in a different place. Here's how to use:

app.py

@app.route('/register', methods =['GET', 'POST']) // Define route and methods
def registerPage():
    if request.method == 'POST' and request.form['username']:
        try:
            with database.atomic(): // atomic methods
                user = User.create(
                        username    = request.form['username'], // key and value from user model
                        password    = md5(request.form['password'].encode('utf-8')).hexdigest(),
                        email       = request.form['email']
                )
                auth_user(user) // Do a auth when register
            return redirect(url_for('showHomePage')) // redirect to the homepage
        except IntegrityError:
            return 'There is something error'

    return render_template('register.html') // Render template
  • I will run the authentication function that we have created in the User.create() section. After we enter the data in the user model we will automatically authenticate the user to bring them in the login section auth_user(user).

If we do a demonstration the results will be as follows:

ezgif.com-video-to-gif (2).gif

We can see in the picture above we managed to register and authenticate the user, and if we look at the database tweets.db, then we can see the user has been successfully registered and authenticated:

ezgif.com-video-to-gif (3).gif

Make user notifications

To add a better response to the user, I will add a flash message when the notification appears, To add a better response to the user, I will add a flash message when the notification appears. I will add the flash function that I will use in each response. for more details, we can see in the example below:

import the flash

from flask import Flask, render_template, request, url_for, redirect, session, flash

We have used many modules that we import, one of them is flash and now we will see how to use it in the application that we have made.

Use the flash

Now I will give an example of how to use flash in the application that we have created, I will take an example when the user logs in. The function that handles authentication is auth_user().

app.py

def auth_user(user):
    session['logged_in'] = True
    session['user_id']   = user.id
    session['username']  = user.username
    flash('You have successfully logged in '+ session['username'])

After we import, we can use it using flash('You have successfully logged in '+ session['username']). Then in the frontend section I will use bootstrap to make an alert, here is how to display the flash message that we have passed in the backend.

layout.html

{% for message in get_flashed_messages() %}
        <div class="alert alert-success" role="alert">
         {{ message }}
        </div>
    {% endfor %}

We can use for to extract messages that are in the get_flashed_message () function and the value is in variable message {{ message }}.

ezgif.com-video-to-gif (4).gif

We can see in the picture above we managed to use alerts from the bootstrap to make flash messages.

Logout Function

Our authentication system is not complete, because we haven't created a system log out for our application. I will make the new routing /logout. For more details, we can see the code below:

app.py

@app.route('/logout') // Routing logout
def logout(): / define function
    session.pop('logged_in', None) // Remove session
    flash('logout was successful') // send flash message to frontend
    return redirect(url_for('showHomePage')) // redirect to home page
  • I will make routing '/logout' and use the logout function def logout():. to be able to delete the active session we can use the pop ().

  • The pop function has two parameters, the first is the key from the session to be deleted, both of which we can give a default value session.pop('logged_in', None).

Screenshot_2.png

  • And then we will apply the flash message to our logout system

  • View when the condition is logged out

I will make a different view when the user is on login and logout, for that I will create a new menu which is the logout list menu.

layout.html

<ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="{{url_for('showHomePage')}}">Home <span class="sr-only">(current)</span></a>
      </li> // home page
      <li class="nav-item">
        <a class="nav-link" href="{{url_for('registerPage')}}">Register</a>
      </li> // Register
      <li class="nav-item">
        <a class="nav-link" href="{{url_for('loginPage')}}">Login</a>
      </li> // Login page
      <li class="nav-item">
        <a class="nav-link" href="{{url_for('logout')}}">Logout</a>
      </li> // Logout
    </ul>

We will see the appearance as shown below, We can see that we have done to log out when and redirect the user to the home page.

ezgif.com-video-to-gif (5).gif

We can use the session in the frontend section to find out whether the user is logged in orlogged out. we can see a simple example like the following:

Layout.html

<ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="{{url_for('showHomePage')}}">Home <span class="sr-only">(current)</span></a>
      </li>
      {% if not session.logged_in %}
      <li class="nav-item">
        <a class="nav-link" href="{{url_for('registerPage')}}">Register</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="{{url_for('loginPage')}}">Login</a>
      </li>
      {% else %}
      <li class="nav-item">
        <a class="nav-link" href="{{url_for('logout')}}">Logout</a>
      </li>
      {% endif %}
    </ul>

In the frontend we can use if not {% if not session.logged_in %} and test whether the user's session exists. The session we are testing is logged_in or not, this session is true or false. The following is the demonstration:

ezgif.com-video-to-gif (7).gif

If the user is logged in, we will display the logout menu only, but if the user is logged out then we will display the register and login menu. We have worked on the authentication section of the application that we have made, in the next tutorial I will discuss more deeply the message features that we will use like social media, just my tutorial this time, thank you for following this tutorial, hopefully, it is useful.

  • Web development with flask

Web developement with python #1 : Flask initialization and Routing system

Web development with python #6 : Use flash message and combine it with framework boostrap

  • File in python

File in python #1 : Read file and Write file and Modes file

  • Class-based views

Tutorial Django - Class based views #1 : Installation and configuration Django, Using a template system



Create Aplication social media with flask

Make social media applications with Flask #1: Design database and initial structure, Following and follower functions

Make social media applications with Flask #2: System routing and Templating, Make user register

Make social media applications with Flask #3: Register user and Store data in SQLite, Base Layout

Make social media applications with Flask #4: Login system and Use session to manage user data

Proof of work done

https://github.com/milleaduski/python-web-app

Sort:  

Thank you for your contribution.

  • I can say there is some improvement in your English language expression, although more effort would be better to help users grasp concepts more easily.
  • Interesting work on flask, although basic in terms of user signup and login/logout. I would suggest to provide more innovative ideas and concepts to your readers.
  • Nice work showing GIFs as always, helpful to the user.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @mcfarhat! Keep up the good work!

Hey @duski.harahap, great post! I enjoyed your content. Keep up the good work! It's always nice to see good content here on Steemit! :)

Posted using Partiko Android

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Congratulations @duski.harahap! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 2000 as payout for your posts. Your next target is to reach a total payout of 3000

Click here to view your Board
If you no longer want to receive notifications, reply to this comment with the word STOP

Support SteemitBoard's project! Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.16
TRX 0.16
JST 0.028
BTC 69542.45
ETH 2439.22
USDT 1.00
SBD 2.38