-
Notifications
You must be signed in to change notification settings - Fork 83
/
index.js
105 lines (74 loc) · 2.76 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'use strict'
const fs = require('fs')
const path = require('path')
const request = require('request-promise')
const mustache = require('mustache')
const uuidv4 = require('uuid/v4');
const authPath = '/restricted/authenticate';
var AUTHORIZED_TOKENS = {};
module.exports = function() {
return function(req, res, next) {
let scopeTest = /^\/restricted\/([a-z]+\.[a-z]+)\//
let requestedUrl = req.url;
let port = req.socket.localPort;
if(scopeTest.test(requestedUrl) === false) {
next();
return;
}
req.app.post(authPath, async (req, res) => {
//wrong scope
let scope = req.body['requested-url'].match(scopeTest)[1];
//get access_token
try {
let result = JSON.parse(await request({
uri: "http://localhost:"+ port + '/auth/token',
method: 'POST',
form: {
client_id: 'node-red-admin',
grant_type: 'password',
scope: scope,
username: req.body.login,
password: req.body.password
}
}))
let ssid = uuidv4();
AUTHORIZED_TOKENS[ssid] = {
expires: Date.now() + result.expires_in,
access_token : result.access_token
};
//redirect
res.cookie(scope, ssid, 30 * 60);
res.send({redirection: global.CONFIG.server.host+req.body['requested-url']});
} catch(e) {
if(e.statusCode) {
res.status(e.statusCode);
return res.send(e.message);
} else {
console.log('Error : ', e);
return res.sendStatus(400);
}
}
});
//get access token
let scope = requestedUrl.match(scopeTest)[1];
let ssid = req.cookies[scope];
if(ssid) {
if(AUTHORIZED_TOKENS[ssid] && AUTHORIZED_TOKENS[ssid].expires > Date.now()) {
return next();
} else {
delete AUTHORIZED_TOKENS[ssid];
if(req.headers["x-requested-with"] === "XMLHttpRequest") {
res.sendStatus(401);
}
}
}
//check access token
var template = fs.readFileSync(path.join(__dirname, "template","login.html"),"utf8");
var data = {
login : fs.readFileSync(path.join(__dirname, "template","login.js"),"utf8"),
url: global.CONFIG.server.host + authPath,
requested_url: requestedUrl
}
res.send(mustache.render(template, data));
}
}