使用Firebase的Django认证项目

使用Firebase的Django认证项目

Django是一个基于Python的网络框架,允许你快速创建高效的网络应用。当我们建立任何网站时,我们都需要一套组件:如何处理用户认证(注册、登录、退出),管理网站的管理面板,如何上传文件等等。Django为我们提供了现成的组件,可以轻松使用。

要查看如何用Django和Firebase创建一个新项目,请查看 – 如何在Django中使用Firebase数据库创建一个新项目?

在这里,我们将学习如何在Django中使用Firebase作为数据库创建登录和注册。在Firebase认证中,我们需要启用Sign-in方法。

在Firebase仪表板上授予权限 –

第1步:进入认证->签到方式->电子邮件/密码。

使用Firebase的Django认证项目

第2步 :启用电子邮件/密码,并点击保存

使用Firebase的Django认证项目

现在,我希望你已经在Django中创建了一个项目。如果没有,请参考《如何在Django中使用MVT创建一个基本项目?

创建Django认证项目-

创建URLs,以映射urls.py中的请求。

from django.contrib import admin
from django.urls import path
from . import views
 
urlpatterns = [
    path('admin/', admin.site.urls),
    # Here we are assigning the path of our url
    path('', views.signIn),
    path('postsignIn/', views.postsignIn),
    path('signUp/', views.signUp, name="signup"),
    path('logout/', views.logout, name="log"),
    path('postsignUp/', views.postsignUp),
]

Views.py

在这里,我们将使用我们的Firebase凭证进行认证。

from django.shortcuts import render
import pyrebase
 
 
config={
    apiKey: "Use Your Api Key Here",
    authDomain: "Use Your authDomain Here",
    databaseURL: "Use Your databaseURL Here",
    projectId: "Use Your projectId Here",
    storageBucket: "Use Your storageBucket Here",
    messagingSenderId: "Use Your messagingSenderId Here",
    appId: "Use Your appId Here"
}
# Initialising database,auth and firebase for further use
firebase=pyrebase.initialize_app(config)
authe = firebase.auth()
database=firebase.database()
 
def signIn(request):
    return render(request,"Login.html")
def home(request):
    return render(request,"Home.html")
 
def postsignIn(request):
    email=request.POST.get('email')
    pasw=request.POST.get('pass')
    try:
        # if there is no error then signin the user with given email and password
        user=authe.sign_in_with_email_and_password(email,pasw)
    except:
        message="Invalid Credentials!!Please ChecK your Data"
        return render(request,"Login.html",{"message":message})
    session_id=user['idToken']
    request.session['uid']=str(session_id)
    return render(request,"Home.html",{"email":email})
 
def logout(request):
    try:
        del request.session['uid']
    except:
        pass
    return render(request,"Login.html")
 
def signUp(request):
    return render(request,"Registration.html")
 
def postsignUp(request):
     email = request.POST.get('email')
     passs = request.POST.get('pass')
     name = request.POST.get('name')
     try:
        # creating a user with the given email and password
        user=authe.create_user_with_email_and_password(email,passs)
        uid = user['localId']
        idtoken = request.session['uid']
        print(uid)
     except:
        return render(request, "Registration.html")
     return render(request,"Login.html")

Login.html

{% if message %}
<script>
    alert('{{ message }}');
