-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathapp.js
229 lines (207 loc) · 7.98 KB
/
app.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
'use strict';
const express = require('express');
const path = require('path');
const packageJson = require('package-json');
const csrf = require('csurf');
const Authentication = require('./Authentication.js');
var fs = require('fs');
const currentVersionFeatures = require('../package.json').parseDashboardFeatures;
var newFeaturesInLatestVersion = [];
packageJson('parse-dashboard', 'latest').then(latestPackage => {
if (latestPackage.parseDashboardFeatures instanceof Array) {
newFeaturesInLatestVersion = latestPackage.parseDashboardFeatures.filter(feature => {
return currentVersionFeatures.indexOf(feature) === -1;
});
}
});
function getMount(mountPath) {
mountPath = mountPath || '';
if (!mountPath.endsWith('/')) {
mountPath += '/';
}
return mountPath;
}
function checkIfIconsExistForApps(apps, iconsFolder) {
for (var i in apps) {
var currentApp = apps[i];
var iconName = currentApp.iconName;
var path = iconsFolder + '/' + iconName;
fs.stat(path, function(err) {
if (err) {
if ('ENOENT' == err.code) {// file does not exist
console.warn('Icon with file name: ' + iconName +' couldn\'t be found in icons folder!');
} else {
console.log(
'An error occurd while checking for icons, please check permission!');
}
} else {
//every thing was ok so for example you can read it and send it to client
}
} );
}
}
module.exports = function(config, options) {
options = options || {};
var app = express();
// Serve public files.
app.use(express.static(path.join(__dirname,'public')));
// Allow setting via middleware
if (config.trustProxy && app.disabled('trust proxy')) {
app.enable('trust proxy');
}
// wait for app to mount in order to get mountpath
app.on('mount', function() {
const mountPath = getMount(app.mountpath);
const users = config.users;
const useEncryptedPasswords = config.useEncryptedPasswords ? true : false;
const authInstance = new Authentication(users, useEncryptedPasswords, mountPath);
authInstance.initialize(app, { cookieSessionSecret: options.cookieSessionSecret });
// CSRF error handler
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
// handle CSRF token errors here
res.status(403)
res.send('form tampered with')
});
// Serve the configuration.
app.get('/parse-dashboard-config.json', function(req, res) {
let apps = config.apps.map((app) => Object.assign({}, app)); // make a copy
let response = {
apps: apps,
newFeaturesInLatestVersion: newFeaturesInLatestVersion,
};
//Based on advice from Doug Wilson here:
//https://github.com/expressjs/express/issues/2518
const requestIsLocal =
req.connection.remoteAddress === '127.0.0.1' ||
req.connection.remoteAddress === '::ffff:127.0.0.1' ||
req.connection.remoteAddress === '::1';
if (!options.dev && !requestIsLocal) {
if (!req.secure && !options.allowInsecureHTTP) {
//Disallow HTTP requests except on localhost, to prevent the master key from being transmitted in cleartext
return res.send({ success: false, error: 'Parse Dashboard can only be remotely accessed via HTTPS' });
}
if (!users) {
//Accessing the dashboard over the internet can only be done with username and password
return res.send({ success: false, error: 'Configure a user to access Parse Dashboard remotely' });
}
}
const authentication = req.user;
const successfulAuth = authentication && authentication.isAuthenticated;
const appsUserHasAccess = authentication && authentication.appsUserHasAccessTo;
const isReadOnly = authentication && authentication.isReadOnly;
// User is full read-only, replace the masterKey by the read-only one
if (isReadOnly) {
response.apps = response.apps.map((app) => {
app.masterKey = app.readOnlyMasterKey;
if (!app.masterKey) {
throw new Error('You need to provide a readOnlyMasterKey to use read-only features.');
}
return app;
});
}
if (successfulAuth) {
if (appsUserHasAccess) {
// Restric access to apps defined in user dictionary
// If they didn't supply any app id, user will access all apps
response.apps = response.apps.filter(function (app) {
return appsUserHasAccess.find(appUserHasAccess => {
const isSame = app.appId === appUserHasAccess.appId;
if (isSame && appUserHasAccess.readOnly) {
app.masterKey = app.readOnlyMasterKey;
}
return isSame;
})
});
}
// They provided correct auth
return res.json(response);
}
if (users) {
//They provided incorrect auth
return res.sendStatus(401);
}
//They didn't provide auth, and have configured the dashboard to not need auth
//(ie. didn't supply usernames and passwords)
if (requestIsLocal || options.dev) {
//Allow no-auth access on localhost only, if they have configured the dashboard to not need auth
return res.json(response);
}
//We shouldn't get here. Fail closed.
res.send({ success: false, error: 'Something went wrong.' });
});
// Serve the app icons. Uses the optional `iconsFolder` parameter as
// directory name, that was setup in the config file.
// We are explicitly not using `__dirpath` here because one may be
// running parse-dashboard from globally installed npm.
if (config.iconsFolder) {
try {
var stat = fs.statSync(config.iconsFolder);
if (stat.isDirectory()) {
app.use('/appicons', express.static(config.iconsFolder));
//Check also if the icons really exist
checkIfIconsExistForApps(config.apps, config.iconsFolder);
}
} catch (e) {
// Directory doesn't exist or something.
console.warn('Iconsfolder at path: ' + config.iconsFolder +
' not found!');
}
}
app.get('/login', csrf(), function(req, res) {
if (!users || (req.user && req.user.isAuthenticated)) {
return res.redirect(`${mountPath}apps`);
}
let errors = req.flash('error');
if (errors && errors.length) {
errors = `<div id="login_errors" style="display: none;">
${errors.join(' ')}
</div>`
}
res.send(`<!DOCTYPE html>
<head>
<link rel="shortcut icon" type="image/x-icon" href="${mountPath}favicon.ico" />
<base href="${mountPath}"/>
<script>
PARSE_DASHBOARD_PATH = "${mountPath}";
</script>
</head>
<html>
<title>Parse Dashboard</title>
<body>
<div id="login_mount"></div>
${errors}
<script id="csrf" type="application/json">"${req.csrfToken()}"</script>
<script src="${mountPath}bundles/login.bundle.js"></script>
</body>
</html>
`);
});
// For every other request, go to index.html. Let client-side handle the rest.
app.get('/*', function(req, res) {
if (users && (!req.user || !req.user.isAuthenticated)) {
return res.redirect(`${mountPath}login`);
}
if (users && req.user && req.user.matchingUsername ) {
res.append('username', req.user.matchingUsername);
}
res.send(`<!DOCTYPE html>
<head>
<link rel="shortcut icon" type="image/x-icon" href="${mountPath}favicon.ico" />
<base href="${mountPath}"/>
<script>
PARSE_DASHBOARD_PATH = "${mountPath}";
</script>
</head>
<html>
<title>Parse Dashboard</title>
<body>
<div id="browser_mount"></div>
<script src="${mountPath}bundles/dashboard.bundle.js"></script>
</body>
</html>
`);
});
});
return app;
}