This repository has been archived by the owner on Nov 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (58 loc) · 1.93 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
const auth = require('basic-auth')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const multer = require('multer')
const upload = multer()
const express = require('express')
const app = express()
const bucket = require('./src/gcloud/bucket')
const PORT = process.env.PORT || 3000
const LIMIT = '50mb'
app.use(morgan('tiny'))
app.use(cors())
app.use(bodyParser.json({limit: LIMIT}))
app.use(bodyParser.urlencoded({limit: LIMIT, extended: true}))
app.get('/', (req, res) => {
res.send('Hello World! My name is uploader!')
})
const doUpload = (req) => {
if(req.file) return bucket.uploadBuffer(req.body.token, req.file)
return bucket.uploadBase64(req.body.token, req.body.file)
}
app.post('/upload', upload.single('file'), (req, res) => {
doUpload(req).then((data) => {
res.status(201).send(data)
}).catch((error) => {
console.error("Erro uploading the file. Reason: ", error)
switch(error) {
case "no_file":
res.status(422).send({error: "Please give us a file to upload"})
break
case "unauthorized":
res.status(401).send({error: "You're unauthorized for this action"})
break
case "invalid_file":
res.status(422).send({error: "The file you gave is invalid"})
break
default:
res.status(500).send({error: "Internal server error"})
}
})
})
const validCredentials = (credentials) => {
let user = process.env.UPLOADER_USER
let pswd = process.env.UPLOADER_PSWD
return (user === undefined && pswd === undefined) ||
(credentials && credentials.name === user && credentials.pass === pswd)
}
app.get('/token', (req, res) => {
if (validCredentials(auth(req))) {
res.status(200).send({token: bucket.generateToken()})
} else {
res.status(401).send({error: "You're not authorized to generate tokens"})
}
})
app.listen(PORT, () => {
console.log(`Uploader listening on port ${PORT}!`)
})