Header Ads

Python Django with Google Firebase - Firebase Authentication :SignIn Alert, Request Session, Logout, Reset Password #Part 2



In previous tutorial we have covered Getting started with Python Django with Google Firebase and created a simple SignIn Form to showcase the example of Firebase Authentication, here i continue with Firebase Auhentication and cover Invalid Credentials SignIn Alert, Requesting Session, Logout User and in bonus Recover Lost Password.


Check out this video, code below follows the video to help

If you like videos like this consider donating $1, or simply turn off AdBlocker. Either helps me to continue making tutorials.


Invalid SignIn Credentials Alert :

For setting invalid credentials alert we will use try & except block, if  user typed right credentials then try block will execute else except block will execute in which will redirect to same template i.e 'SignIn.html'. 

Views.py 
def postsign(request):
email=request.POST.get('email')
passw = request.POST.get("pass")
try:
user = authe.sign_in_with_email_and_password(email,passw)
except:
message="invalid credentials"
return render(request,"signIn.html",{"messg":message})
print(user['idToken'])
return render(request, "welcome.html",{"e":email})

SignIn.html

when except block redirect on same template then if condition will check of 'messg' variable which contains message for alert function, if 'messg' variable exists while rendering template then we will get popup alert.
{% if messg %}
<script>
alert('{{ messg }}');
</script>
{% endif %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign</title>
</head>
<body>
<form action="/postsign/" method="post">
{% csrf_token %}
Email :
<input type="email" name="email">
Password:
<input type="password" name="pass">
<input type="submit" value="SignIn">
</form>
</body>
</html>
Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Here while requesting session for user we have two choices either we can use 'localid' or 'idtoken'. I  suggest to use idtoken as it contains all information about logged-in user and it also automatically get expire after 30 minutes for security purpose. Well i have also used 'localid' in my previous projects as it's pretty easy to use then 'idtoken'.

Views.py
def postsign(request):
email=request.POST.get('email')
passw = request.POST.get("pass")
try:
user = authe.sign_in_with_email_and_password(email,passw)
except:
message="invalid credentials"
return render(request,"signIn.html",{"messg":message})
print(user['idToken'])
session_id=user['idToken']
request.session['uid']=str(session_id)
return render(request, "welcome.html",{"e":email})

Logout User : 
   
Django authentication provides both authentication and authorization together and is generally referred to as the authentication system, as these features are somewhat coupled.When you call logout(), the session data for the current request is completely cleaned out. All existing data is removed. This is to prevent another person from using the same Web browser to log in and have access to the previous user’s session data.

Views.py
from django.shortcuts import render
import pyrebase
from django.contrib import auth
config = {
'apiKey': "AIzaSyB0Il0NLQPxxDyMgoE0fOMd4pYUkbkZVvI",
'authDomain': "cpanel-5e873.firebaseapp.com",
'databaseURL': "https://cpanel-5e873.firebaseio.com",
'projectId': "cpanel-5e873",
'storageBucket': "cpanel-5e873.appspot.com",
'messagingSenderId': "579985583952"
}
firebase = pyrebase.initialize_app(config)
authe = firebase.auth()
def signIn(request):
return render(request, "signIn.html")
def postsign(request):
email=request.POST.get('email')
passw = request.POST.get("pass")
try:
user = authe.sign_in_with_email_and_password(email,passw)
except:
message="invalid credentials"
return render(request,"signIn.html",{"messg":message})
print(user['idToken'])
session_id=user['idToken']
request.session['uid']=str(session_id)
return render(request, "welcome.html",{"e":email})
def logout(request):
auth.logout(request)
return render(request,'signIn.html')

Welcome.html

<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
position : absolute;
right : 10px;
top : 5px
}
</style>
</head>
<body>
<div>
<button type="button" onclick="location.href='{% url 'log' %}'">Logout</button>
</div>
Welcome {{e}}
</body>
</html>
Urls.py

from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.signIn),
url(r'^postsign/',views.postsign),
url(r'^logout/',views.logout,name="log")
]

Recover Lost Password:
Pyrebase library supports the functionality of resetting lost password by sending password reset emails.
auth.send_password_reset_email("email")

That's end up with a great tutorial on Firebase Authentication functionalities if you guys have any query comment out :)
Get full source code for Django Project Here.

No comments:

Powered by Blogger.