Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ce0d409

Browse files
committedFeb 16, 2025·
feat: upload user image to digital ocean
1 parent 09ca9cf commit ce0d409

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed
 

‎package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@
4040
"@hapi/vision": "^6.1.0",
4141
"adm-zip": "^0.5.9",
4242
"async": "^3.2.3",
43-
"axios": "^0.26.0",
4443
"aws-sdk": "^2.814.0",
44+
"axios": "^0.26.0",
4545
"bunyan": "^1.8.15",
4646
"esprima": "^4.0.1",
4747
"good": "^2.3.0",

‎server/resources/user.js

+49
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
const aws = require('../plugins/aws')
12
const Boom = require('@hapi/boom')
23
const server = require('../').hapi
34
const log = require('../helpers/logger')
@@ -6,6 +7,7 @@ const fieldsParser = require('../helpers/fieldsParser')
67
const config = require('../../config')
78
const User = require('../db/user')
89

10+
911
server.method('user.create', create, {})
1012
server.method('user.update', update, {})
1113
server.method('user.updateMe', updateMe, {})
@@ -55,6 +57,19 @@ async function update(filter, user, opts) {
5557
filter = { id: filter }
5658
}
5759

60+
if (user && user.img.startsWith("data:image/jpeg;base64,")) {
61+
const base64Data = user.img.replace(/^data:image\/\w+;base64,/, "");
62+
const buffer = Buffer.from(base64Data, "base64");
63+
64+
const imgUrl = await uploadUserImage(filter.id, buffer)
65+
if (!imgUrl) {
66+
log.error('Error setting image URL for user ' + filter.id)
67+
throw Boom.internal('Error setting image URL for user ' + filter.id)
68+
}
69+
70+
user.img = imgUrl
71+
}
72+
5873
if (user && user.company) {
5974
const user2 = Object.assign({}, user)
6075
if (!user.company.edition) {
@@ -404,3 +419,37 @@ async function getQRCode(user) {
404419
// FIXME: Implement this in a secure way using JWT
405420
return `sinfo://${btoa(JSON.stringify({ kind: "user", user: { id: user.id, name: user.name, img: user.img, role: user.role } }))}`
406421
}
422+
423+
/* Image Functions */
424+
function getDataFromStream(stream) {
425+
return new Promise((resolve, reject) => {
426+
let data = []
427+
428+
stream.on('data', (chunk) => {
429+
data.push(chunk)
430+
})
431+
432+
stream.on('end', () => {
433+
resolve(Buffer.concat(data))
434+
})
435+
436+
stream.on('error', (err) => {
437+
reject(err)
438+
})
439+
})
440+
}
441+
442+
function getFileName(userId) {
443+
return userId + '.jpg'
444+
}
445+
446+
function getUserPath() {
447+
return `static/users/`
448+
}
449+
450+
async function uploadUserImage(userId, file) {
451+
const path = getUserPath()
452+
const fileName = getFileName(userId)
453+
const data = await getDataFromStream(file)
454+
return aws.upload(path, data, fileName, true)
455+
}

0 commit comments

Comments
 (0)
Please sign in to comment.