soaring_simple_captcha 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 01dd4a44e19e39d4b331227227234f33cd8504665feeed793f02012d4b758afa
4
+ data.tar.gz: eef625c6c5bf51a0c066e8e14e296aa77a73e4491cc096e46645cb2acfb79f58
5
+ SHA512:
6
+ metadata.gz: 7be95f8030715ee2e965cef57778954cf87fca04182f82823d14acc7ae15aff198c05c6d0251852c7567479cbb4feb64c143432a989d961811ff2f47216fa894
7
+ data.tar.gz: ad9257ea35a48d70228286a86b0f471002f4f0728376bc53e2c1f97cef5d4bca94ec29ac008998ab11aa48a9edc93dfd1b2a7fdac0f4351ce8f512afc49564f8
data/README.rdoc ADDED
@@ -0,0 +1,234 @@
1
+ =Fixture
2
+ fix the table name to support rails 4.0
3
+
4
+ =SimpleCaptcha
5
+
6
+ SimpleCaptcha is the simplest and a robust captcha plugin. Its implementation requires
7
+ adding up a single line in views and in controllers/models.
8
+ SimpleCaptcha is available to be used with Rails 3 or above and also it provides the
9
+ backward compatibility with previous versions of Rails.
10
+
11
+ ==Features
12
+
13
+ * Zero FileSystem usage(secret code moved to db-store and image storage removed).
14
+ * Provides various image styles.
15
+ * Provides three level of complexity of images.
16
+ * Works absolutely fine in distributed environment(session and db based implementation works fine in distributed environment).
17
+ * Implementation is as easy as just writing a single line in your view. "<%= show_simple_captcha %>" within the 'form' tags.
18
+ * Flexible DOM and CSS handling(There is a separate view partial for rednering SimpleCaptcha DOM elements).
19
+ * Automated removal of 1 hour old unmatched simple_captcha data.
20
+
21
+ ==Requirements
22
+
23
+ * {Ruby}[http://ruby-lang.org/] >= 1.8.7
24
+ * {Rails}[http://github.com/rails/rails] >= 3
25
+ * ImageMagick should be installed on your machine to use this plugin.
26
+ visit http://www.imagemagick.org/script/index.php for more details.
27
+
28
+ ==Installation
29
+
30
+ gem "galetahub-simple_captcha", :require => "simple_captcha"
31
+
32
+ or
33
+
34
+ gem 'simple_captcha', :git => 'git://github.com/galetahub/simple-captcha.git'
35
+
36
+ ==Setup
37
+
38
+ After installation, follow these simple steps to setup the plugin. The setup will depend
39
+ on the version of rails your application is using.
40
+
41
+ rails generate simple_captcha
42
+
43
+ rake db:migrate
44
+
45
+ ==Usage
46
+
47
+ ===Controller Based
48
+
49
+ Add the following line in the file "app/controllers/application.rb"
50
+
51
+ ApplicationController < ActionController::Base
52
+ include SimpleCaptcha::ControllerHelpers
53
+ end
54
+
55
+ In the view file within the form tags add this code
56
+
57
+ <%= show_simple_captcha %>
58
+
59
+ and in the controller's action authenticate it as
60
+
61
+ if simple_captcha_valid?
62
+ do this
63
+ else
64
+ do that
65
+ end
66
+
67
+ ===Model Based
68
+
69
+ In the view file within the form tags write this code
70
+
71
+ <%= show_simple_captcha(:object=>"user") %>
72
+
73
+ and in the model class add this code
74
+
75
+ class User < ActiveRecord::Base
76
+ apply_simple_captcha
77
+ end
78
+
79
+ ====FormBuilder helper
80
+
81
+ <%= form_for @user do |form| -%>
82
+ ...
83
+ <%= form.simple_captcha :label => "Enter numbers.." %>
84
+ ...
85
+ <% end -%>
86
+
87
+ ====Validating with captcha
88
+ NOTE: @user.valid? will still work as it should, it will not validate the captcha code.
89
+
90
+ @user.valid_with_captcha?
91
+
92
+ ====Saving with captcha
93
+ NOTE: @user.save will still work as it should, it will not validate the captcha code.
94
+
95
+ @user.save_with_captcha
96
+
97
+ ===Formtastic integration
98
+ SimpleCaptcha detects if your use Formtastic and appends "SimpleCaptcha::CustomFormBuilder".
99
+
100
+ <%= form.input :captcha, :as => :simple_captcha %>
101
+
102
+ ==Options & Examples
103
+ ===View Options
104
+
105
+ * *label* - provides the custom text b/w the image and the text field, the default is "type the code from the image"
106
+
107
+ * *object* - the name of the object of the model class, to implement the model based captcha.
108
+
109
+ * *code_type* - return numeric only if set to 'numeric'
110
+
111
+ ===Global options
112
+
113
+ * *image_style* - provides the specific image style for the captcha image.
114
+ There are eight different styles available with the plugin as...
115
+ 1) simply_blue
116
+ 2) simply_red
117
+ 3) simply_green
118
+ 4) charcoal_grey
119
+ 5) embosed_silver
120
+ 6) all_black
121
+ 7) distorted_black
122
+ 8) almost_invisible
123
+ Default style is 'simply_blue'.
124
+ You can also specify 'random' to select the random image style.
125
+
126
+ * *distortion* - handles the complexity of the image. The :distortion can be set to 'low', 'medium' or 'high'. Default is 'low'.
127
+
128
+ Create "rails_root/config/initializers/simple_captcha.rb"
129
+
130
+ SimpleCaptcha.setup do |sc|
131
+ # default: 100x28
132
+ sc.image_size = '120x40'
133
+
134
+ # default: 5
135
+ sc.length = 6
136
+
137
+ # default: simply_blue
138
+ # possible values:
139
+ # 'embosed_silver',
140
+ # 'simply_red',
141
+ # 'simply_green',
142
+ # 'simply_blue',
143
+ # 'distorted_black',
144
+ # 'all_black',
145
+ # 'charcoal_grey',
146
+ # 'almost_invisible'
147
+ # 'random'
148
+ sc.image_style = 'simply_green'
149
+
150
+ # default: low
151
+ # possible values: 'low', 'medium', 'high', 'random'
152
+ sc.distortion = 'medium'
153
+ end
154
+
155
+ You can add your own style:
156
+
157
+ SimpleCaptcha.setup do |sc|
158
+ sc.image_style = 'mycaptha'
159
+ sc.add_image_style('mycaptha', [
160
+ "-background '#F4F7F8'",
161
+ "-fill '#86818B'",
162
+ "-border 1",
163
+ "-bordercolor '#E0E2E3'"])
164
+ end
165
+
166
+ You can provide the path where image_magick is installed as well:
167
+
168
+ SimpleCaptcha.setup do |sc|
169
+ sc.image_magick_path = '/usr/bin' # you can check this from console by running: which convert
170
+ end
171
+
172
+ You can provide the path where should be stored tmp files.
173
+ It's usefull when you dont have acces to /tmp (default directory)
174
+
175
+ SimpleCaptcha.setup do |sc|
176
+ sc.tmp_path = '/tmp' # or somewhere in project eg. Rails.root.join('tmp/simple_captcha').to_s, make shure directory exists
177
+ end
178
+
179
+
180
+ ===How to change the CSS for SimpleCaptcha DOM elements?
181
+ You can change the CSS of the SimpleCaptcha DOM elements as per your need in this file.
182
+ /app/views/simple_captcha/_simple_captcha.erb
183
+
184
+ ===View's Examples
185
+ ====Controller Based Example
186
+
187
+ <%= show_simple_captcha %>
188
+
189
+ <%= show_simple_captcha(:label => "human authentication") %>
190
+
191
+ ====Model Based Example
192
+
193
+ <%= show_simple_captcha(:object => 'user', :label => "human authentication") %>
194
+
195
+ ====Model Options
196
+
197
+ * *message* - provides the custom message on failure of captcha authentication the default is "Secret Code did not match with the Image"
198
+
199
+ * *add_to_base* - if set to true, appends the error message to the base.
200
+
201
+ =====Model's Example
202
+
203
+ class User < ActiveRecord::Base
204
+ apply_simple_captcha
205
+ end
206
+
207
+ class User < ActiveRecord::Base
208
+ apply_simple_captcha :message => "The secret Image and code were different", :add_to_base => true
209
+ end
210
+
211
+ ==I18n
212
+
213
+ simple_captcha:
214
+ placeholder: "Enter the image value"
215
+ label: "Enter the code in the box:"
216
+ message:
217
+ default: "Secret Code did not match with the Image"
218
+ user: "The secret Image and code were different"
219
+
220
+ ==Who's who?
221
+
222
+ Enjoy the simplest captcha implementation.
223
+
224
+ Author: Sur
225
+
226
+ Blog: http://expressica.com
227
+
228
+ Contact: sur.max@gmail.com
229
+
230
+ Plugin Homepage: http://expressica.com/simple_captcha
231
+
232
+ Plugin update for rails 3: http://github.com/galetahub
233
+
234
+ Any feedback/comment/issue/donation is welcome!
data/Rakefile ADDED
@@ -0,0 +1,22 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+ require 'rake/rdoctask'
4
+
5
+ desc 'Default: run unit tests.'
6
+ task :default => :test
7
+
8
+ desc 'Test the simple_captcha plugin.'
9
+ Rake::TestTask.new(:test) do |t|
10
+ t.libs << 'lib'
11
+ t.pattern = 'test/**/*_test.rb'
12
+ t.verbose = true
13
+ end
14
+
15
+ desc 'Generate documentation for the simple_captcha plugin.'
16
+ Rake::RDocTask.new(:rdoc) do |rdoc|
17
+ rdoc.rdoc_dir = 'rdoc'
18
+ rdoc.title = 'SoaringSimpleCaptcha'
19
+ rdoc.options << '--line-numbers' << '--inline-source'
20
+ rdoc.rdoc_files.include('README')
21
+ rdoc.rdoc_files.include('lib/**/*.rb')
22
+ end
@@ -0,0 +1,4 @@
1
+ SimplaCaptcha
2
+ =============
3
+ # Generate migration and copy view partial
4
+ rails generate simple_captcha
@@ -0,0 +1,21 @@
1
+ require 'rails/generators'
2
+
3
+ class SimpleCaptchaGenerator < Rails::Generators::Base
4
+ include Rails::Generators::Migration
5
+
6
+ def self.source_root
7
+ @source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates/'))
8
+ end
9
+
10
+ def self.next_migration_number(dirname)
11
+ Time.now.strftime("%Y%m%d%H%M%S")
12
+ end
13
+
14
+ def create_partial
15
+ template "partial.erb", File.join('app/views', 'simple_captcha', "_simple_captcha.erb")
16
+ end
17
+
18
+ def create_migration
19
+ migration_template "migration.rb", File.join('db/migrate', "create_simple_captcha_data.rb")
20
+ end
21
+ end
@@ -0,0 +1,15 @@
1
+ class CreateSimpleCaptchaData < ActiveRecord::Migration
2
+ def self.up
3
+ create_table :simple_captcha_data do |t|
4
+ t.string :key, :limit => 40
5
+ t.string :value, :limit => 6
6
+ t.timestamps
7
+ end
8
+
9
+ add_index :simple_captcha_data, :key, :name => "idx_key"
10
+ end
11
+
12
+ def self.down
13
+ drop_table :simple_captcha_data
14
+ end
15
+ end
@@ -0,0 +1,37 @@
1
+ <style type="text/CSS">
2
+ .simple_captcha{border: 1px solid #ccc; padding: 5px !important;}
3
+ .simple_captcha,
4
+ .simple_captcha div{display: table;}
5
+ .simple_captcha .simple_captcha_field,
6
+ .simple_captcha .simple_captcha_image{
7
+ border: 1px solid #ccc;
8
+ margin: 0px 0px 2px 0px !important;
9
+ padding: 0px !important;
10
+ }
11
+ .simple_captcha .simple_captcha_image img{
12
+ margin: 0px !important;
13
+ padding: 0px !important;
14
+ width: 110px !important;
15
+ }
16
+ .simple_captcha .simple_captcha_label{font-size: 12px;}
17
+ .simple_captcha .simple_captcha_field input{
18
+ width: 150px !important;
19
+ font-size: 16px;
20
+ border: none;
21
+ background-color: #efefef;
22
+ }
23
+ </style>
24
+
25
+ <div class='simple_captcha'>
26
+ <div class='simple_captcha_image'>
27
+ <%%= simple_captcha_options[:image] %>
28
+ </div>
29
+
30
+ <div class='simple_captcha_field'>
31
+ <%%= simple_captcha_options[:field] %>
32
+ </div>
33
+
34
+ <div class='simple_captcha_label'>
35
+ <%%= simple_captcha_options[:label] %>
36
+ </div>
37
+ </div>
@@ -0,0 +1,62 @@
1
+ # encoding: utf-8
2
+
3
+ module SoaringSimpleCaptcha
4
+ autoload :Utils, 'soaring_simple_captcha/utils'
5
+
6
+ autoload :ImageHelpers, 'soaring_simple_captcha/image'
7
+ autoload :ViewHelper, 'soaring_simple_captcha/view'
8
+ autoload :ControllerHelpers, 'soaring_simple_captcha/controller'
9
+
10
+ autoload :FormBuilder, 'soaring_simple_captcha/form_builder'
11
+ autoload :CustomFormBuilder, 'soaring_simple_captcha/formtastic'
12
+
13
+ if defined?(ActiveRecord)
14
+ autoload :ModelHelpers, 'soaring_simple_captcha/active_record'
15
+ autoload :SimpleCaptchaData, 'soaring_simple_captcha/simple_captcha_data'
16
+ else
17
+ autoload :SimpleCaptchaData, 'soaring_simple_captcha/simple_captcha_data_mongoid.rb'
18
+ end
19
+
20
+
21
+ autoload :Middleware, 'soaring_simple_captcha/middleware'
22
+
23
+ mattr_accessor :image_size
24
+ @@image_size = "100x28"
25
+
26
+ mattr_accessor :length
27
+ @@length = 5
28
+
29
+ # 'embosed_silver',
30
+ # 'simply_red',
31
+ # 'simply_green',
32
+ # 'simply_blue',
33
+ # 'distorted_black',
34
+ # 'all_black',
35
+ # 'charcoal_grey',
36
+ # 'almost_invisible'
37
+ # 'random'
38
+ mattr_accessor :image_style
39
+ @@image_style = 'simply_blue'
40
+
41
+ # 'low', 'medium', 'high', 'random'
42
+ mattr_accessor :distortion
43
+ @@distortion = 'low'
44
+
45
+ # command path
46
+ mattr_accessor :image_magick_path
47
+ @@image_magick_path = ''
48
+
49
+ # tmp directory
50
+ mattr_accessor :tmp_path
51
+ @@tmp_path = nil
52
+
53
+ def self.add_image_style(name, params = [])
54
+ SoaringSimpleCaptcha::ImageHelpers.image_styles.update(name.to_s => params)
55
+ end
56
+
57
+ def self.setup
58
+ yield self
59
+ end
60
+ end
61
+
62
+ require 'soaring_simple_captcha/engine' if defined?(Rails)
@@ -0,0 +1,74 @@
1
+ module SoaringSimpleCaptcha #:nodoc
2
+ module ModelHelpers #:nodoc
3
+ def self.included(base)
4
+ base.extend(SingletonMethods)
5
+ end
6
+
7
+ # To implement model based simple captcha use this method in the model as...
8
+ #
9
+ # class User < ActiveRecord::Base
10
+ #
11
+ # apply_simple_captcha :message => "my customized message"
12
+ #
13
+ # end
14
+ #
15
+ # Customize the error message by using :message, the default message is "Captcha did not match".
16
+ # As in the applications captcha is needed with a very few cases like signing up the new user, but
17
+ # not every time you need to authenticate the captcha with @user.save. So as to maintain simplicity
18
+ # here we have the explicit method to save the instace with captcha validation as...
19
+ #
20
+ # * to validate the instance
21
+ #
22
+ # @user.valid_with_captcha? # whene captcha validation is required.
23
+ #
24
+ # @user.valid? # when captcha validation is not required.
25
+ #
26
+ # * to save the instance
27
+ #
28
+ # @user.save_with_captcha # whene captcha validation is required.
29
+ #
30
+ # @user.save # when captcha validation is not required.
31
+ module SingletonMethods
32
+ def apply_simple_captcha(options = {})
33
+ options = { :add_to_base => false }.merge(options)
34
+
35
+ class_attribute :simple_captcha_options
36
+ self.simple_captcha_options = options
37
+
38
+ unless self.is_a?(ClassMethods)
39
+ include InstanceMethods
40
+ extend ClassMethods
41
+
42
+ attr_accessor :captcha, :captcha_key
43
+ end
44
+ end
45
+ end
46
+
47
+ module ClassMethods
48
+ end
49
+
50
+ module InstanceMethods
51
+
52
+ def valid_with_captcha?
53
+ [valid?, is_captcha_valid?].all?
54
+ end
55
+
56
+ def is_captcha_valid?
57
+ return true if Rails.env.test?
58
+
59
+ if captcha && captcha.upcase.delete(" ") == SoaringSimpleCaptcha::Utils::simple_captcha_value(captcha_key)
60
+ SoaringSimpleCaptcha::Utils::simple_captcha_passed!(captcha_key)
61
+ return true
62
+ else
63
+ message = simple_captcha_options[:message] || I18n.t(self.class.model_name.downcase, :scope => [:simple_captcha, :message], :default => :default)
64
+ simple_captcha_options[:add_to_base] ? errors.add(:base, message) : errors.add(:captcha, message)
65
+ return false
66
+ end
67
+ end
68
+
69
+ def save_with_captcha
70
+ valid_with_captcha? && save(:validate => false)
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,29 @@
1
+ module SoaringSimpleCaptcha #:nodoc
2
+ module ControllerHelpers #:nodoc
3
+ # This method is to validate the simple captcha in controller.
4
+ # It means when the captcha is controller based i.e. :object has not been passed to the method show_simple_captcha.
5
+ #
6
+ # *Example*
7
+ #
8
+ # If you want to save an object say @user only if the captcha is validated then do like this in action...
9
+ #
10
+ # if simple_captcha_valid?
11
+ # @user.save
12
+ # else
13
+ # flash[:notice] = "captcha did not match"
14
+ # redirect_to :action => "myaction"
15
+ # end
16
+ def simple_captcha_valid?
17
+ return true if Rails.env.test?
18
+
19
+ if params[:captcha]
20
+ data = SoaringSimpleCaptcha::Utils::simple_captcha_value(params[:captcha_key] || session[:captcha])
21
+ result = data == params[:captcha].delete(" ").upcase
22
+ SoaringSimpleCaptcha::Utils::simple_captcha_passed!(session[:captcha]) if result
23
+ return result
24
+ else
25
+ return false
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,30 @@
1
+ # encoding: utf-8
2
+ require 'rails'
3
+ require 'soaring_simple_captcha'
4
+
5
+ module SoaringSimpleCaptcha
6
+ class Engine < ::Rails::Engine
7
+ config.before_initialize do
8
+ ActiveSupport.on_load :active_record do
9
+ ActiveRecord::Base.send(:include, SoaringSimpleCaptcha::ModelHelpers)
10
+ end
11
+ end
12
+
13
+ config.after_initialize do
14
+ ActionView::Base.send(:include, SoaringSimpleCaptcha::ViewHelper)
15
+ ActionView::Helpers::FormBuilder.send(:include, SoaringSimpleCaptcha::FormBuilder)
16
+
17
+ if Object.const_defined?("Formtastic")
18
+ if Formtastic.const_defined?("Helpers")
19
+ Formtastic::Helpers::FormHelper.builder = SoaringSimpleCaptcha::CustomFormBuilder
20
+ else
21
+ Formtastic::SemanticFormHelper.builder = SoaringSimpleCaptcha::CustomFormBuilder
22
+ end
23
+ end
24
+ end
25
+
26
+ config.app_middleware.use SoaringSimpleCaptcha::Middleware
27
+ end
28
+ end
29
+
30
+
@@ -0,0 +1,43 @@
1
+ module SoaringSimpleCaptcha
2
+ module FormBuilder
3
+ def self.included(base)
4
+ base.send(:include, SoaringSimpleCaptcha::ViewHelper)
5
+ base.send(:include, SoaringSimpleCaptcha::FormBuilder::ClassMethods)
6
+ base.send(:include, ActionView::Helpers)
7
+ if defined? Sprokets
8
+ base.send(:include, Sprockets::Helpers::RailsHelper)
9
+ base.send(:include, Sprockets::Helpers::IsolatedHelper)
10
+ end
11
+
12
+ base.delegate :render, :session, :to => :template
13
+ end
14
+
15
+ module ClassMethods
16
+ # Example:
17
+ # <% form_for :post, :url => posts_path do |form| %>
18
+ # ...
19
+ # <%= form.simple_captcha :label => "Enter numbers.." %>
20
+ # <% end %>
21
+ #
22
+ def simple_captcha(options = {})
23
+ options.update :object => @object_name
24
+ show_simple_captcha(objectify_options(options))
25
+ end
26
+
27
+ private
28
+
29
+ def template
30
+ @template
31
+ end
32
+
33
+ def simple_captcha_field(options={})
34
+ html = {:autocomplete => 'off', :required => 'required', :value => ''}
35
+ html.merge!(options[:input_html] || {})
36
+ html[:placeholder] = options[:placeholder] || I18n.t('simple_captcha.placeholder')
37
+
38
+ text_field(:captcha, html) +
39
+ hidden_field(:captcha_key, {:value => options[:field_value]})
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,11 @@
1
+ module SoaringSimpleCaptcha
2
+ class CustomFormBuilder < (defined?(::Formtastic::FormBuilder) ? Formtastic::FormBuilder : ::Formtastic::SemanticFormBuilder)
3
+
4
+ private
5
+
6
+ def simple_captcha_input(method, options)
7
+ options.update :object => sanitized_object_name
8
+ self.send(:show_simple_captcha, options)
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,86 @@
1
+ require 'tempfile'
2
+ module SoaringSimpleCaptcha #:nodoc
3
+ module ImageHelpers #:nodoc
4
+
5
+ mattr_accessor :image_styles
6
+ @@image_styles = {
7
+ 'embosed_silver' => ['-fill darkblue', '-shade 20x60', '-background white'],
8
+ 'simply_red' => ['-fill darkred', '-background white'],
9
+ 'simply_green' => ['-fill darkgreen', '-background white'],
10
+ 'simply_blue' => ['-fill darkblue', '-background white'],
11
+ 'distorted_black' => ['-fill darkblue', '-edge 10', '-background white'],
12
+ 'all_black' => ['-fill darkblue', '-edge 2', '-background white'],
13
+ 'charcoal_grey' => ['-fill darkblue', '-charcoal 5', '-background white'],
14
+ 'almost_invisible' => ['-fill red', '-solarize 50', '-background white']
15
+ }
16
+
17
+ DISTORTIONS = ['low', 'medium', 'high']
18
+
19
+ class << self
20
+
21
+ def image_params(key = 'simply_blue')
22
+ image_keys = @@image_styles.keys
23
+
24
+ style = begin
25
+ if key == 'random'
26
+ image_keys[rand(image_keys.length)]
27
+ else
28
+ image_keys.include?(key) ? key : 'simply_blue'
29
+ end
30
+ end
31
+
32
+ @@image_styles[style]
33
+ end
34
+
35
+ def distortion(key='low')
36
+ key =
37
+ key == 'random' ?
38
+ DISTORTIONS[rand(DISTORTIONS.length)] :
39
+ DISTORTIONS.include?(key) ? key : 'low'
40
+ case key.to_s
41
+ when 'low' then return [0 + rand(2), 80 + rand(20)]
42
+ when 'medium' then return [2 + rand(2), 50 + rand(20)]
43
+ when 'high' then return [4 + rand(2), 30 + rand(20)]
44
+ end
45
+ end
46
+ end
47
+
48
+ if RUBY_VERSION < '1.9'
49
+ class Tempfile < ::Tempfile
50
+ # Replaces Tempfile's +make_tmpname+ with one that honors file extensions.
51
+ def make_tmpname(basename, n = 0)
52
+ extension = File.extname(basename)
53
+ sprintf("%s,%d,%d%s", File.basename(basename, extension), $$, n, extension)
54
+ end
55
+ end
56
+ end
57
+
58
+ private
59
+
60
+ def generate_simple_captcha_image(simple_captcha_key) #:nodoc
61
+ amplitude, frequency = SoaringSimpleCaptcha::ImageHelpers.distortion(SoaringSimpleCaptcha.distortion)
62
+ text = Utils::simple_captcha_value(simple_captcha_key)
63
+
64
+ params = SoaringSimpleCaptcha::ImageHelpers.image_params(SoaringSimpleCaptcha.image_style).dup
65
+ params << "-size #{SoaringSimpleCaptcha.image_size}"
66
+ params << "-wave #{amplitude}x#{frequency}"
67
+ #params << "-gravity 'Center'"
68
+ params << "-gravity \"Center\""
69
+ params << "-pointsize 22"
70
+ params << "-implode 0.2"
71
+
72
+ dst = Tempfile.new(RUBY_VERSION < '1.9' ? 'simple_captcha.jpg' : ['simple_captcha', '.jpg'], SoaringSimpleCaptcha.tmp_path)
73
+ dst.binmode
74
+
75
+ #params << "label:#{text} '#{File.expand_path(dst.path)}'"
76
+ params << "label:#{text} \"#{File.expand_path(dst.path)}\""
77
+
78
+ SoaringSimpleCaptcha::Utils::run("convert", params.join(' '))
79
+
80
+ dst.close
81
+
82
+ File.expand_path(dst.path)
83
+ #dst
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,58 @@
1
+ # encoding: utf-8
2
+ module SoaringSimpleCaptcha
3
+ class Middleware
4
+ include SoaringSimpleCaptcha::ImageHelpers
5
+
6
+ DEFAULT_SEND_FILE_OPTIONS = {
7
+ :type => 'application/octet-stream'.freeze,
8
+ :disposition => 'attachment'.freeze,
9
+ }.freeze
10
+
11
+ def initialize(app, options={})
12
+ @app = app
13
+ self
14
+ end
15
+
16
+ def call(env) # :nodoc:
17
+ if env["REQUEST_METHOD"] == "GET" && captcha_path?(env['PATH_INFO'])
18
+ make_image(env)
19
+ else
20
+ @app.call(env)
21
+ end
22
+ end
23
+
24
+ protected
25
+ def make_image(env, headers = {}, status = 404)
26
+ request = Rack::Request.new(env)
27
+ code = request.params["code"]
28
+ body = []
29
+
30
+ if !code.blank? && SoaringSimpleCaptcha::Utils::simple_captcha_value(code)
31
+ #status, headers, body = @app.call(env)
32
+ #status = 200
33
+ #body = generate_simple_captcha_image(code)
34
+ #headers['Content-Type'] = 'image/jpeg'
35
+
36
+ return send_file(generate_simple_captcha_image(code), :type => 'image/jpeg', :disposition => 'inline', :filename => 'simple_captcha.jpg')
37
+ end
38
+
39
+ [status, headers, body]
40
+ end
41
+
42
+ def captcha_path?(request_path)
43
+ request_path.include?('/soaring_simple_captcha') || request_path.include?('/simple_captcha')
44
+ end
45
+
46
+ def send_file(path, options = {})
47
+ # raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path)
48
+
49
+ options[:filename] ||= File.basename(path) unless options[:url_based_filename]
50
+
51
+ status = options[:status] || 200
52
+ headers = {"Content-Disposition" => "#{options[:disposition]}; filename='#{options[:filename]}'", "Content-Type" => options[:type], 'Content-Transfer-Encoding' => 'binary', 'Cache-Control' => 'private'}
53
+ response_body = File.open(path, "rb")
54
+
55
+ [status, headers, response_body]
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,32 @@
1
+ module SoaringSimpleCaptcha
2
+ class SimpleCaptchaData < ::ActiveRecord::Base
3
+
4
+ if ::ActiveRecord::VERSION::MAJOR >= 3
5
+ # Fixes deprecation warning in Rails 3.2:
6
+ # DEPRECATION WARNING: Calling set_table_name is deprecated. Please use `self.table_name = 'the_name'` instead.
7
+ self.table_name = "simple_captcha_data"
8
+ else
9
+ set_table_name "simple_captcha_data"
10
+ end
11
+
12
+ #attr_accessible :key, :value
13
+
14
+ class << self
15
+ def get_data(key)
16
+ data = find_by_key(key) || new(:key => key)
17
+ end
18
+
19
+ def remove_data(key)
20
+ # delete_all(["#{connection.quote_column_name(:key)} = ?", key])
21
+ find_by(key: key).destroy
22
+ clear_old_data(1.hour.ago)
23
+ end
24
+
25
+ def clear_old_data(time = 1.hour.ago)
26
+ return unless Time === time
27
+ # delete_all(["#{connection.quote_column_name(:updated_at)} < ?", time])
28
+ where("updated_at < ?", time).each{|r|r.destroy}
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,25 @@
1
+ module SoaringSimpleCaptcha
2
+ class SimpleCaptchaData
3
+ include Mongoid::Document
4
+ include Mongoid::Timestamps
5
+
6
+ field :key, type: String
7
+ field :value, type: String
8
+
9
+ class << self
10
+ def get_data(key)
11
+ data = where(:key => key).first || new(:key => key)
12
+ end
13
+
14
+ def remove_data(key)
15
+ where(:key => key).delete_all
16
+ clear_old_data(1.hour.ago)
17
+ end
18
+
19
+ def clear_old_data(time = 1.hour.ago)
20
+ return unless Time === time
21
+ where(:updated_at.lte => time).delete_all
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,36 @@
1
+ require 'digest/sha1'
2
+
3
+ module SoaringSimpleCaptcha #:nodoc
4
+ module Utils #:nodoc
5
+ # Execute command with params and return output if exit status equal expected_outcodes
6
+ def self.run(cmd, params = "", expected_outcodes = 0)
7
+ command = %Q[#{cmd} #{params}].gsub(/\s+/, " ")
8
+ command = "#{command} 2>&1"
9
+
10
+ unless (image_magick_path = SoaringSimpleCaptcha.image_magick_path).blank?
11
+ command = File.join(image_magick_path, command)
12
+ end
13
+
14
+ output = `#{command}`
15
+
16
+ unless [expected_outcodes].flatten.include?($?.exitstatus)
17
+ raise ::StandardError, "Error while running #{cmd}: #{output}"
18
+ end
19
+
20
+ output
21
+ end
22
+
23
+ def self.simple_captcha_value(key) #:nodoc
24
+ SimpleCaptchaData.get_data(key).value rescue nil
25
+ end
26
+
27
+ def self.simple_captcha_passed!(key) #:nodoc
28
+ SimpleCaptchaData.remove_data(key)
29
+ end
30
+
31
+ def self.generate_key(*args)
32
+ args << Time.now.to_s
33
+ Digest::SHA1.hexdigest(args.join)
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,3 @@
1
+ module SoaringSimpleCaptcha
2
+ VERSION = "0.1.6".freeze
3
+ end
@@ -0,0 +1,115 @@
1
+ module SoaringSimpleCaptcha #:nodoc
2
+ module ViewHelper #:nodoc
3
+
4
+ # Simple Captcha is a very simplified captcha.
5
+ #
6
+ # It can be used as a *Model* or a *Controller* based Captcha depending on what options
7
+ # we are passing to the method show_simple_captcha.
8
+ #
9
+ # *show_simple_captcha* method will return the image, the label and the text box.
10
+ # This method should be called from the view within your form as...
11
+ #
12
+ # <%= show_simple_captcha %>
13
+ #
14
+ # The available options to pass to this method are
15
+ # * label
16
+ # * object
17
+ #
18
+ # <b>Label:</b>
19
+ #
20
+ # default label is "type the text from the image", it can be modified by passing :label as
21
+ #
22
+ # <%= show_simple_captcha(:label => "new captcha label") %>.
23
+ #
24
+ # *Object*
25
+ #
26
+ # This option is needed to create a model based captcha.
27
+ # If this option is not provided, the captcha will be controller based and
28
+ # should be checked in controller's action just by calling the method simple_captcha_valid?
29
+ #
30
+ # To make a model based captcha give this option as...
31
+ #
32
+ # <%= show_simple_captcha(:object => "user") %>
33
+ # and also call the method apply_simple_captcha in the model
34
+ # this will consider "user" as the object of the model class.
35
+ #
36
+ # *Examples*
37
+ # * controller based
38
+ # <%= show_simple_captcha(:label => "Human Authentication: type the text from image above") %>
39
+ # * model based
40
+ # <%= show_simple_captcha(:object => "person", :label => "Human Authentication: type the text from image above") %>
41
+ #
42
+ # Find more detailed examples with sample images here on my blog http://EXPRESSICA.com
43
+ #
44
+ # All Feedbacks/CommentS/Issues/Queries are welcome.
45
+ def show_simple_captcha(options={})
46
+ key = simple_captcha_key(options[:object])
47
+ options[:field_value] = set_simple_captcha_data(key, options)
48
+
49
+ defaults = {
50
+ :image => simple_captcha_image(key, options),
51
+ :label => options[:label] || I18n.t('simple_captcha.label'),
52
+ :field => simple_captcha_field(options)
53
+ }
54
+
55
+ render :partial => 'simple_captcha/simple_captcha', :locals => { :simple_captcha_options => defaults }
56
+ end
57
+
58
+ private
59
+
60
+ def simple_captcha_image(simple_captcha_key, options = {})
61
+ defaults = {}
62
+ defaults[:time] = options[:time] || Time.now.to_i
63
+
64
+ query = defaults.collect{ |key, value| "#{key}=#{value}" }.join('&')
65
+ url = "#{ENV['RAILS_RELATIVE_URL_ROOT']}/simple_captcha?code=#{simple_captcha_key}&#{query}"
66
+
67
+ tag('img', :src => url, :alt => 'captcha')
68
+ end
69
+
70
+ def simple_captcha_field(options={})
71
+ html = {:autocomplete => 'off', :required => 'required'}
72
+ html.merge!(options[:input_html] || {})
73
+ html[:placeholder] = options[:placeholder] || I18n.t('simple_captcha.placeholder')
74
+
75
+ if options[:object]
76
+ text_field(options[:object], :captcha, html.merge(:value => '')) +
77
+ hidden_field(options[:object], :captcha_key, {:value => options[:field_value]})
78
+ else
79
+ text_field_tag(:captcha, nil, html) +
80
+ hidden_field_tag(:captcha_key, options[:field_value])
81
+ end
82
+ end
83
+
84
+ def set_simple_captcha_data(key, options={})
85
+ code_type = options[:code_type]
86
+
87
+ value = generate_simple_captcha_data(code_type)
88
+ data = SoaringSimpleCaptcha::SimpleCaptchaData.get_data(key)
89
+ data.value = value
90
+ data.save
91
+ key
92
+ end
93
+
94
+ def generate_simple_captcha_data(code)
95
+ value = ''
96
+
97
+ case code
98
+ when 'numeric' then
99
+ SoaringSimpleCaptcha.length.times{value << (48 + rand(10)).chr}
100
+ else
101
+ SoaringSimpleCaptcha.length.times{value << (65 + rand(26)).chr}
102
+ end
103
+
104
+ return value
105
+ end
106
+
107
+ def simple_captcha_key(key_name = nil)
108
+ if key_name.nil?
109
+ session[:captcha] ||= SoaringSimpleCaptcha::Utils.generate_key(session[:id].to_s, 'captcha')
110
+ else
111
+ SoaringSimpleCaptcha::Utils.generate_key(session[:id].to_s, key_name)
112
+ end
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,8 @@
1
+ require 'test/unit'
2
+
3
+ class SimpleCaptchaTest < Test::Unit::TestCase
4
+ # Replace this with your real tests.
5
+ def test_this_plugin
6
+ flunk
7
+ end
8
+ end
metadata ADDED
@@ -0,0 +1,66 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: soaring_simple_captcha
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.6
5
+ platform: ruby
6
+ authors:
7
+ - Pavlo Galeta
8
+ - Igor Galeta
9
+ - hinagiku
10
+ autorequire:
11
+ bindir: bin
12
+ cert_chain: []
13
+ date: 2021-07-24 00:00:00.000000000 Z
14
+ dependencies: []
15
+ description: SoaringSimpleCaptcha is available to be used with Rails 3 or above and
16
+ also it provides the backward compatibility with previous versions of Rails.
17
+ email: chenliang@soaring.com
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files:
21
+ - README.rdoc
22
+ files:
23
+ - README.rdoc
24
+ - Rakefile
25
+ - lib/generators/USAGE
26
+ - lib/generators/simple_captcha_generator.rb
27
+ - lib/generators/templates/migration.rb
28
+ - lib/generators/templates/partial.erb
29
+ - lib/soaring_simple_captcha.rb
30
+ - lib/soaring_simple_captcha/active_record.rb
31
+ - lib/soaring_simple_captcha/controller.rb
32
+ - lib/soaring_simple_captcha/engine.rb
33
+ - lib/soaring_simple_captcha/form_builder.rb
34
+ - lib/soaring_simple_captcha/formtastic.rb
35
+ - lib/soaring_simple_captcha/image.rb
36
+ - lib/soaring_simple_captcha/middleware.rb
37
+ - lib/soaring_simple_captcha/simple_captcha_data.rb
38
+ - lib/soaring_simple_captcha/simple_captcha_data_mongoid.rb
39
+ - lib/soaring_simple_captcha/utils.rb
40
+ - lib/soaring_simple_captcha/version.rb
41
+ - lib/soaring_simple_captcha/view.rb
42
+ - test/simple_captcha_test.rb
43
+ homepage: http://github.com/hinagiku/soaring_simple_captcha
44
+ licenses: []
45
+ metadata: {}
46
+ post_install_message:
47
+ rdoc_options: []
48
+ require_paths:
49
+ - lib
50
+ required_ruby_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ required_rubygems_version: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: '0'
60
+ requirements: []
61
+ rubygems_version: 3.2.3
62
+ signing_key:
63
+ specification_version: 4
64
+ summary: SoaringSimpleCaptcha is the simplest and a robust captcha plugin for soaring.
65
+ test_files:
66
+ - test/simple_captcha_test.rb