-
Notifications
You must be signed in to change notification settings - Fork 41
/
feedback_captcha.rb
92 lines (76 loc) · 2.31 KB
/
feedback_captcha.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
require 'digest/md5'
class FeedbackCaptcha
include WebivaCaptcha::HandlerSupport
include SimpleCaptchaImage
def self.webiva_captcha_handler_info
{
:name => 'Feedback Captcha',
:class => 'FeedbackCaptcha'
}
end
def initialize(controller)
super controller
@captcha_session = WebivaCaptcha::Session.new self.session, self.class.to_s.underscore
@valid = true
end
def validate(options={})
@valid = false
return @valid if self.params[:captcha_text].blank? || self.phrase.blank?
@valid = self.params[:captcha_text].downcase == self.phrase.downcase
end
def generate(options={})
self.generate_phrase((options[:length] || 6).to_i)
self.controller.send(:render_to_string, :partial => self.partial, :locals => {:captcha => self, :options => options})
end
def render(options={})
return nil unless self.params[:path] && self.params[:path][0]
@captcha_code = self.params[:path][0]
if self.phrase
controller.response.content_type = 'image/jpeg'
generate_simple_captcha_image options
else
controller.response.content_type = 'image/jpeg'
generate_invalid_captcha_image
end
end
def captcha_code
return @captcha_code if @captcha_code
@captcha_code = self.params[:captcha_code] || Digest::MD5::hexdigest(rand.to_s)
end
def phrase
@captcha_session.get_phrase self.captcha_code
end
def url
"/website/feedback/captcha/image/#{self.captcha_code}?Z=#{Time.now.to_i}"
end
def partial
'/feedback/captcha/feedback_captcha'
end
def generate_phrase(length)
chars = ('A'..'Z').to_a + ('1'..'9').to_a - ['O']
phrase = ((1..length).collect { |i| chars[rand(chars.size-1)] }).join
@captcha_session.add self.captcha_code, phrase
end
def simple_captcha_value(key=nil)
self.phrase
end
def valid?
@valid
end
def generate_invalid_captcha_image #:nodoc
@image = Magick::Image.new(110, 30) do
self.background_color = 'white'
self.format = 'JPG'
end
color = 'black'
text = Magick::Draw.new
text.annotate(@image, 0, 0, 0, 5, 'Invalid Captcha'.t) do
self.font_family = 'arial'
self.font_weight = Magick::BoldWeight
self.pointsize = 15
self.fill = color
self.gravity = Magick::CenterGravity
end
@image.implode(0).to_blob
end
end