salix/back/methods/image/download.js

95 lines
2.7 KiB
JavaScript
Raw Normal View History

2020-11-10 07:39:34 +00:00
const UserError = require('vn-loopback/util/user-error');
const fs = require('fs-extra');
module.exports = Self => {
Self.remoteMethod('download', {
description: 'Get the user image',
accessType: 'READ',
accepts: [
{
arg: 'collection',
type: 'String',
description: 'The image collection',
http: {source: 'path'}
},
{
arg: 'size',
type: 'String',
description: 'The image size',
http: {source: 'path'}
},
{
arg: 'id',
type: 'Number',
description: 'The user id',
http: {source: 'path'}
}
],
returns: [
{
arg: 'body',
type: 'file',
root: true
},
{
arg: 'Content-Type',
type: 'String',
http: {target: 'header'}
},
{
arg: 'Content-Disposition',
type: 'String',
http: {target: 'header'}
}
],
http: {
path: `/:collection/:size/:id/download`,
verb: 'GET'
}
});
Self.download = async function(collection, size, id) {
const filter = {
where: {
collectionFk: collection,
name: id},
include: {
relation: 'collection',
scope: {
fields: ['name', 'readRoleFk'],
include: {
relation: 'readRole'
}
}
}
};
const image = await Self.app.models.Image.findOne(filter);
2020-11-10 10:33:01 +00:00
if (!image) return false;
2020-11-10 07:39:34 +00:00
const imageRole = image.collection().readRole().name;
const hasRole = await Self.app.models.Account.hasRole(id, imageRole);
if (!hasRole)
throw new UserError(`You don't have enough privileges`);
let file;
let env = process.env.NODE_ENV;
if (env && env != 'development') {
file = {
path: `/var/lib/salix/image/${collection}/${size}/${id}.png`,
contentType: 'image/png',
name: `${id}.png`
};
} else {
file = {
path: `${process.cwd()}/storage/image/${collection}/${size}/${id}.png`,
contentType: 'image/png',
name: `${id}.png`
};
}
await fs.access(file.path);
let stream = fs.createReadStream(file.path);
return [stream, file.contentType, `filename="${file.name}"`];
};
};