简体   繁体   English

Firebase Auth + Python后端

[英]Firebase Auth + Python backend

I am going to use Firebase Auth and Database modules to create my web app. 我将使用Firebase身份验证和数据库模块创建我的Web应用程序。 However, not all things that I want my app to do is possible to achieve on only front end. 但是,并非我希望我的应用程序执行的所有操作都只能在前端实现。 So I want to also use backend with Python's Bottle framework to handle requests and Pyrebase to get access to Firebase Database. 因此,我还想将后端与Python的Bottle框架一起使用来处理请求,并使用Pyrebase来访问Firebase数据库。
Let's say that after logging in I need to go to mainpage and see personalized content, for example my notes. 假设登录后,我需要转到主页并查看个性化内容,例如我的笔记。 They are structured this way in DB: 它们在数据库中的结构如下:

{
    "notes": [{
        "id": "1",
        "title": "X",
        "author": "user1"
    },
    {
        "id": "2",
        "title": "Y",
        "author": "user2"
    } and so on... ]
}

So how it's possible to implement showing only my articles on main page? 那么如何实现只在首页显示我的文章呢? I understand that I need to filter my notes based on author value, but how to let Bottle understand who is currently logged in? 我了解我需要根据author价值过滤笔记,但是如何让Bottle了解当前登录的人呢?
I've read there , that I should somehow send unique token to backend server to authenticate current user, but how to do that? 我读过那里 ,我应该以某种方式发送唯一令牌到后端服务器进行身份验证当前用户,但如何做到这一点? Inserting Token in every link as GET parameter seems to be silly, but I see no other way to implement that. 在每个链接中将Token作为GET参数插入似乎很愚蠢,但是我看不到其他实现方法。

Start by organizing your database so that each note becomes a child object: 首先组织数据库,以便每个注释成为子对象:

{
  "notes": {
    "id1": {
      "id": "id1",
      "title": "X",
      "author": "user1",
    },
    "id2": {

    }
  }
}

Then this particular interaction can be implemented entirely in the client-side. 然后,可以在客户端完全实现这种特定的交互。 Just execute a query to filter the notes you want. 只需执行查询即可过滤所需的注释。 For example in a JS client: 例如在JS客户端中:

var uid = firebase.auth().currentUser.uid;
var query = ref.orderByChild('author').equalTo(uid);
// Listen for query value events

If you want to run this on a backend server, and you want to ensure that only logged in users are allowed to execute it, then you must pass the ID token from the client app to the server on each request. 如果要在后端服务器上运行此程序,并且要确保只允许登录用户执行该程序,则必须在每次请求时将ID令牌从客户端应用传递到服务器。 Here's how to implement the server-side logic using the Python Admin SDK: 以下是使用Python Admin SDK实施服务器端逻辑的方法:

import firebase_admin
from firebase_admin import auth
from firebase_admin import db

token = '....' # Extract from the client request
try:
    decoded = auth.verify_id_token(token)
    uid = decoded.uid
    ref = db.reference('path/to/notes')
    notes = ref.order_by_child('author').equal_to(uid).get()
    # Process notes response
except ValueError as ex:
    print(ex)
    # Send error to client

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM