Recommendations for a captcha on Ruby on Rails [closed] - ruby-on-rails

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I'd like to implement a captcha in a Rails project for a form submission, but I'm not sure what to go with. I'm inclining towards simplicity of implemention, and reliability when in use, over it being too sophisticated, as my application doesn't require too high a level of security.
Anyone have any recommendations?

The easiest way to add a CAPTCHA to your Rails application is using Ambethia reCAPTCHA:
1. Installation:
config.gem "ambethia-recaptcha", :lib => "recaptcha/rails",
:source => "http://gems.github.com"
You can install it as a plugin, too, if you like.
2. Get a reCAPTCHA account:
You have to create a reCAPTCHA key. You can do it on the reCAPTCHA site.
3. Usage:
Use recaptcha_tags to output the necessary HTML code and then verify the input with verify_recaptcha.
4. Further reading:
Ambethia reCAPTCHA
reCAPTCHA documentation

Installation
Add the following to your GEMFILE
gem "galetahub-simple_captcha", :require => "simple_captcha"
or
gem 'galetahub-simple_captcha', :require => 'simple_captcha',
:git => 'git://github.com/galetahub/simple-captcha.git'
Then run bundle install if you're using Bundler (or use the package manager for your Rails configuration)
Setup
After installation, follow these simple steps to setup the plugin. The setup will depend on the version of rails your application is using.
rails generate simple_captcha
rake db:migrate
Usage
Controller Based
Add the following line in the file “app/controllers/application.rb”
ApplicationController < ActionController::Base
include SimpleCaptcha::ControllerHelpers
end
In the view file within the form tags add this code
<%= show_simple_captcha %>
and in the controller’s action authenticate it as
if simple_captcha_valid?
do this
else
do that
end
Model Based
In the view file within the form tags add this code
<%= show_simple_captcha(:object=>"user") %>
and in the model class add this code
class User < ActiveRecord::Base
apply_simple_captcha
end
FormBuilder helper
<%= form_for #user do |form| -%>
...
<%= form.simple_captcha :label => "Enter numbers.." %>
...
<% end -%>
Validating with captcha
NOTE: #user.valid? will still work as it should, it will not validate the captcha code.
#user.valid_with_captcha?
Saving with captcha
NOTE: #user.save will still work as it should, it will not validate the captcha code.
#user.save_with_captcha
Formtastic integration
SimpleCaptcha detects if your use Formtastic and appends
“SimpleCaptcha::CustomFormBuilder”.
<%= form.input :captcha, :as => :simple_captcha %>
Options & Examples
View Options
*label* - provides the custom text b/w the image and the text field, the default is “type the code from the image”
*object* - the name of the object of the model class, to implement the model based captcha.
*code_type* - return numeric only if set to ‘numeric’
Global options
image_style - provides the specific image style for the captcha image.
There are eight different styles available with the plugin as…
simply_blue
simply_red
simply_green
charcoal_grey
embosed_silver
all_black
distorted_black
almost_invisible
Default style is ‘simply_blue’. You can also specify ‘random’ to select the random image style.
distortion - handles the complexity of the image. The :distortion can be set to ‘low’, ‘medium’ or ‘high’. Default is ‘low’.
*Create “rails_root/config/initializers/simple_captcha.rb”*
SimpleCaptcha.setup do |sc|
# default: 100x28
sc.image_size = '120x40'
# default: 5
sc.length = 6
# default: simply_blue
# possible values:
# 'embosed_silver',
# 'simply_red',
# 'simply_green',
# 'simply_blue',
# 'distorted_black',
# 'all_black',
# 'charcoal_grey',
# 'almost_invisible'
# 'random'
sc.image_style = 'simply_green'
# default: low
# possible values: 'low', 'medium', 'high', 'random'
sc.distortion = 'medium'
end
You can add your own style:
SimpleCaptcha.setup do |sc|
sc.image_style = 'mycaptha'
sc.add_image_style('mycaptha', [
"-background '#F4F7F8'",
"-fill '#86818B'",
"-border 1",
"-bordercolor '#E0E2E3'"])
end
You can provide the path where image_magick is installed as well:
SimpleCaptcha.setup do |sc|
sc.image_magick_path = '/usr/bin' # you can check this from console by running: which convert
end
You can provide the path where should be stored tmp files. It’s usefull when you dont have acces to /tmp (default directory)
SimpleCaptcha.setup do |sc|
sc.tmp_path = '/tmp' # or somewhere in project eg. Rails.root.join('tmp/simple_captcha').to_s, make shure directory exists
end
How to change the CSS for SimpleCaptcha DOM elements?
You can change the CSS of the SimpleCaptcha DOM elements as per your need in this file.
*/app/views/simple_captcha/_simple_captcha.erb*
View’s Examples
Controller Based Example
<%= show_simple_captcha %>
<%= show_simple_captcha(:label => "human authentication") %>
Model Based Example
<%= show_simple_captcha(:object => 'user', :label => "human authentication") %>
Model Options
message - provides the custom message on failure of captcha authentication the default is “Secret Code did not match with the Image”
add_to_base - if set to true, appends the error message to the base.
Model’s Example
class User < ActiveRecord::Base
apply_simple_captcha
end
class User < ActiveRecord::Base
apply_simple_captcha :message => "The secret Image and code were different", :add_to_base => true
end

