微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 firebase admin 登录后,我无法读取 firebase 数据

如何解决使用 firebase admin 登录后,我无法读取 firebase 数据

注册用户登录我的网站后,我无法写入读取我的规则的数据

{
  "rules": {
    ".read": "auth != null",// i have tried also "auth.uid != null"
    ".write": "auth != null"
  }
}

所以即使我是一个普通用户,我也应该根据上面的规则读取数据,如果 auth != nil 和这里是我在 app.js 中登录的方式

const cookieParser = require("cookie-parser");
const csrf = require("csurf");
const bodyParser = require("body-parser");
const express = require("express");
const admin = require("firebase-admin");

var serviceAccount = require("./serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),databaseURL: "https://my-app.firebaseio.com"
});

const csrfMiddleware = csrf({ cookie: true });

const app = express();

app.engine("html",require('ejs').renderFile);

app.use(express.static('static'))

app.use(bodyParser.json());
app.use(cookieParser());
app.use(csrfMiddleware);

app.all("*",(req,res,next) => {
  res.cookie("XSRF-TOKEN",req.csrftoken());
  next();
});

app.get("/login",function (req,res) {
  res.render("login.html");
});

app.post('/sessionLogin',res) =>{
    const idToken = req.body.idToken.toString()
    const expiresIn = 60*60*24*7*1000

    admin
    .auth()
    .createSessionCookie(idToken,{ expiresIn })
    .then(
      (sessionCookie) => {
        const options = { maxAge: expiresIn,httpOnly: true };
        res.cookie("session",sessionCookie,options);
        res.end(JSON.stringify({ status: "success" }));
      },(error) => {
        res.status(401).send("UNAUTHORIZED REQUEST!");
      }
    );
})

app.listen(5000,()=> {
    console.log("app is listening on port 5000")
})

我的 login.html 文件

<script>
        window.addEventListener("DOMContentLoaded",() => {
          var firebaseConfig = {
            apiKey: "AIzaSyACIsI..........",authDomain: "my-app.firebaseapp.com",databaseURL: "https://my-app.firebaseio.com",projectId: "my-app",storageBucket: "my-app.appspot.com",messagingSenderId: "38.........",appId: "1:38......:web:7b........",measurementId: "G-Y........."
          };
          // Initialize Firebase
          firebase.initializeApp(firebaseConfig);

          firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE)


          document
            .getElementById("login")
            .addEventListener("submit",(event) => {
                event.preventDefault();
              const login = event.target.login.value;
              const password = event.target.password.value;

              firebase
                .auth()
                .signInWithEmailAndPassword(login,password)
                .then(({ user }) => {
                  return user.getIdToken().then((idToken) => {
                    return fetch("/sessionLogin",{
                      method: "POST",headers: {
                        Accept: "application/json","Content-Type": "application/json","CSRF-Token": Cookies.get("XSRF-TOKEN"),},body: JSON.stringify({ idToken }),});
                  });
                })
                .then(() => {
                  return firebase.auth().signOut();
                })
                .then(() => {
                  window.location.assign("/home");
                });
              return false;
            });

    
        });
      </script>

谁能看到我在这个 webapp 中哪里出错了,我的 webbapp 包含另一个页面,并且在每个页面中我检查用户是否登录,例如

app.get("/Applications.html",res) {
  const sessionCookie = req.cookies.session || "";

  admin
    .auth()
    .verifySessionCookie(sessionCookie,true /** checkRevoked */)
    .then(() => {
      res.render("Applications.html");
    })
    .catch((error) => {
      res.redirect("/login");
    });
}); 

这是我尝试读取数据的方式

var ref = firebase.database().ref("Applications");
ref.on("value",function(data){
  $('#applicationTable').empty()
    var content = '';
     data.forEach(function(childSnapshot){
         if (childSnapshot.exists()){
         var childData = childSnapshot.val();
         console.log(childData);
         
 
         content +='<tr>';
            content += '<td>' + childData.drivername + '</td>';
            content += '<td>' + childData.phone + '</td>';
            content += '<td>' + childSnapshot.key + '</td>';
            content += '</tr>';
 
      };
    });
    $('#applicationTable').append(content);
 });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?