• Stars
    star
    686
  • Rank 63,322 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 8 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Captcha Gem for Rails, which generates captcha image by Rust.

RuCaptcha

Gem Version build

Captcha Gem for Rails, which generates captcha image by Rust.

NOTE: According to the use of Ruby China, the verification code looks like has a lower than 5% probability of being parsed by OCR and the verification code is cracked (All Image Captcha libs are has same problem). It is recommended that you use the IP rate limit to enhance the protection. NOTE: 以 Ruby China 的使用来看,验证码似乎有低于 5% 的概率被 OCR 读取解析 (图片验证码都有这个问题) 导致验证码被破解(我们从日志分析绝大多数是成功的,但偶尔一个成功,配合大量机器攻击,导致注册了很多的垃圾账号),建议你额外配合 IP 频率限制的功能来加强保护。

如果你需要更高强度的验证,建议选择商用服务。

中文介绍和使用说明

Example

0 1 2 3 4 5 6 7 8 9

Feature

  • Native Gem base on Rust.
  • For Rails Application;
  • Simple, Easy to use;
  • High performance.

Usage

Put rucaptcha in your Gemfile:

gem 'rucaptcha'

Create config/initializers/rucaptcha.rb

RuCaptcha.configure do
  # Custom captcha code expire time if you need, default: 2 minutes
  # self.expires_in = 120

  # [Requirement / 重要]
  # Store Captcha code where, this config more like Rails config.cache_store
  # default: Read config info from `Rails.application.config.cache_store`
  # But RuCaptcha requirements cache_store not in [:null_store, :memory_store, :file_store]
  # 默认:会从 Rails 配置的 cache_store 里面读取相同的配置信息,并尝试用可以运行的方式,用于存储验证码字符
  # 但如果是 [:null_store, :memory_store, :file_store] 之类的,你可以通过下面的配置项单独给 RuCaptcha 配置 cache_store
  self.cache_store = :mem_cache_store

  # If you wants disable `cache_store` check warning, you can do it, default: false
  # 如果想要 disable cache_store 的 warning,就设置为 true,default false
  # self.skip_cache_store_check = true

  # Chars length, default: 5, allows: [3 - 7]
  # self.length = 5

  # Enable or disable Strikethrough, default: true
  # self.line = true

  # Enable or disable noise, default: false
  # self.noise = false

  # Set the image format, default: png, allows: [jpeg, png, webp]
  # self.format = 'png'

  # Custom mount path, default: '/rucaptcha'
  # self.mount_path = '/rucaptcha'
end

RuCaptcha 没有使用 Rails Session 来存储验证码信息,因为 Rails 的默认 Session 是存储在 Cookie 里面,如果验证码存在里面会存在 Replay attack 漏洞,导致验证码关卡被攻破。

所以我在设计上要求 RuCaptcha 得配置一个可以支持分布式的后端存储方案例如:Memcached 或 Redis 以及其他可以支持分布式的 cache_store 方案。

同时,为了保障易用性,默认会尝试使用 :file_store 的方式,将验证码存在应用程序的 tmp/cache/rucaptcha/session 目录(但请注意,多机器部署这样是无法正常运作的)。

所以,我建议大家使用的时候,配置上 cache_store (详见 Rails Guides 缓存配置部分的文档)到一个 Memcached 或 Redis,这才是最佳实践。