Well, ReCaptcha will do the job and there are many tutorials on it online.
However, you have to write a correct "def create" (create method) in your controller that will pass whatever is in your form plus validate Recaptcha at the same time. Then it will work nicely.
There was one little problem with it. After I inserted ReCaptcha into my form, the form validation stopped working. However, it can be fixed with an easy code inserted into the model file:
after_validation :on => :create
(:create = is the "def create" method in your controller). It will force the form to validate the form first and then validate Recaptcha.

I've used Recaptcha in one of my PHP project. http://recaptcha.net/
According to the site, it also has plugins for Ruby (http://recaptcha.net/resources.html). Although first ruby link didn't work, next link still works. http://svn.ambethia.com/pub/rails/plugins/recaptcha/
Check it.

I've used ambethia recapchat for rails application. it most easy than other

reCAPTCHA for rails is great, in terms of functionality. However, if you require XHTML validation, RUN AWAY! This plugin does not (and probably never will) validate. I find it embarrassing that only one page on my entire site does not validate - it is the page with reCAPTCHA. If there was ANY other choice, I would take it.

if you're after a CAPTCHA that validates, and is (almost) as easy to use as reCAPTCHA, please give my SlideCAPTCHA a try. (Wrote it a few days ago, needs some tests in real-life usage.) I based its deployment process on the reCAPTCHA plugin, but you can style it with CSS.
It does require Ruby/GD, however, so if you don't have GD already, I can't promise that GD is easy to install and use!

Related

Rails gem Ratyrate showings stars only after refresh and not saving

(Saw many posts with these problems and got it working, so I will upload solution)
I'm using Ratyrate without Devise and the stars only appear after a web refresh and they do not save the previously assigned rate.
Fixed this issue with:
Specifying version in each Rating Migration (currently using ActiveRecord::Migration[5.1])
Changing Rate Controller "create" method, replacing "if user_signed_in?" with "if current_user"
Adding "post '/rate' => 'rater#create', :as => 'rate'" to routes.rb (gem should do this for you)
Adding
<%= javascript_include_tag 'ratyrate.js', "data-turbolinks-track": false %> at the bottom of show.html.erb (the view of the model you want to rate)
Hope this helps !

Building sites using rails [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am new to programming. A friend suggested I start with rails.Once in,I realize,Rails has steep learning curve for a non programmer. Then I come across this tutorial https://www.youtube.com/watch?v=quLmIuIrIigaches
It teaches how to build a website locally in 12 minutes ... JustIt says ... 1. Make a rails app
2. Get an html template
3. Add js,css,images to relevant folder generated in rails_app>>apps>>views.
4. The site is ready
Is that all there is to rails ? The other tutorials are rally hard. or could you suggest me some tutorial that directly gets me into a real life prject and teaches along the way ?
Thank you :)
I am new to programming
Some of the best programmers live on the computer. They have a deep appreciation for the structure, flow & artistry required to craft digital experiences.
If you're new to programming, make a point of looking into what interests you with the system; if it's games, try and look up how games like DOOM were created etc. This will help you more than reading tutorials on how to do generic things.
Foundation
If you're really new to programming, build yourself a website, using HTML and CSS. This will give you appreciation of how Rails works.
Here are some basic tutorials on making HTML/CSS websites (you'd be surprised at how many people got their start making base level websites):
4 Hour Long HTML/CSS Tutorial (long tutorials are generally a waste of time)
15 minute HTML/CSS/JS tutorial (this is more the time you should be looking at)
A 23 minute long tutorial (this looks good but might be a bit long)
Read up on the HTTP protocol, how HTML fits into the the "web", how the world wide web != the "Internet", and was invented in 1989 by Tim Berners Lee.
Read up how Windows95 changed the game, how Marc Andreessen brought people online with Mosaic and NetScape. How Apple brought more people online with iMac and the iPhone.
Read up about how Elon Musk and his merry band of rogues started to monetize the Internet with companies such as Amazon, Zip2, Paypal, Google, etc, etc.
Rails is the distillation of all this stuff.
It will also help you appreciate that web apps are not some golden ticket to riches. Real people use the Internet; your app has to benefit them in some way.
Getting Started
Here's a tutorial:
Download & Install Ruby & RubyGems on your system
If you're using Windows, you can use RubyInstaller, or better still RailsInstaller. It's recommended you use Linux to develop Rails, but it's not essential. We use Windows and people always raise question with it :)
Once you have Ruby installed, in your cmd, you can type gem install rails. This will install the Rails Gem (explained in a second)
4. Once you have Rails installed, you're ready to start developing an "app".
To clarify the role of Ruby and Rails, you have to appreciate that Ruby is the language, Rails the framework.
This means that when dealing with your development environment (OS), you'll be mainly dealing with your Ruby installation. Rails is a layer of abstraction higher than Ruby. Programming issues are typically a Rails problem, environment issues are typically a Ruby issue.
RubyGems is the dependency library for Ruby. Although Rails works perfectly with almost all Ruby Gems, the gems are for Ruby. Most people don't know that Rails is just a gem for Ruby...
First App
Here's how to make a simple app (it will look like shit):
In your CMD, cd to a directory, and type rails new app_name:
This puts all the Rails files in the directory you cd'd into.
This will allow you to then boot up the Rails server. However, before you do that, you need to make sure you have a database.
Rails ships with SQLite, which I've never used. Apparently it stores data in files, which should give you the ability to start developing out of the gate.
We use a simple MYSQL database server on some shared hosting. This gives us the ability to just use it for development, it adds latency but retains data integrity.
I'll let you ask another question about the db. It's another matter in itself.
--
Once you've generated your rails app, you'll be able to boot up the Rails server.
Do this by typing rails s / rails server in your cmd:
(Sorry, this is the best picture I could find)...
The standard Rails server is one called WEBrick. You can alter this later, but I won't go into this now.
All you need to know is that if you're able to successfully boot your server, it is good news, and you'll be able to access it at http://localhost:3000; we use http://lvh.me:3000 which does the same thing.
Once you get to this point, you'll be able to do some programming:
MVC
Rails is made up of 3 components - models, views, controllers (MVC):
MVC is nothing new; tons of other frameworks use it. Since many people enter programming through Rails, they attribute the pattern to this framework, although that's incorrect.
The MVC pattern is very simple (once you understand it):
User browses to your url
Request is sent to your server
Server software passes request to Rails
Rails "middleware" stack handles request, sends to appropriate controller
Controller pulls data from Model (which loads data from the db)
Controller inserts data into view and renders view as HTML, with layout
Controller passes rendered HTML back to web server, which sends to browser
User sees dynamically updated web page
This means if you want to have a simple app, you need to at least have a model, views and controller.
To do this, browse to your Rails application directory (the one you cd'd into at the beginning). Each file below is one you should edit (we use SublimeText):
#config/routes.rb
root "posts#index"
resources :posts
#app/controllers/posts_controller.rb (you have to create this)
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
#posts = Post.all
end
def new
#post = Post.new
end
def create
#post = Post.new post_params
#post.save
redirect_to #post
end
def edit
end
def show
end
def update
redirect_to #post if #post.update
end
def destroy
redirect_to posts_path if #post.destroy
end
private
def post_params
params.require(:post).permit(:title, :body)
end
def set_post
#post = Post.find params[:id]
end
end
This will then mean you have to create certain views:
#app/views/posts/index.html.erb
<% #posts.each do |post| %>
<%= link_to post.title, post %>
<% end %>
<%= link_to "New Post", new_posts_path #-> will have to check the route %>
#app/views/posts/new.html.erb
<%= render "form", locals: {post: #post} %>
#app/views/posts/edit.html.erb
<%= render "form", locals: {post: #post} %>
<%= link_to "Destroy Post", post, method: :delete %>
#app/views/posts/_form.html.erb
<%= form_for post do |f| %>
<%= f.text_field :title %>
<%= f.text_field :body %>
<%= f.submit %>
<% end %>
--
Finally, you should then populate the data model. To do this, you need to make sure you have your database infrastructure set up; if this is in place, stop your Rails server by pressing crtl+c in cmd, then type:
$ rails g migration CreatePostsTable
A file will be created at:
#db/migrate/_____.rb
class CreatePostsTable < ActiveRecord::Migration
def change
#### You'll have to add this part ###
create_table :posts do |t|
t.string :title
t.string :body
t.timestamps
end
end
end
After that, go back to your cmd and type: rake db:migrate.
If your database is set up correctly, this should create a new posts table for Rails to interact with. Then, you just need a Model to work with it:
#app/models/post.rb ##-> you'll have to create this
class Post < ActiveRecord::Base
end
Once that's done, fire up your Rails server again (rails s in cmd), and access the following:
http://lvh.me:3000
It should show you a single button saying "New Post". If you press it, type out a post and it should appear, if all works.
Google search query "rails tutorial" gives that as the first link, and it is (subjectively) the best one: https://www.railstutorial.org/book. So if you really want to learn rails, go through it.

Devise CanCan Roles and Profile

I am trying to create profile pages for my community site. I have followed video tutorials and read docs on github for both Devise gem and CanCan gem. I have installed and currently have a functioning authentication system thanks to these two gems and the tutorials at railscasts.
I am very new to ruby and rails so everything is still very literal. My first question relates to a line of code from CanCan wiki page
<!-- in users/_form.html.erb -->
<%= f.collection_select :role, User::ROLES, :to_s, :humanize %>
I do not see a users folder or this controller. Is this something I can generate - for example I ran
rails g devise User
Could I also run:
rails g controller Users
I have seen this question here but do not quite understand the answer. Will I get an error by generating the "Users" controller to handle the things I would like to do?
I generated the devise views, but don't see any controllers - I understand that these could be overwritten - although I dont quite understand how this would work. If I overwrite than would all default devise controller functionality still work plus overwritten controller?
If I can generate the "Users" controller, I assume I could just put a view template into that location for all of the profile view information. I apologize for the amount of questions and length of this post, but I think with a little help I could be off and running again. Thanks for any information provided.
Alright so I solved this! I will post my solution for anyone with a similar question who could potentially benefit.
One of my questions was:
Could I also run:
rails g controller Users
Yes this is what I did. I use nifty scaffold generators to generate the views so this command would actually look like the following
rails g nifty:scaffold user
It is important to note that I DID NOT pass any variables after user. Devise has already created Users table in the database. This would create a conflict. Rails thinks you would like to overwrite your original database - which you do not want to do.
Do this builds the correct structure for User CRUD. Next open your config/routes.rb file.
Using nifty generators add the resources :users to the top of this file - move this below the devise resource and prefix the path as described on this devise wiki page to resemble the code below.
devise_for :users, :path_prefix => 'd'
resources :users
This is very important to remove any conflicts with your User controller and the devise controllers url paths by adding the "/d/" prefix to all devise controllers.
As well as adding the following code to you users_controller update method:
if params[:user][:password].blank?
params[:user].delete(:password)
params[:user].delete(:password_confirmation)
end
Which ensures devise will validate correctly.
Now comes the fun - register a user if you have not done so already. You now have a profile page for that user located at:
localhost:3000/users/1
localhost:3000/users/2
localhost:3000/users/3
...ect
You can edit user show.html.erb page in the views folder to change what information will display on each users profile page.
As for my question about Roles:
<!-- in users/_form.html.erb -->
<%= f.collection_select :role, User::ROLES, :to_s, :humanize %>
You now have access to this in the user controllers created by nifty-scaffold generator, so you can add this code to your form if you were also following Ryan Bates methods to integrate CanCan roles as described here.
Hopefully this help some else.

How to Add An Attribute By Default to All Formtastic Forms

I want to add :validate => true to every formtastic form in my Rails 3 app. I've looked over the code to Formtastic and don't see an obvious hook for that. Before forking it and writing the code myself, I wanted to see if anyone had already solved this problem.
Sorry to answer my own question but Justin French confirmed what I suspected. There is no current facility to do this in Formtastic. He suggested a wrapper, which I implemented as follows:
def validated_form_for(record_name_or_array, *args, &proc)
options = args.extract_options!
options.reverse_merge!({:validate => true})
semantic_form_for(record_name_or_array, options, &proc)
end
This handles the case where you want forms that are automatically client-side validated, but wish to be able to override it on a case by case basis.

active_scaffold routing error

If you haven't seen my question yesterday, this is my second rails app. The first went nice and smooth, but this one keeps giving me one random error after another. I installed active_scaffold for this app as well as the last app (the first error, instead of using script/install plugin git://active_scaffold repository, I did script/install plugin http://active_scaffold repository.) I didn't want to spell out basic CRUD on minor models. After the install problems, (before I found the http solution from a windows user when I'm on Linux) I thought I'd try out Hobo. Well, Hobo updated actionmailer, actionpack, activerecord, activeresource, and installed rack. Rails isn't even using the updated versions. But as you can see at the bottom of the trace it's using rack. I have a feeling it has something to do with my futzing around with installing Hobo which I uninstalled. Thanks in advance.
[Edit]
I had asked the question over at the
ActiveScaffold Group
the answer (if you don't want to follow the link) was that this line needed to be added to routes:
map.resources :modelName, :active_scaffold => true
It doesn't entirely answer my question, since the documentation said nothing about changing routes. But, it works.
[/Edit]
ActionController::RoutingError in Departments#index
Showing vendor/plugins/active_scaffold/frontends/default/views/_list_header.html.erb where line #8 raised:
No route matches {:_method=>:get, :action=>"show_search", :controller=>"departments"}
Extracted source (around line #8):
5: <% next if controller.respond_to? link.security_method and !controller.send(link.security_method) -%>
6: <% next if link.action == 'new' && params[:nested].nil? && active_scaffold_config.list.always_show_create %>
7: <% next if link.action == 'show_search' && active_scaffold_config.list.always_show_search %>
8: <%= render_action_link(link, new_params) -%>
9: <% end -%>
10:
11: <%= loading_indicator_tag(:action => :table) %>
Trace of template inclusion: vendor/plugins/active_scaffold/frontends/default/views/list.html.erb
Full Trace It was taking forever to format it. I'm still not fully conversant in SO's formatting (sometimes the server is down. reboots are reinstalls. it's a play server)
Add this to routes:
map.resources :modelName, :active_scaffold => true
And, contrary to my edit, it is in the documentation. It's in the wiki at Github. My second question at SO, and I could have found the answer by RTFM'ing. <sigh>
For Rails 4+ at least, your entry in config/routes.rb should look like:
resources :models do # my model name in plural
as_routes
# for action links of type member, add the following
# see also [note, via the action-link API, you can change the HTTP verb. Adjust this route accordingly.
# https://github.com/activescaffold/active_scaffold/wiki/Adding-custom-actions
# get :my_custom_action, :on => :member
end
Note, getting the right version of the Gem requires the following config in your Gemfile:
gem 'active_scaffold', github: 'activescaffold/active_scaffold', :branch => "3-4-stable"
If you get an error that "as_routes" isn't found; that'd be the problem.
THIS IS RAILS 4 ONLY
For Rails 5.x you can set route as follow:
resources :model, concerns: :active_scaffold

Resources