Browse Source

Check params for spam flags, and return blank when found

tags/v0.2.0^2
Bèr Kessels 1 year ago
parent
commit
039b44e323
2 changed files with 38 additions and 4 deletions
  1. 17
    4
      lib/contact.rb
  2. 21
    0
      test/integration/spam_message_test.rb

+ 17
- 4
lib/contact.rb View File

@@ -15,7 +15,8 @@ error BadRequest do |error|
15 15
 end
16 16
 
17 17
 post '/messages' do
18
-  validate(params)
18
+  return status(201) if spam?
19
+  validate
19 20
   raise BadRequest, errors.join("\n") if errors.any?
20 21
 
21 22
   @name    = params['name']
@@ -33,14 +34,26 @@ post '/messages' do
33 34
   end
34 35
 end
35 36
 
36
-def validate(params)
37
+def spam?
38
+  !params['contact_captcha'].nil?
39
+end
40
+
41
+def validate
37 42
   { email: 255, name: 255, message: 1000 }.each do |field, length|
38 43
     errors << "#{field} cannot be over #{length} characters" if
39
-                                        params[field.to_s].to_s.length > length
40
-    errors << "#{field} cannot be empty" if params[field].to_s.empty?
44
+                                                       too_long?(field, length)
45
+    errors << "#{field} cannot be empty" if empty?(field)
41 46
   end
42 47
 end
43 48
 
49
+def too_long?(field, length)
50
+  params[field.to_s].to_s.length > length
51
+end
52
+
53
+def empty?(field)
54
+  params[field].to_s.empty?
55
+end
56
+
44 57
 def errors
45 58
   @errors ||= []
46 59
 end

+ 21
- 0
test/integration/spam_message_test.rb View File

@@ -0,0 +1,21 @@
1
+require 'test_helper'
2
+
3
+describe 'attempt to spam message through REST' do
4
+  let(:params) do
5
+    {
6
+      name: 'Harry Potter',
7
+      email: 'harry@hogwards.edu.wizard',
8
+      message: 'Wingardium Leviosar',
9
+      contact_captcha: 'true'
10
+    }
11
+  end
12
+
13
+  describe 'POST /messages' do
14
+    it 'does not send the message over SMTP but fakes the response' do
15
+      assert_no_changes 'Mail::TestMailer.deliveries.length' do
16
+        post '/messages', params
17
+        assert_response 201
18
+      end
19
+    end
20
+  end
21
+end

Loading…
Cancel
Save