11import uuid from 'node-uuid' ;
2- import policy from 's3-policy' ;
2+ import S3Policy from 's3-policy-v4 ' ;
33import s3 from '@auth0/s3' ;
4+ import mongoose from 'mongoose' ;
45import { getProjectsForUserId } from './project.controller' ;
56import { findUserByUsername } from './user.controller' ;
67
8+ const { ObjectId } = mongoose . Types ;
9+
710const client = s3 . createClient ( {
811 maxAsyncS3 : 20 ,
912 s3RetryCount : 3 ,
@@ -18,7 +21,7 @@ const client = s3.createClient({
1821} ) ;
1922
2023const s3Bucket = process . env . S3_BUCKET_URL_BASE ||
21- `https://s3-${ process . env . AWS_REGION } .amazonaws.com/${ process . env . S3_BUCKET } /` ;
24+ `https://s3-${ process . env . AWS_REGION } .amazonaws.com/${ process . env . S3_BUCKET } /` ;
2225
2326function getExtension ( filename ) {
2427 const i = filename . lastIndexOf ( '.' ) ;
@@ -27,14 +30,10 @@ function getExtension(filename) {
2730
2831export function getObjectKey ( url ) {
2932 const urlArray = url . split ( '/' ) ;
30- let objectKey ;
31- if ( urlArray . length === 5 ) {
32- const key = urlArray . pop ( ) ;
33- const userId = urlArray . pop ( ) ;
34- objectKey = `${ userId } /${ key } ` ;
35- } else {
36- const key = urlArray . pop ( ) ;
37- objectKey = key ;
33+ const objectKey = urlArray . pop ( ) ;
34+ const userId = urlArray . pop ( ) ;
35+ if ( ObjectId . isValid ( userId ) && userId === new ObjectId ( userId ) . toString ( ) ) {
36+ return `${ userId } /${ objectKey } ` ;
3837 }
3938 return objectKey ;
4039}
@@ -81,21 +80,17 @@ export function signS3(req, res) {
8180 const fileExtension = getExtension ( req . body . name ) ;
8281 const filename = uuid . v4 ( ) + fileExtension ;
8382 const acl = 'public-read' ;
84- const p = policy ( {
83+ const policy = S3Policy . generate ( {
8584 acl,
86- secret : process . env . AWS_SECRET_KEY ,
87- length : 5000000 , // in bytes?
85+ key : `${ req . body . userId } /${ filename } ` ,
8886 bucket : process . env . S3_BUCKET ,
89- key : filename ,
90- expires : new Date ( Date . now ( ) + 60000 ) ,
87+ contentType : req . body . type ,
88+ region : process . env . AWS_REGION ,
89+ accessKey : process . env . AWS_ACCESS_KEY ,
90+ secretKey : process . env . AWS_SECRET_KEY ,
91+ metadata : [ ]
9192 } ) ;
92- const result = {
93- AWSAccessKeyId : process . env . AWS_ACCESS_KEY ,
94- key : `${ req . body . userId } /${ filename } ` ,
95- policy : p . policy ,
96- signature : p . signature
97- } ;
98- res . json ( result ) ;
93+ res . json ( policy ) ;
9994}
10095
10196export function copyObjectInS3 ( url , userId ) {
0 commit comments