-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
vmstarchenko #4
base: master
Are you sure you want to change the base?
vmstarchenko #4
Changes from all commits
645a768
cc7cf74
9865c7b
4ded33d
c8141e7
a287eed
a090049
baaa799
126351d
760399f
eed7e64
e39a8e7
5a62583
d44b05b
e5c2904
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,4 @@ | ||
node_modules/ | ||
*.log | ||
.#* | ||
tmp* |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,135 @@ | ||
'use strict'; | ||
;(function() { | ||
"use strict"; | ||
|
||
const express = require('express'); | ||
const app = express(); | ||
// import | ||
const express = require('express'); | ||
const fs = require('fs'); | ||
|
||
const PORT = process.env.PORT || 4000; | ||
// custom import | ||
const TransformStream = require('./transformStream'); | ||
|
||
app.listen(PORT, function () { | ||
const app = express(); | ||
|
||
const PORT = process.env.PORT || 4000; | ||
|
||
app.listen(PORT, function () { | ||
console.log(`App is listen on ${PORT}`); | ||
}); | ||
}); | ||
|
||
// log request time | ||
app.use(function(req, res, next) { | ||
req.requestTime = new Date().getTime(); | ||
next(); | ||
}); | ||
|
||
// add cookies | ||
app.use(function (req, res, next) { | ||
let cookiesString = (req.headers.cookie) ? req.headers.cookie : "", | ||
cookies = {}, _; | ||
let cookiesList = cookiesString.split(';'); | ||
for (let i=0, size=cookiesList.length; i < size; ++i) { | ||
_ = cookiesList[i].split('='); | ||
cookies[_[0]] = _[1]; | ||
} | ||
req.cookies = cookies; | ||
next(); | ||
}); | ||
|
||
// check authorized | ||
app.use(function (req, res, next) { | ||
if (isAuthorized(req)) { | ||
next(); | ||
return; | ||
} | ||
res.sendStatus(403); | ||
}); | ||
|
||
// log url | ||
app.use(function (req, res, next) { | ||
res.setHeader('X-Request-Url', req.method+' '+req.url); | ||
console.log('X-Request-Url:', req.method+' '+req.url); | ||
next(); | ||
}); | ||
|
||
// log time | ||
app.use(function (req, res, next) { | ||
let date = new Date(); | ||
let time = date.getTime() - req.requestTime + 1; | ||
res.setHeader('X-Time', time); | ||
console.log('X-Time=' + time); | ||
next(); | ||
}); | ||
|
||
// IMPORTANT. Это строка должна возвращать инстанс сервера | ||
|
||
// views | ||
|
||
app.get(/\/v1\/(.*)/, function (req, res) { | ||
let path = simplifyPath(req.params[0]); // 0 | ||
// warn access | ||
if (path === undefined) { | ||
throw new Error(); | ||
} | ||
path = './' + path; | ||
|
||
if (fs.lstatSync(path).isDirectory()) { // is dir | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Синхронно, конечно не очень здорово, но ладно |
||
fs.readdir(path, function (err, items) { | ||
if (err) { | ||
throw new Error(); | ||
} | ||
items.push('.'); | ||
items.push('..'); | ||
let context = { | ||
content: items, | ||
}; | ||
res.send(context); | ||
}); | ||
} else { | ||
|
||
let stream = fs.createReadStream(path), | ||
tstream = new TransformStream(); | ||
|
||
res.setHeader('Content-Type', 'application/json'); | ||
stream.pipe(tstream).pipe(res); | ||
|
||
// stream.on('error', function(err) {res.end(err);}); | ||
} | ||
}); | ||
|
||
app.get(/\/.*/, function (req, res) { | ||
throw new Error(); | ||
// res.send('Test'); | ||
}); | ||
|
||
// log error | ||
app.use(function (error, req, res, next) { | ||
res.setHeader('X-Request-Error', "Unknown request"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. На самом деле ты тут должен устанавливать в хедер то, что пришло тебе в error. У тебя же могут быть разные ошибки в приложении возникнуть, а ты будешь всегда одну и туже выставлять. |
||
res.status(503).end(); | ||
}); | ||
|
||
// add path check | ||
function simplifyPath(path) { | ||
let newPath = []; | ||
path = path.split('/'); | ||
let depth = 0; | ||
for (let i=0, size=path.length; i < size; ++i) { | ||
if (path[i] === '..') { | ||
if (depth <= 0) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Хоть на это теста и нет, но тем не менее, это у тебя не будет работать, если запрос будет следующего вида ././../ т.е. в newPath будет что-то лежать, но ../ уведет тебя на уровень выше. Можешь попробовать доработать собственную версию, а можешь воспользоваться встроенным модулем path |
||
return undefined; | ||
depth -= 1; | ||
newPath.pop(); | ||
} else { | ||
depth += 1; | ||
newPath.push(path[i]); | ||
} | ||
} | ||
return newPath.join('/'); | ||
} | ||
|
||
function isAuthorized(request) { | ||
return !!(request && request.cookies && request.cookies.authorize); | ||
} | ||
|
||
module.exports = app; | ||
|
||
// IMPORTANT. Это строка должна возвращать инстанс сервера | ||
module.exports = app; | ||
})(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А зачем ты прибавляешь единицу, чтобы тесты прошли:) Тебе нужно использовать другой механизм измерения времени выполнения запроса, который довал бы тебе точность до тысячных