(RuCaptha do not use Rails Session to store captcha information. As the default session is stored in Cookie in Rails, there's a Replay attack bug which may causes capthcha being destroyed if we store captcha in Rails Session.

So in my design I require RuCaptcha to configure a distributed backend storage scheme, such as Memcached, Redis or other cache_store schemes which support distribution.

Meanwhile, for the ease of use, RuCapthca would try to use :file_store by default and store the capthca in tmp/cache/rucaptcha/session directory (kindly note that it's not working if deploy on multiple machine).

For recommendation, configure the cache_store(more details on Rails Guides Configuration of Cache Stores) to Memcached or Redis, that would be the best practice.)

Controller app/controller/account_controller.rb

When you called verify_rucaptcha?, it uses value from params[:_rucaptcha] to validate.

class AccountController < ApplicationController
  def create
    @user = User.new(params[:user])
    if verify_rucaptcha?(@user) && @user.save
      redirect_to root_path, notice: 'Sign up successed.'
    else
      render 'account/new'
    end
  end
end

class ForgotPasswordController < ApplicationController
  def create
    # without any args
    if verify_rucaptcha?
      to_send_email
    else
      redirect_to '/forgot-password', alert: 'Invalid captcha code.'
    end
  end
end

TIP: Sometimes you may need to keep last verified captcha code in session on verify_rucaptcha? method call, you can use keep_session: true. For example: verify_rucaptcha? @user, keep_session: true.

View app/views/account/new.html.erb

<form method="POST">
  ...
  <div class="form-group">
    <%= rucaptcha_input_tag(class: 'form-control', placeholder: 'Input Captcha') %>
    <%= rucaptcha_image_tag(alt: 'Captcha') %>
  </div>
  ...

  <div class="form-group">
    <button type="submit" class="btn btn-primary">Submit</button>
  </div>
</form>

And if you are using Devise, you can read this reference to add validation: RuCaptcha with Devise.

Write your test skip captcha validation

for RSpec

describe 'sign up and login', type: :feature do
  before do
    allow_any_instance_of(ActionController::Base).to receive(:verify_rucaptcha?).and_return(true)
  end

  it { ... }
end

for MiniTest

class ActionDispatch::IntegrationTest
  def sign_in(user)
    ActionController::Base.any_instance.stubs(:verify_rucaptcha?).returns(true)
    post user_session_path \
         'user[email]'    => user.email,
         'user[password]' => user.password
  end
end

Invalid message without Devise

When you are using this gem without Devise, you may find out that the invalid message is missing. For this case, use the trick below to add your i18n invalid message manually.

if verify_rucaptcha?(@user) && @user.save
  do_whatever_you_want
  redirect_to someplace_you_want
else
  # this is the trick
  @user.errors.add(:base, t('rucaptcha.invalid'))
  render :new
end

Performance

rake benchmark to run benchmark test.

Warming up --------------------------------------
      Generate image    51.000  i/100ms
Calculating -------------------------------------
      Generate image    526.350  (± 2.5%) i/s -      2.652k in   5.041681s

More Repositories

1

rails-settings-cached

Global settings for your Rails application.
Ruby
1,005
star
2

flora-kit

💐 基于 shadowsocks-go 做的完善实现,自动网络分流,完全兼容 Surge 的配置文件。
Go
898
star
3

autocorrect

A linter and formatter to help you to improve copywriting, correct spaces, words, and punctuations between CJK (Chinese, Japanese, Korean).
Rust
770
star
4

redis-search

Deprecated! High performance real-time prefix search, indexes store in Redis for Rails application
Ruby
712
star
5

quora

Quora.com like project with Ruby on Rails (不再维护)
JavaScript
684
star
6

init.d

⚙️ Batch scripts for Rails production environment install on Ubuntu Server.
678
star
7

bluedoc

An open-source document management tool for enterprise self host.
Ruby
623
star
8

social-share-button

Helper for add social share feature in your Rails app. Twitter, Facebook, Weibo, Douban ...
CoffeeScript
581
star
9

PokemonGoMove

Pokemon GO iOS GPS Emulator - NO Jailbreak needed, lets you play the game on your Mac :)
Python
412
star
10

imax.im

🎬 Source code of IMAX.im
Ruby
366
star
11

mediom

Forum web application, an example for from Rails to Go (Revel)
Go
355
star
12

jquery.qeditor

This is a simple WYSIWYG editor with jQuery.
CoffeeScript
259
star
13

carrierwave-aliyun

阿里云 OSS Ruby 上传组件,基于 Carrierwave
Ruby
195
star
14

auto-correct

Automatically add whitespace between CJK (Chinese, Japanese, Korean) and half-width characters (alphabetical letters, numerical digits and symbols).
Ruby
142
star
15

activestorage-aliyun

