javascript - 如何在服务器端查看用户认证状态

标签 javascript html express firebase-authentication

我想在显示 html 页面之前检查用户身份验证

我的 server.js 文件是这样的

const express = require('express');
var jquery = require('jquery');
var admin = require("firebase");

const app = express();

app.use(express.static(__dirname + '/public'));



var serviceAccount = require("firebasekey.json");

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

var ref = admin.app().database().ref();
 

app.get(['/','/index.html'], function(req, res) {
	res.sendFile(__dirname + '/public/index.html');
 
 });


app.get(['/dash' ], function(req, res) {
	res.sendFile(__dirname + '/public/dash/index.html');
  
 });
 
 

在渲染页面之前,如何检查用户是否首先在服务器端经过身份验证?例如,

 app.get(['/dash' ], function(req, res) {
      //check if the user is authenticated

     if auth == true {
    res.sendFile(__dirname + '/public/dash/index.html');
     } else{
            res.sendFile(__dirname + '/public/login.html');

     }

 });

如何在服务器端查看用户认证状态?

最佳答案

正如所建议的,有无数种方法可以对用户进行身份验证。 但我会用一个简单的例子来帮助你:

  1. 您应该有一个持久的用户列表,例如数据库。为了简单起见,我们将在代码中使用常量。
const express = require('express');
var jquery = require('jquery');
var admin = require("firebase");

const USER = {
    email: "john@doe.com",
    password: "12345"
}

  • 有多种方法可以实现身份验证检查。我建议使用可以应用于各种路由的中间件:
  • const authenticate = (req, res, next) => {
        // parse the user out of your request
        // e.g with bodyparser -> see npm
        if (req.body.email === USER.email && req.body.password === USER.password) {
            next()
        } else {
            res.send({ status: 401 });
        }
    }
    
    
  • 将此中间件应用于您要保护的路由或所有路由
  • // all routes
    app.use(authenticate)
    
    // certain route
    app.get('/someRoute', authenticate, (req, res)) => {
        // only successful authenticated user
        // (in this case: john@doe.com) will
        // have access to this route.
        // ... code
    }
    

    可以使用 cookie、jwt 等扩展此模式,当然还有可以存储注册用户的数据库。

    关于javascript - 如何在服务器端查看用户认证状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54787275/

    相关文章:

    javascript - 从 HTTP 函数将图像文件写入 Firebase Storage

    javascript - 如何在 d3.js 双条形图中选择比例?

    html - 如何删除 input[type ="date"] 的占位符文本?

    html - 垂直对齐列表中较大元素符号的文本

    javascript - 我如何使用 res.clearCookie() 清除expressjs中特定域的所有cookie

    node.js - Express.js 的 API 在哪里?

    javascript - 如何从现有 JSON 文件添加新 JSON

    javascript - 拖动时从可拖动对象中删除 <a href> - jquery

    javascript - 在javaScript中通过DOM获取tagNames而不依赖其他元素

    node.js - 为什么 Node.js 上的 Express 处理 http 请求 "serially"?