1
1
package fi .oph .vkt .service .aws ;
2
2
3
+ import fi .oph .vkt .util .exception .APIException ;
4
+ import fi .oph .vkt .util .exception .APIExceptionType ;
3
5
import java .time .Duration ;
4
6
import java .time .LocalDate ;
5
7
import java .time .ZoneId ;
@@ -29,11 +31,24 @@ public class S3Service {
29
31
private final AwsCredentialsProvider awsCredentialsProvider ;
30
32
31
33
private static final int MAX_SIZE_100_MB = 100 * 1024 * 1024 ;
32
- private static final String ACCEPTED_CONTENT_TYPES =
33
- "application/pdf,image/jpeg,image/png,image/heic,image/tiff,image/webp" ;
34
34
private static final Duration POST_POLICY_VALID_FOR_ONE_MIN = Duration .ofMinutes (1 );
35
35
private static final int OBJECT_EXPIRY_MONTHS = 3 ;
36
36
37
+ private static String guessContentType (String extension ) {
38
+ if (extension == null ) {
39
+ throw new APIException (APIExceptionType .INVALID_ATTACHMENT );
40
+ }
41
+ return switch (extension .toLowerCase ()) {
42
+ case "pdf" -> "application/pdf" ;
43
+ case "jpg" , "jpeg" -> "image/jpeg" ;
44
+ case "png" -> "image/png" ;
45
+ case "heic" -> "image/heic" ;
46
+ case "tiff" -> "image/tiff" ;
47
+ case "webp" -> "image/webp" ;
48
+ default -> throw new APIException (APIExceptionType .INVALID_ATTACHMENT );
49
+ };
50
+ }
51
+
37
52
public String getPresignedUrl (String key ) {
38
53
GetObjectRequest request = GetObjectRequest .builder ().bucket (s3Config .getBucketName ()).key (key ).build ();
39
54
GetObjectPresignRequest presignRequest = GetObjectPresignRequest
@@ -46,16 +61,17 @@ public String getPresignedUrl(String key) {
46
61
return presignedRequest .url ().toExternalForm ();
47
62
}
48
63
49
- public Map <String , String > getPresignedPostRequest (String key ) {
64
+ public Map <String , String > getPresignedPostRequest (String key , String extension ) {
50
65
final LocalDate objectExpiry = LocalDate .now ().plusMonths (OBJECT_EXPIRY_MONTHS );
66
+ final String contentType = guessContentType (extension );
51
67
52
68
S3PostObjectRequest .Builder requestBuilder = S3PostObjectRequest
53
69
.builder ()
54
70
.bucket (s3Config .getBucketName ())
55
71
.expiration (POST_POLICY_VALID_FOR_ONE_MIN )
56
72
.withCondition (Conditions .keyStartsWith (key ))
57
73
.withCondition (Conditions .contentLengthRange (0 , MAX_SIZE_100_MB ))
58
- .withCondition (Conditions .contentTypeHeaderEquals (ACCEPTED_CONTENT_TYPES ))
74
+ .withCondition (Conditions .contentTypeHeaderEquals (contentType ))
59
75
.withCondition (
60
76
Conditions .expiresHeaderEquals (
61
77
DateTimeFormatter .RFC_1123_DATE_TIME .format (objectExpiry .atStartOfDay (ZoneId .of ("GMT" )))
0 commit comments