Wraps the Aliyun OSS as an Active Storage service.
Ruby
130
star
16

sails

Create a Thrift Server use like Rails
Ruby
71
star
17

turbolinks-prefetch

Turbolinks extends for prefetch links to speeds up your website.
JavaScript
70
star
18

personlab

我博客的源代码,这个代码较老,不推荐拿来学习
Ruby
69
star
19

vimmate

Custom vim like Textmate for Ruby on Rails development
Vim Script
69
star
20

mongoid_auto_increment_id

Override id field to MySQL like auto increment for Mongoid.
Ruby
65
star
21

hello-go

入门 Go 编写应用
Go
56
star
22

pasite

Share your sources code on the web, see the http://pasite.org
Ruby
55
star
23

sql-builder

A simple SQL builder for generate SQL for non-ActiveRecord supports databases
Ruby
36
star
24

rails-activestorage-example

Rails use Active Storage the right way
Ruby
30
star
25

redmine-theme-innerboard

Innerboard theme for Redmine
26
star
26

cocoaout

Auto build and release tool for Cocoa projects.
Ruby
25
star
27

enumize

Extend ActiveRecord::Enum for add more helpful methods.
Ruby
24
star
28

jquery.lazyimg

Image lazy load plugin for jQuery, fork from jquery.unveil to improve performance with huge DOMs.
CoffeeScript
23
star
29

gitlab-mail-receiver

The way of allow your GitLab support Email receive and parse the email content, and find Issue/MergeRequest to create reply.
Ruby
23
star
30

redis-search-example

An example for use redis-search gem
JavaScript
23
star
31

ip-location

通过淘宝 IP 库查询 IP 所在地域位置 http://ip.taobao.com
Ruby
18
star
32

mongoid_taggable_on

Taggable on custom fields for Mongoid
Ruby
16
star
33

zed-theme-macos-classic

A macOS native style theme for Zed, let it same like native app in macOS.
JavaScript
13
star
34

backup-aliyun

Aliyun OSS storage with Backup
Ruby
12
star
35

jdialog

a jQuery popup window plugin
JavaScript
12
star
36

vscode-macos-classic.theme

macOS Classic theme for Visual Studio Code
Makefile
11
star
37

html-pipeline.cr

HTML processing filters and utilities for Crystal.
Crystal
11
star
38

vue-rails-example

Use Vue.js in Rails 6 example
Ruby
9
star
39

actiontext-lite

Lite version of ActionText
Ruby
7
star
40

docker-rails

Deploy Rails via Docker example
Ruby
5
star
41

vscode-blackboard-plus.theme

Visual Studio Code - Blackboard Plus Theme
4
star
42

booklib

php + Codeigniter Library management tool
PHP
4
star
43

remarkdown

This is extends of Markdown lib from Crystal Stdlib for Support Markdown GFM.
Crystal
4
star
44

autocorrect-action

GitHub action for use AutoCorrect as lint
Shell
3
star
45

huacnlee.github.io

Ruby
3
star
46

vscode-autocorrect

AutoCorrect for VS Code
TypeScript
3
star
47

sidekiq-activerecord-shard

Sidekiq middleware to supports ActiveRecord 7 shard
Ruby
3
star
48

autocorrect-idea-plugin

AutoCorrect Plugin for IntelliJ IDEA
Kotlin
2
star
49

auto-booking-park

Shell
2
star
50

jselectdate

jQuery date choice control with dropdown list
JavaScript
2
star
51

capistrano-upload-configs

Capistrano plugin for Upload local config files to remote, and create soft link.
Ruby
2
star
52

micro-web-simple

Go
1
star
53

jimagelink

模拟yupoo的缩略图上的小图标效果的jQuery插件
JavaScript
1
star
54

jcaches

client side cache with Javascript
JavaScript
1
star
55

yjs-server

JavaScript
1
star
56

Light-Classic.tmTheme

Improve of TextMate Light Theme from Mac Classic
1
star
57

zed-extension-action

GitHub Action for automatically bump Zed Extensions version after a release.
JavaScript
1
star