Skip to content

Adds authentication to file retrieval #3897

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export class Config {
this.generateSessionExpiresAt = this.generateSessionExpiresAt.bind(this);
this.generateEmailVerifyTokenExpiresAt = this.generateEmailVerifyTokenExpiresAt.bind(this);
this.revokeSessionOnPasswordReset = cacheInfo.revokeSessionOnPasswordReset;
this.authenticatedFileRetrieval = cacheInfo.authenticatedFileRetrieval;
}

static validate({
Expand Down
2 changes: 2 additions & 0 deletions src/ParseServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ class ParseServer {
schemaCacheTTL = defaults.schemaCacheTTL, // cache for 5s
enableSingleSchemaCache = false,
__indexBuildCompletionCallbackForTests = () => {},
authenticatedFileRetrieval,
}) {
// Initialize the node client SDK automatically
Parse.initialize(appId, javascriptKey || 'unused', masterKey);
Expand Down Expand Up @@ -253,6 +254,7 @@ class ParseServer {
liveQueryController: liveQueryController,
sessionLength: Number(sessionLength),
expireInactiveSessions: expireInactiveSessions,
authenticatedFileRetrieval: authenticatedFileRetrieval,
jsonLogs,
revokeSessionOnPasswordReset,
databaseController,
Expand Down
76 changes: 56 additions & 20 deletions src/Routers/FilesRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class FilesRouter {

expressRouter(options = {}) {
var router = express.Router();
router.get('/files/:appId/:filename', this.getHandler);
router.get('/files/:appId/:filename/:referencingClass?/:referencingKey?/:sessionToken?', this.getHandler);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could we split the 2 endpoints for the sake a readability and ease of maintenance?

This way the endpoint that validates the auth calls the getHandler if everything is authorized. This will remove the clutter in the getHandler.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or even better probably make it a middleware to not clutter the logic inside the function


router.post('/files', function(req, res, next) {
next(new Parse.Error(Parse.Error.INVALID_FILE_NAME,
Expand All @@ -36,28 +36,39 @@ export class FilesRouter {
getHandler(req, res) {
const config = new Config(req.params.appId);
const filesController = config.filesController;
const filename = req.params.filename;
const params = req.params;
const filename = params.filename;
const contentType = mime.lookup(filename);
if (isFileStreamable(req, filesController)) {
filesController.getFileStream(config, filename).then((stream) => {
handleFileStream(stream, req, res, contentType);
}).catch(() => {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
} else {
filesController.getFileData(config, filename).then((data) => {
res.status(200);
res.set('Content-Type', contentType);
res.set('Content-Length', data.length);
res.end(data);
}).catch(() => {

checkAuthentication(config, params).then((isAuthenticated) => {
if (isAuthenticated) {
if (isFileStreamable(req, filesController)) {
filesController.getFileStream(config, filename).then((stream) => {
handleFileStream(stream, req, res, contentType);
}).catch(() => {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
} else {
filesController.getFileData(config, filename).then((data) => {
res.status(200);
res.set('Content-Type', contentType);
res.set('Content-Length', data.length);
res.end(data);
}).catch(() => {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
}
} else {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
}
res.end('Unauthorized.');
}
})

}

createHandler(req, res, next) {
Expand Down Expand Up @@ -107,6 +118,31 @@ export class FilesRouter {
}
}

function checkAuthentication(config, params) {
if (config.authenticatedFileRetrieval) {
const restController = Parse.CoreManager.getRESTController();
const filename = params.filename;
const referencingClass = params.referencingClass;
const referencingKey = params.referencingKey;
const sessionToken = params.sessionToken;
const url = `${config.publicServerURL}files/${config.appId}/${filename}`;
const fileObject = {name: filename, url: url, __type: 'File'};
const query = {where: {[referencingKey]: fileObject}};

if (!referencingClass || !referencingKey || !sessionToken) return Promise.resolve(false);
else {
return restController.request("GET", `/classes/${referencingClass}`, query, {sessionToken}).then((res) => {
if (res.results.length > 0)
return true;
else
return false;
}, (err) => {
return false;
});
}
} else return Promise.resolve(true);
}

function isFileStreamable(req, filesController){
if (req.get('Range')) {
if (!(typeof filesController.adapter.getFileStream === 'function')) {
Expand Down
3 changes: 2 additions & 1 deletion src/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,6 @@ export default {
expireInactiveSessions: true,
revokeSessionOnPasswordReset: true,
schemaCacheTTL: 5000, // in ms
userSensitiveFields: ['email']
userSensitiveFields: ['email'],
authenticatedFileRetrieval: false,
}