Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
travist committed Nov 3, 2018
0 parents commit 55e97a0
Show file tree
Hide file tree
Showing 19 changed files with 1,790 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
PORT=4100
MAX_UPLOAD_SIZE=16mb
DEBUG=*
PROVIDERS=file
UPLOAD_DIR=
ALFRESCO_USER=admin
ALFRESCO_PASS=admin
ALFRESCO_HOST=http://127.0.0.1:8082
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
providers/uploads/*
.idea
18 changes: 18 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
FROM node:8-alpine
MAINTAINER Form.io <[email protected]>

COPY ./ /src
WORKDIR /src

# Install git
RUN apk update && \
apk upgrade && \
apk add --no-cache --virtual .build-deps bash git make gcc g++ python

RUN npm cache clean --force && \
npm install && \
npm uninstall -g npm && \
apk del .build-deps

EXPOSE 80
ENTRYPOINT ["node", "index"]
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
Form.io File Upload Server
-------------------------
This library provides an Upload Server/Proxy for use with the Form.io File Component and URL configuration.
This allows for Private file upload and downloads by sending Authentication requests to the Form.io API Server
to determine if a user has permissions to upload or download based on their access to either Submit the form, or fetch the Submission JSON respectively.

Getting Started
---------------------
This library can be ran within 3 different environments.

1.) Locally using Node.js
2.) Docker container
3.) AWS Lambda

### Running locally with Node.js
In order to run this server locally, you can type the following within your terminal.

npm install
node index

### Running within Docker


#### Environment Variables.
You must use Environment variables to configure the runtime operation of this server. When running this server locally using Node.js, you can set the Environment variables within the ```.env``` file. These variables are defined as follows.


| Variable | Description | Default |
|----------|-------------|---------|
| PORT | The port you wish to run the server on. | 4100 |
| MAX_UPLOAD_SIZE | The maximum upload size for files being uploaded. | 16mb |
| DEBUG | Enables debugging | * |
| PROVIDERS | Determines which upload providers are enabled. This is a CSV of the providers you wish to enable. For example "file,alfresco" will enable both local file uploads as well as Alfresco ECM uploads. | file |
| UPLOAD_DIR | When using the "file" provider, this is the local upload base directory. | providers/uploads |
| ALFRESCO_USER | When using the Alfresco provider, this is the user account to log into the Alfresco ECM | admin |
| ALFRESCO_PASS | When using the Alfresco provider, this is the user account password to log into the Alfresco ECM | admin |
| ALFRESCO_HOST | When using the Alfresco provider, this is the Alfresco ECM server URL | http://127.0.0.1:8082 |

3 changes: 3 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
require('dotenv').config();
const app = require('./server');
app.listen((process.env.PORT || 80), () => console.log('Alfresco Proxy Listening on ' + (process.env.PORT || 80)));
14 changes: 14 additions & 0 deletions lambda.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict'
const awsServerlessExpress = require('aws-serverless-express')
const app = require('./server')
const binaryMimeTypes = [
'application/octet-stream',
'font/eot',
'font/opentype',
'font/otf',
'image/jpeg',
'image/png',
'image/svg+xml'
]
const server = awsServerlessExpress.createServer(app, null, binaryMimeTypes);
exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context)
56 changes: 56 additions & 0 deletions middleware/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const request = require('request');
module.exports = function authenticate(req, res, next) {
req.debug('Authenticating');
// Require an auth token to get the file.
if (req.method === 'GET' && !req.query.token) {
return res.status(401).send('Unauthorized');
}

if (req.query.token) {
request.get({
url: `${req.query.baseUrl}/form/${req.query.form}/submission/${req.query.submission}`,
json: true,
qs: {token: req.query.token}
}, (err, response, body) => {
if (err) {
return next(err);
}
if (!body._id) {
return res.status(401).send('Unauthorized');
}

// We are able to load the submission, so we are authenticated to download this file.
return next();
});
}
else if (req.method === 'POST') {
if (!req.query.form || !req.query.baseUrl) {
return next('Form not found.');
}

// Perform a fake submission to see if we can upload.
request.post({
url: `${req.query.baseUrl}/form/${req.query.form}/submission`,
json: true,
qs: { dryrun: 1 },
headers: {
'x-jwt-token': req.headers['x-jwt-token']
}
}, (err, response) => {
if (err) {
return next(err);
}

if (response.statusCode !== 200) {
return res.sendStatus(response.statusCode);
}

// If we could submit the form, then we are allowed to upload the file.
return next();
});
}
else {
// Everything else is unauthorized.
return res.status(401).send('Unauthorized');
}
};
21 changes: 21 additions & 0 deletions middleware/cleanup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const fs = require('fs-extra');
const _ = require('lodash');
module.exports = (req, res, next) => {
if (!req.cleanup || !req.cleanup.length) {
req.debug('Nothing to cleanup');
return next();
}

// Cleanup all files.
_.each(req.cleanup, (file) => {
try {
req.debug(`Deleting file ${file}`);
fs.unlink(file);
}
catch (err) {
req.debug(`ERROR: Deleting File ${err.message || err}`);
console.log(err);
}
});
next();
};
7 changes: 7 additions & 0 deletions middleware/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
init: require('./init'),
auth: require('./auth'),
upload: require('./upload'),
tempToken: require('./tempToken'),
cleanup: require('./cleanup')
};
18 changes: 18 additions & 0 deletions middleware/init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const debug = require('debug');
const uuid = require('uuid/v4');
module.exports = function(namespace) {
const log = debug(namespace);
return function initialize(req, res, next) {
const reqId = uuid();
req.cleanup = [];
req.debug = (msg) => {
log(`${reqId}: ${msg}`);
};
const ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
(req.connection.socket ? req.connection.socket.remoteAddress : null);
req.debug(`New Request from ${req.get('Referrer')}: (${ip})`);
next();
}
};
52 changes: 52 additions & 0 deletions middleware/tempToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const request = require('request');
const _ = require('lodash');
module.exports = function tempToken(req, res, next) {
if (!req.body || !req.body.url) {
return next('No file url provided.');
}

// Get the project and form.
const url = _.get(req.body, 'data.baseUrl');
const project = _.get(req.body, 'data.project');
const form = _.get(req.body, 'data.form');
const submission = _.get(req.body, 'data.submission');

req.body.url += '?';
if (url) {
req.body.url += `baseUrl=${url}&`;
}
if (project) {
req.body.url += `project=${project}&`;
}
if (form) {
req.body.url += `form=${form}&`;
}
if (submission) {
req.body.url += `submission=${submission}&`;
}

// If a project is provided and we are authenticated, then we can fetch a temp token that can only access
// this submission for a limited time period.
if (project && req.headers['x-jwt-token']) {
request.get({
url: `${url}/token`,
json: true,
headers: {
'x-allow': `GET:/project/${project}/form/${form}/submission/${submission}`,
'x-jwt-token': req.headers['x-jwt-token']
}
}, (err, response, body) => {
if (err) {
return next(err);
}
if (!body || !body.key) {
return res.status(401).send('Unauthorized');
}
req.body.url += `token=${body.key}`;
next();
});
}
else {
next();
}
};
26 changes: 26 additions & 0 deletions middleware/upload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const os = require('os');
const multer = require('multer');
const upload = multer({
dest: os.tmpdir()
});
module.exports = function uploadFile(req, res, next) {
req.debug(`Uploading file`);
upload.single('file')(req, res, (err) => {
if (err) {
return next(err);
}

if (!req.file || !req.file.path) {
return next('File not uploaded');
}

// Add the uploaded file to cleanup task.
req.debug(`Uploaded file ${req.file.path}`);
req.cleanup.push(req.file.path);
req.provider.upload(req.file, req.body.dir).then(entity => {
req.response = entity;
req.debug(`Uploaded file ${entity.url}`);
return next();
}, err => next(err));
});
};
Loading

0 comments on commit 55e97a0

Please sign in to comment.