Question

In a _form, I have a field to upload files. What I am trying to do is check if the file contains a dangerous extension.

In my case, I return an error message if the extension is one of the following: . 'bat'. 'with'. 'exe'. 'src',. 'cmd'

So I did this:

def suspitious_attachment        
  if ends_with? '.bat', '.com', '.exe', '.src', '.cmd'
    errors.add(:base, I18n.t('errors.messages.suspitious_attachment', :value => attachments.split(".").last))
  end
end

But it is not a good idea, a file can have multiple dot in the name.

So I would like to get the last 4 letters of the name.

I'm not able to do this, can you help me?

Sorry for my English.

Was it helpful?

Solution

You can use [-4..-1] or [-4, 4]:

'this.is.really.dangerous.file.exe'[-4..-1]
# => ".exe"
'this.is.really.dangerous.file.exe'[-4, 4]
# => ".exe"
'a_file.rb'[-4..-1]
# => "e.rb"

But File::extname is more appropriate to get filename.

File.extname 'a_file.cmd'
# => ".cmd"
File.extname 'a_file.rb'
# => ".rb"
File.extname 'this.is.really.dangerous.file.exe'
# => ".exe"

OTHER TIPS

You're lulling yourself into a false sense of security here. Checking the name of the file will not prevent someone from uploading a file with a fake extension.

If you need to verify the file format, you should check against the MIME type instead.

See more here: How to check in rails uploaded file type?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top