-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
399 lines (349 loc) · 10.1 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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
"use strict";
var express = require("express")
var session = require("express-session")
var bodyParser = require("body-parser")
var fs = require("fs")
var path = require("path")
var Handlebars = require("handlebars")
var passport = require("passport")
var LocalStrategy = require("passport-local").Strategy
var appRoot = require("app-root-path")
var Sha256 = require("./public/sha256")
var FileMap = require("./FileMap")
var BasicUsers = require("./BasicUsers")
var multer = require("multer")
// ensure some folders
var mkdirp = require("mkdirp")
mkdirp(appRoot + "/expressdrive/uploads")
mkdirp(__dirname + "/public/processed")
var templateLoader = require("./templateLoader")
var loadTemplates = templateLoader.loadTemplates
var templates = templateLoader.templates
var handleConfig = require("./handleConfig")
var config = handleConfig.config
var branding = handleConfig.branding
var basicUsers = new BasicUsers({
saveDestination: appRoot + "/expressdrive/users.json",
adminUsername: config.adminUsername,
adminPassword: config.adminPassword,
secret: config.secret
})
// setup passport
passport.use(new LocalStrategy(
{
passReqToCallback: true
},
(req, username, password, done) => {
var user = basicUsers.getUserByUsername(username)
if (!user) {
req.session.loginMessage = "Invalid username"
return done(null, false)
} else if (!basicUsers.checkPassword(user, password)) {
req.session.loginMessage = "Invalid password"
return done(null, false)
}
done(null, {
id: user.id,
username: user.username,
permission: user.permission
})
}
))
passport.serializeUser((user, done) => {
done(null, user.id);
})
passport.deserializeUser((id, done) => {
done(null, basicUsers.users[id])
})
class ExpressDrive {
constructor(app, passedConfig) {
this.app = app
this.restrictedPaths = {
f: true,
fileTable: true,
// edit
upload: true,
createFolder: true,
editFile: true,
moveFiles: true,
getFolders: true,
deleteFiles: true,
// admin
admin: true,
createUser: true,
editUser: true,
deleteUser: true,
userTable: true,
getPermissions: true,
setPermissions: true
}
this.fileMap = new FileMap({ saveDestination: appRoot + "/expressdrive/files.json" })
this.init()
}
init() {
// upload setup
this.storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, appRoot + "/expressdrive/uploads")
},
filename: function (req, file, cb) {
var fileSplit = file.originalname.split(".")
var extension = fileSplit[fileSplit.length - 1]
cb(null, Sha256.hash(file.originalname + Date.now()) + "." + extension)
}
})
this.upload = multer({ storage: this.storage })
this.app.use(bodyParser.urlencoded({ extended: false }))
this.app.use(bodyParser.json())
this.app.use(session({
secret: config.secret,
resave: false,
saveUninitialized: true,
httpOnly: true,
secure: false
}));
this.app.use("/expressdrive", express.static(__dirname + "/public"));
this.app.use(passport.initialize())
this.app.use(passport.session())
// middleware to validate the user is logged in before viewing certain pages
this.app.use("*",
(req, res, next) => {
if (req.originalUrl.substring(0,config.path.length) == config.path) {
// reload templates with each request (TODO dev only)
loadTemplates(() => {
var urlComponents = req.originalUrl.substring(config.path.length).split("/")
var userRestriced = this.restrictedPaths[urlComponents[1]]
if (!req.user && userRestriced) {
return res.redirect(config.path + "/login?oreq=" + req.originalUrl)
}
next()
})
} else {
next()
}
}
)
// login screen
this.app.get(config.path + "/login",
(req, res) => {
if (req.user) { return res.redirect(config.path) }
var message = req.session.loginMessage
delete req.session.loginMessage
res.setHeader('Cache-Control', 'no-cache, no-store')
res.send(templates.main({ branding, page: "login", path: config.path, message }))
}
)
// login post
this.app.post(config.path + "/login",
(req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) { return next(err); }
if (!user) { return res.redirect(config.path + '/login'); }
req.logIn(user, (err) => {
if (err) { return next(err); }
return res.redirect(req.body.oreq == "" ? config.path : req.body.oreq);
});
})(req, res, next);
}
)
// logout
this.app.get(config.path + "/logout",
(req, res) => {
if (req.user) {
req.logout()
}
res.redirect(config.path + "/login")
}
)
// fileView page when accessing from URL
this.app.get([config.path, config.path + "/f", config.path + "/f/*"],
(req, res) => {
if (!req.user) { return res.redirect(config.path + "/login") }
if (req.originalUrl == config.path) { req.originalUrl = config.path + "/f" }
var cleanPath = req.originalUrl.substring(config.path.length + "/f".length)
var fileData = this.fileMap.getFileFromPath(cleanPath, req.user)
var file = fileData.file
if (file == undefined) {
return res.send(templates.main({
branding,
page: "loggedIn",
view: "fileView",
path: config.path,
badRequest: true,
user: req.user
}))
}
if (file.type == "folder") {
var folderData = this.fileMap.getFolderData(fileData, req.user, cleanPath)
var folderPermission = fileData.permission
if (req.user.permission === 0) {
folderPermission = 0
}
res.setHeader('Cache-Control', 'no-cache, no-store')
res.setHeader('Content-Type', 'text/html')
res.send(templates.main({
branding,
page: "loggedIn",
view: "fileView",
path: config.path,
user: req.user,
folderPermission,
files: folderData.files,
stats: folderData.stats,
breadcrumbs: folderData.breadcrumbs
}))
} else {
res.sendFile(path.join(appRoot.path, 'expressdrive', 'uploads', file.nameOnDisk))
}
}
)
// endpoint for AJAX fileTable
this.app.get([config.path + "/fileTable", config.path + "/fileTable/*"],
(req, res) => {
var cleanPath = req.originalUrl.substring(config.path.length + "/fileTable".length)
var folderData = this.fileMap.getFolderData(cleanPath, req.user)
var folderPermission = folderData.folderPermission
if (req.user.permission === 0) {
folderPermission = 0
}
res.send(templates.fileTable({
path: config.path,
user: req.user,
files: folderData.files,
stats: folderData.stats,
folderPermission
}))
}
)
this.app.post(config.path + "/upload",
this.upload.single("file"),
(req, res) => {
this.fileMap.addFile(req.file, req.query.target, req.user)
res.sendStatus(200)
}
)
this.app.post(config.path + "/createFolder",
(req, res) => {
this.fileMap.createFolder(req.body.name, req.body.target, req.user)
res.sendStatus(200)
}
)
this.app.post(config.path + "/editFile",
(req, res) => {
this.fileMap.editFile(req.body.name, req.body.filePath, req.user)
res.sendStatus(200)
}
)
this.app.post(config.path + "/moveFiles",
(req, res) => {
this.fileMap.moveFiles(req.body.files, req.body.target, req.body.keepOriginal, req.user)
res.sendStatus(200)
}
)
this.app.post(config.path + "/deleteFiles",
(req, res) => {
var deletedFiles = this.fileMap.deleteFiles(req.body.files, req.user)
for (var i = 0; i < deletedFiles.length; i++) {
fs.unlink(path.join(appRoot.path, 'expressdrive', 'uploads', deletedFiles[i].nameOnDisk))
}
res.sendStatus(200)
}
)
this.app.get(config.path + "/getFolders",
(req, res) => {
res.send(this.fileMap.getFolders(req.user))
}
)
this.app.post(config.path + "/getPermissions",
(req, res) => {
if (req.user.permission === 0) {
var permissions = this.fileMap.getPermissions(req.body.path, req.user)
var inheritPermissions
var users = basicUsers.getUsers()
users.unshift({ username: "All Users", id: "_all" })
if (permissions == undefined) {
inheritPermissions = true
permissions = {}
}
var currentPermissions = []
for (var i = 0; i < users.length; i++) {
var user = users[i]
var permItem = { name: user.username, id: user.id }
var perm = permissions[user.id]
if (perm === 1) {
permItem.edit = true
} else if (perm === 2) {
permItem.read = true
}
currentPermissions.push(permItem)
}
res.send(templates.permissionsTable({
inheritPermissions,
permissions: currentPermissions,
showInherit: req.body.path !== "" // check if it's the home folder
}))
} else {
res.sendStatus(403)
}
}
)
this.app.post(config.path + "/setPermissions",
(req, res) => {
if (req.user.permission === 0) {
this.fileMap.setPermissions(req.body.path, req.body.permissions, req.body.inheritPermissions, req.user)
res.sendStatus(200)
} else {
res.sendStatus(403)
}
}
)
// administration
this.app.get(config.path + "/admin",
(req, res) => {
res.send(templates.main({
branding,
page: "loggedIn",
view: "adminView",
user: req.user,
users: basicUsers.getUsers(),
path: config.path
}))
}
)
this.app.get(config.path + "/userTable",
(req, res) => {
res.send(templates.usersTable({
user: req.user,
users: basicUsers.getUsers(),
path: config.path
}))
}
)
this.app.post(config.path + "/createUser",
(req, res) => {
basicUsers.createUser(req.body.username, req.body.password, req.body.permission)
res.sendStatus(200)
}
)
this.app.post(config.path + "/editUser",
(req, res) => {
basicUsers.editUser(req.body.id, req.body.username, req.body.password, req.body.permission)
res.sendStatus(200)
}
)
this.app.post(config.path + "/deleteUsers",
(req, res) => {
basicUsers.deleteUsers(req.body.ids)
res.sendStatus(200)
}
)
// error handling middleware
this.app.use([config.path, config.path + "/*"],
(err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
}
)
}
}
module.exports = ExpressDrive