2017-08-14 31 views
0

我們正在構建僅爲我們數據庫中的某些用戶創建的應用程序。該應用程序不應該由其他人訪問。如果用戶已通過驗證,則可以通過快遞服務角色應用程序

我們的想法是爲一個簡單的HTML文件提供一些關於我們應用程序的信息。我們的應用程序後端應該是nodejs,它應該檢查用戶是否有從我們的身份驗證API提供並附加到我們的域的cookie。如果用戶擁有cookie,我們應該爲他們提供app文件夾。

我們想要保護我們的js文件和屬於該應用程序的所有文件,如果它們未經過身份驗證,則應該從公開位置保護。

在簡單的HTML文件中,我們應該基本上有一個按鈕:「我已驗證,讓我瀏覽應用程序」。

<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Landing page</title> 
</head> 
<body> 
    <h1>Landing page app!!!</h1> 
    <input onclick="location.href='/app';" type="submit" 
    value="I'm authenticated, let me browse the app!"/> 
</body> 
</html> 

節點服務器有一條路徑,稱爲/app

const express = require('express'); 
const app = express(); 
const port = process.env.PORT || 9090; 
const fs = require('fs'); 

app.use(express.static('public')); //only contains index.html 

app.listen(port, (err) => { 
    if (err) { 
    console.log(err); 
    } 
}); 

app.get('/app', (req, res) => { 
    if(req.user.isAuthenticated){ 
     //Psuedo code below 
     res.send(WholeAngularAppToUser()); 
    } 
    else{ 
     // User should stay on landing page 
     // with information about that they are not authenticated 
    } 
}); 

我們怎樣才能將整個角度的應用程序發送給用戶?

回答

1

除非'身份驗證'按鈕在身份驗證過程中用於某種目的(如同時發送憑據),否則您應該立即刪除它並嘗試直接訪問該應用程序。角應用往往充當靜態文件,所以你應該把它作爲一個被一些中間件保護靜態路由:

app.use('/app', function(req, res, next) { 
    if (req.user.isAuthenticated) { 
    next() 
    } else { 
    res.sendFile(path.join(__dirname, 'public/index.html')) 
    } 
}) 
app.use('/app', express.static('/app'); 

當然,你不會只是接受一些請求爲用戶「isAuthenticated」標誌被認證,所以你會交換中間件的東西更安全一些。

+0

是的!這個,但是他們在訪問/時也應該提供相同的index.html文件。這是如何實現的? – petur

+1

只需設置另一條路徑,這次使用'/'路徑並從那裏提供索引文件。不同的路線可以提供相同的文件。 (函數(req,res){res.sendFile(path.join(__ dirname,'public/index.html'))})'app.get('/' –

相關問題