Class: Form1010EzrAttachments::FileTypeValidator
- Inherits:
-
Object
- Object
- Form1010EzrAttachments::FileTypeValidator
- Defined in:
- app/services/form1010_ezr_attachments/file_type_validator.rb
Instance Method Summary collapse
-
#initialize(file) ⇒ FileTypeValidator
constructor
A new instance of FileTypeValidator.
-
#mime_subtype_allow_list ⇒ Object
private
These MIME types correspond to the extensions accepted by enrollment system: PDF,WORD,JPG,RTF.
-
#validate ⇒ Object
This method was created because there’s an issue on the frontend where a user can manually ‘change’ a file’s extension via its name in order to circumvent frontend validation.
Constructor Details
#initialize(file) ⇒ FileTypeValidator
Returns a new instance of FileTypeValidator.
7 8 9 |
# File 'app/services/form1010_ezr_attachments/file_type_validator.rb', line 7 def initialize(file) @file = file end |
Instance Method Details
#mime_subtype_allow_list ⇒ Object (private)
These MIME types correspond to the extensions accepted by enrollment system: PDF,WORD,JPG,RTF
44 45 46 |
# File 'app/services/form1010_ezr_attachments/file_type_validator.rb', line 44 def mime_subtype_allow_list %w[pdf msword vnd.openxmlformats-officedocument.wordprocessingml.document jpeg rtf png] end |
#validate ⇒ Object
This method was created because there’s an issue on the frontend where a user can manually ‘change’ a file’s extension via its name in order to circumvent frontend validation. ‘.xlsx’ files, in particular, were the cause of several form submission failures. With that said, we need to check the actual file type and ensure the Enrollment System accepts it.
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 |
# File 'app/services/form1010_ezr_attachments/file_type_validator.rb', line 15 def validate file_path = @file.tempfile.path # Using 'MIME::Types' doesn't work here because it will # return, for example, 'application/zip' for .docx files mime_subtype = IO.popen( ['file', '--mime-type', '--brief', file_path] ) { |io| io.read.chomp.to_s }.split('/').last unless mime_subtype_allow_list.include?(mime_subtype) StatsD.increment("#{Form1010Ezr::Service::STATSD_KEY_PREFIX}.attachments.invalid_file_type") raise Common::Exceptions::UnprocessableEntity.new( detail: 'File type not supported. Follow the instructions on your device ' \ 'on how to convert the file type and try again to continue.' ) end rescue => e StatsD.increment("#{Form1010Ezr::Service::STATSD_KEY_PREFIX}.attachments.failed") Rails.logger.error( "Form1010EzrAttachment validate file type failed #{e.}.", backtrace: e.backtrace ) raise e end |