</script>
{% endif %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sign In</title>
    <style>
     body{
            background-image: url(https://images.unsplash.com/photo-1493723843671-1d655e66ac1c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80);
        }
         input{
            margin-top:20px;
            height: 30px;
             padding: 12px 20px;
             width: 150px;
             margin: 8px 0;
            border-radius: 5px;
        }
        input[type="submit"]{
            background-color: rgba(7, 179, 185, 0.753);
            color: rgb(255, 255, 255);
            border: none;
            border-radius: 5px;
        }
        button{
            background-color: rgba(7, 179, 185, 0.753);
            color: white;
            width: 150px;
            height: 30px;
            border: none;
            border-radius: 5px;
        }
    </style>
</head>
<body>
 
<form action="/postsignIn/" method="post">
    {% csrf_token %}
    <br/>
   <!-- Enter Your Email: -->
    <label for="Email">Email</label>
    <input type="email"id="Email" name="email"><br><br>
   <!-- Enter Your Password: -->
    <label for="Password">Password</label>
    <input type="password" id="Password" name="pass"><br><br>
    <input type="submit" value="SignIn"><br><br>
    <label>
      <input type="checkbox" checked="checked" name="remember"> Remember me
    </label>
    <button type="button" onclick="location.href='{% url 'signup' %} '">SignUp</button>
</form>
</body>
</html>

Registration.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sign Up</title>
    <style>
     body{
            background-image: url(https://images.unsplash.com/photo-1493723843671-1d655e66ac1c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80);
        }
        input{
            margin-top:20px;
            height: 30px;
            width: 150px;
            border-radius: 5px;
             
        }
        input[type="submit"]{
            background-color: rgba(7, 179, 185, 0.753);
            color: rgb(255, 255, 255);
            border: none;
            border-radius: 5px;
        }
 
    </style>
</head>
<body>
 
<form action="/postsignUp/" method="post">
    {% csrf_token %}
    <br/>
      <h1>Sign Up</h1>
      
 
<p>Please fill in this form</p>
 
 
    <label for="username">Username</label>
    <input type="name" id="Username" name="name" placeholder="Your Name"><br><br>
    <!-- Email: -->
    <label for="Email" >Email</label>
    <input type="email" id="Email" name="email" placeholder="Your Email Id"><br><br>
    <!-- Password: -->
    <label for="Password">Password/label>
    <input type="password" id="Password" name="pass" placeholder="Password"><br><br>
    <!-- RepeatPassword: -->
    <label for="confirm_password">Confirm Password</label>
    <input type="password" id="confirm_password" name="pass-repeat" placeholder=" Repeat Password"><br><br>
    <label>
      <input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
    </label>
     
    <input type="submit" value="SignUp"><br><br>
 
</form>
</body>
</html>

Home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome</title>
    <style>
        body{
            background-image: url(https://images.unsplash.com/photo-1493723843671-1d655e66ac1c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80);
        }
        div{
        position:absolute;
        right:10px;
        top:5px;
        }
        p{
            font-size: 32px;
        }
        button{
            background-color: rgba(7, 179, 185, 0.753);
            color: white;
            width: 70px;
            height: 40px;
            border: none;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<br><br>
<div>
<button type="button" onclick="location.href='{% url 'log' %}' ">Logout</button>
</div>
</body>
</html>

现在移动到你的项目目录,使用给定的命令运行我们的项目。

python manage.py runserver

登录界面

使用Firebase的Django认证项目

注册界面

使用Firebase的Django认证项目

主页

使用Firebase的Django认证项目

实施重设密码功能 –

在这里,我们将学习如何在Django中用Firebase数据库重置密码。就像大多数时候发生的那样,你忘记了你的密码,你想重置你的密码。所以在这篇文章中,我们将学习如何在Django中这样做。

Urls.py

path('reset/', views.reset),
path('postReset/', views.postReset),

Views.py

在这里,我们基本上是渲染到Reset.html页面,用户将在这里输入他/她的注册邮箱,并会收到一封重置密码的邮件。 send_password_reset_email是Firebase预定义的重置密码的方法。

def reset(request):
    return render(request, "Reset.html")
 
def postReset(request):
    email = request.POST.get('email')
    try:
        authe.send_password_reset_email(email)
        message  = "A email to reset password is successfully sent"
        return render(request, "Reset.html", {"msg":message})
    except:
        message  = "Something went wrong, Please check the email you provided is registered or not"
        return render(request, "Reset.html", {"msg":message})

Login.html

{% if message %}
<script>
    alert('{{ message }}');
</script>
{% endif %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sign In</title>
    <style>
     body{
            background-image: url(https://images.unsplash.com/photo-1493723843671-1d655e66ac1c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80);
        }
         input{
            margin-top:20px;
            height: 30px;
             padding: 12px 20px;
             width: 150px;
             margin: 8px 0;
            border-radius: 5px;
        }
        input[type="submit"]{
            background-color: rgba(7, 179, 185, 0.753);
            color: rgb(255, 255, 255);
            border: none;
            border-radius: 5px;
        }
        button{
            background-color: rgba(7, 179, 185, 0.753);
            color: white;
            width: 150px;
            height: 30px;
            border: none;
            border-radius: 5px;
        }
    </style>
</head>
<body>
 
<form action="/postsignIn/" method="post">
    {% csrf_token %}
    <br/>
   <!-- Enter Your Email: -->
    <label for="Email">Email</label>
    <input type="email"id="Email" name="email"><br><br>
   <!-- Enter Your Password: -->
    <label for="Password">Password</label>
    <input type="password" id="Password" name="pass"><br><br>
    <input type="submit" value="SignIn"><br><br>
    <p style="color: black;padding: 10px 0;">Forgot Password? <a href="/reset/" style="color: black;">Click Here to Reset</a></p>
 
 
    <label>
      <input type="checkbox" checked="checked" name="remember"> Remember me
    </label>
    <button type="button" onclick="location.href='{% url 'signup' %} '">SignUp</button>
</form>
</body>
</html>

Reset.html

<!DOCTYPE html>
{% load static %}
{%if msg%}
    <script>
        window.alert('{{msg}}');
    </script>
{% endif%}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="{% static '/css/Reset.css/' %}">
    <link rel="stylesheet" type="text/css" href="{% static '/css/footer.css/' %}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src='https://kit.fontawesome.com/a076d05399.js'></script>
</head>
<body>
    <div class="back">
        <a href="/"><i class='fas fa-arrow-left' style='font-size:22px'>  </i>Back</a>
    </div>
    <div class="container">
        <div class="inner">
            <h1>Reset Your Password</h1><br>
            <form action="/postReset/" method="POST">
                {% csrf_token %}
                <input type="email" name="email" id="email" placeholder="Enter Your email" required><br><br>
                <input type="submit" value="Send Reset Link">
            </form>
        </div>
    </div>
</body>
</html>

现在移动到你的项目目录,使用给定的命令运行我们的项目。

python manage.py runserver

点击 “点击这里重置”,然后你会被转到另一个页面。

使用Firebase的Django认证项目

输入你的电子邮件并点击发送重设链接,然后你会在你的电子邮件上收到一个链接来更改你的密码。

使用Firebase的Django认证项目

一个提示框会出现,确认邮件已发送。

使用Firebase的Django认证项目

现在,你会收到这样的邮件

.点击它查看邮件的描述。

使用Firebase的Django认证项目

在这里,点击给定的链接来改变你的密码。

使用Firebase的Django认证项目

在这里,键入一个新的密码并点击保存。

使用Firebase的Django认证项目

现在,你可以用你的新密码登录了。

使用Firebase的Django认证项目

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程