This repository has been archived by the owner on Aug 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
uppy.js
251 lines (227 loc) · 7.79 KB
/
uppy.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
const express = require('express')
// @ts-ignore
const Grant = require('grant-express')
const grantConfig = require('./config/grant')()
const providerManager = require('./server/provider')
const controllers = require('./server/controllers')
const s3 = require('./server/controllers/s3')
const url = require('./server/controllers/url')
const SocketServer = require('ws').Server
const emitter = require('./server/emitter')
const merge = require('lodash.merge')
const redis = require('./server/redis')
const cookieParser = require('cookie-parser')
const { jsonStringify, getURLBuilder } = require('./server/helpers/utils')
const jobs = require('./server/jobs')
const interceptor = require('express-interceptor')
const logger = require('./server/logger')
const { STORAGE_PREFIX } = require('./server/Uploader')
const middlewares = require('./server/middlewares')
const providers = providerManager.getDefaultProviders()
const defaultOptions = {
server: {
protocol: 'http',
path: ''
},
providerOptions: {
s3: {
acl: 'public-read',
endpoint: 'https://{service}.{region}.amazonaws.com',
conditions: [],
getKey: (req, filename) => filename
}
},
debug: true
}
/**
* Entry point into initializing the uppy-server app.
*
* @param {object} options
*/
module.exports.app = (options = {}) => {
options = merge({}, defaultOptions, options)
providerManager.addProviderOptions(options, grantConfig)
const customProviders = options.customProviders
if (customProviders) {
providerManager.addCustomProviders(customProviders, providers, grantConfig)
}
// create singleton redis client
if (options.redisUrl) {
redis.client({ url: options.redisUrl })
}
emitter(options.multipleInstances && options.redisUrl)
const app = express()
app.use(cookieParser()) // server tokens are added to cookies
app.use(interceptGrantErrorResponse)
app.use(new Grant(grantConfig))
app.use((req, res, next) => {
res.header(
'Access-Control-Allow-Headers',
[res.get('Access-Control-Allow-Headers'), 'uppy-auth-token'].join(', ')
)
next()
})
if (options.sendSelfEndpoint) {
app.use('*', (req, res, next) => {
const { protocol } = options.server
res.header('i-am', `${protocol}://${options.sendSelfEndpoint}`)
// add it to the exposed custom headers.
res.header('Access-Control-Expose-Headers', [res.get('Access-Control-Expose-Headers'), 'i-am'].join(', '))
next()
})
}
// add uppy options to the request object so it can be accessed by subsequent handlers.
app.use('*', getOptionsMiddleware(options))
app.use('/s3', s3(options.providerOptions.s3))
app.use('/url', url())
app.get('/:providerName/callback', middlewares.hasSessionAndProvider, controllers.callback)
app.get('/:providerName/connect', middlewares.hasSessionAndProvider, controllers.connect)
app.get('/:providerName/redirect', middlewares.hasSessionAndProvider, controllers.redirect)
app.get('/:providerName/logout', middlewares.hasSessionAndProvider, middlewares.gentleVerifyToken, controllers.logout)
app.get('/:providerName/authorized', middlewares.hasSessionAndProvider, middlewares.gentleVerifyToken, controllers.authorized)
app.get('/:providerName/list/:id?', middlewares.hasSessionAndProvider, middlewares.verifyToken, controllers.list)
app.post('/:providerName/get/:id', middlewares.hasSessionAndProvider, middlewares.verifyToken, controllers.get)
app.get('/:providerName/thumbnail/:id', middlewares.hasSessionAndProvider, middlewares.cookieAuthToken, middlewares.verifyToken, controllers.thumbnail)
app.param('providerName', providerManager.getProviderMiddleware(providers))
if (app.get('env') !== 'test') {
jobs.startCleanUpJob(options.filePath)
}
return app
}
/**
* the socket is used to send progress events during an upload
*
* @param {object} server
*/
module.exports.socket = (server) => {
const wss = new SocketServer({ server })
const redisClient = redis.client()
// A new connection is usually created when an upload begins,
// or when connection fails while an upload is on-going and,
// client attempts to reconnect.
wss.on('connection', (ws) => {
// @ts-ignore
const fullPath = ws.upgradeReq.url
// the token identifies which ongoing upload's progress, the socket
// connection wishes to listen to.
const token = fullPath.replace(/\/api\//, '')
logger.info(`connection received from ${token}`, 'socket.connect')
/**
*
* @param {{action: string, payload: object}} data
*/
function sendProgress (data) {
ws.send(jsonStringify(data), (err) => {
if (err) logger.error(err, 'socket.progress.error')
})
}
// if the redisClient is available, then we attempt to check the storage
// if we have any already stored progress data on the upload.
if (redisClient) {
redisClient.get(`${STORAGE_PREFIX}:${token}`, (err, data) => {
if (err) logger.error(err, 'socket.redis.error')
if (data) {
const dataObj = JSON.parse(data.toString())
if (dataObj.action) sendProgress(dataObj)
}
})
}
emitter().emit(`connection:${token}`)
emitter().on(token, sendProgress)
ws.on('message', (jsonData) => {
const data = JSON.parse(jsonData.toString())
// whitelist triggered actions
if (data.action === 'pause' || data.action === 'resume') {
emitter().emit(`${data.action}:${token}`)
}
})
ws.on('close', () => {
emitter().removeListener(token, sendProgress)
})
})
}
// intercepts grantJS' default response error when something goes
// wrong during oauth process.
const interceptGrantErrorResponse = interceptor((req, res) => {
return {
isInterceptable: () => {
// match grant.js' callback url
return /^\/connect\/\w+\/callback/.test(req.path)
},
intercept: (body, send) => {
const unwantedBody = 'error=Grant%3A%20missing%20session%20or%20misconfigured%20provider'
if (body === unwantedBody) {
logger.error(`grant.js responded with error: ${body}`, 'grant.oauth.error')
send([
'Uppy-server was unable to complete the OAuth process :(',
'(Hint, try clearing your cookies and try again)'
].join('\n'))
} else {
send(body)
}
}
}
})
/**
* returns a logger function, that would log a message only if
* the debug option is set to true
*
* @param {{debug: boolean}} options
* @returns {function}
*/
const getDebugLogger = (options) => {
// TODO: deprecate this.
// TODO: add line number and originating file
/**
*
* @param {string} message
*/
const conditonalLogger = (message) => {
if (options.debug) {
logger.debug(message, 'debugLog')
}
}
return conditonalLogger
}
/**
*
* @param {object} options
*/
const getOptionsMiddleware = (options) => {
let s3Client = null
if (options.providerOptions.s3) {
const S3 = require('aws-sdk/clients/s3')
const AWS = require('aws-sdk')
const config = options.providerOptions.s3
// Use credentials to allow assumed roles to pass STS sessions in.
// If the user doesn't specify key and secret, the default credentials (process-env)
// will be used by S3 in calls below.
let credentials
if (config.key && config.secret) {
credentials = new AWS.Credentials(config.key, config.secret, config.sessionToken)
}
s3Client = new S3({
region: config.region,
endpoint: config.endpoint,
credentials,
signatureVersion: 'v4'
})
}
/**
*
* @param {object} req
* @param {object} res
* @param {function} next
*/
const middleware = (req, res, next) => {
req.uppy = {
options,
s3Client,
authToken: req.header('uppy-auth-token'),
debugLog: getDebugLogger(options),
buildURL: getURLBuilder(options)
}
next()
}
return middleware
}