
Archive for the ‘rails’ Category
9 Things You Should Know About Ruby on Rails

Single Sign-On In Rails Application

- Distributed under MIT LIcense
- Active Development since
- External authentication sources (LDAP, SQL)
- Two-factor authentication
- Session-overview for logged-in users
- Full localization support
- REST-API
- user request to client domain .
- it redirects to the server if not authorised.
- Start with adding the gems client app
- redirects to back url to whichever client request url is
gem 'devise_cas_authenticatable', git: '<a href="https://github.com/jpamaya/devise_cas_authenticatable">https://github.com/jpamaya/devise_cas_authenticatable</a>'routes.rb
devise_for :users, skip: [:sessions], controllers: { cas_sessions: 'sso_cas' } devise_scope :user do get "sign_in", to: "devise/cas_sessions#new" delete "sign_out", to: "devise/cas_sessions#destroy" enddevise.rb # ==> Configuration for SSO server authentication
config.cas_base_url = "http://localhost:4000/" config.cas_create_user = false config.cas_destination_logout_param_name = 'service' config.cas_enable_single_sign_out = trueUser.rb
devise :cas_authenticatableNow run client application on localhost:3000 and begin with typing users/sign_in Since we overwrote devise’s sign in mechanism, so instead of presenting devise’s normal sign in page, we are redirected to localhost:4000 which is the backend app to authenticate the users. Lets prepare the backend app to authenticate the users. Step #2 Start with implementing code in server app limitation use ruby ruby “2.1.5” and rails “3.2.11” check rails -v ‘~>(‘ 3.2.11’). for server app Gemfile #It users these db to store sessions and some tokens. casino will take care all about these
gem 'sqlite3' # for sqlite support gem 'mysql2' # for mysql support gem 'pg' # for postgresql support gem 'casino'Run bundle install and rails g casino:install The CAS configuration is stored under config/cas.yml. This is where you configure how your SSO handles logins. An example configuration can be found in the file config/cas.yml.example provide the valid db credentials and run the migrations. Run this app on localhost:4000 , Just follow the old steps
- Goto localhost:3000/users/sign_in
- You will redirected to localhost:4000 enter credentials click sign in
- You will be redirected back on successful login
Server exampleruby “2.1.5”git clone https://github.com/codescrum/casino-sso-server-example.gitRails 4 client examplegit clone https://github.com/codescrum/casino-sso-client-rails4-example.gitRails 3 client example git clone https://github.com/codescrum/casino-sso-client-rails3-example.git |
A Step by Step Guide to Setup Rails application on Ec2 instance (Ubuntu Server)
-
Rails applications are a little bit different to install on servers but the process is very easy.Rails application needs a web server and an application server to run with. For development, it comes with default Webrick server that serve as application server on local machine. For setting it up on production server, we have the following choices on Web and application servers :-
-
-
Web servers
-
Apache
-
Nginx
-
-
Application Servers
-
Passenger
-
Thin
-
Puma
-
Unicorn
-
-
-
The simplest and best combination consists of Nginx + Passenger. It allows greater flexibility for configuration and also allows good speed over other combinations. So we are going to setup an Rails application using Nginx + passenger configuration on a bare Ubuntu server. Here are the steps :-
-
Launch an Ec2 instance with ubuntu AMI. Make sure you have HTTP and SSH access to the server.
-
SSH into the server by using private key (.pem) used while launching the instance and install the available updates by running :-
sudo apt-get install updates
- Now you need to setup ruby on your server, so install the single user rvm ruby by following this blog.
-
Load the rvm and make the installed ruby as default by running the following commands :-
source ~/.rvm/scripts/rvm
rvm use 2.1.0 –default
-
Install the version control to clone your rails application to server. We generally use Git with rails application which can be installed by running the following command :-
sudo apt-get install git
-
Now clone your application on the server :-
git clone yourepo.git
Note:- In case of private git repository, you need to add public key of server to deploy keys of your repository, otherwise you will be promped with an permission denied error.
OR
Deploy using application to this server using Capistrano script. Please read this blog for more details on deploying your application using Capistrano.
-
Now go to your application and install the gems by running bundle install command. If you want to setup your database on the same server, you can do the same by using the following commands 😐
-
In case of MYSQL
sudo apt-get install mysql-server mysql-client
sudo apt-get install libmysql++-dev
-
In case of POSTGRESQL, follow this blog for installation and then install the development headers
sudo apt-get install libpq-dev
After setting this up, migrate your databases in whichever environment you want to launch the server.
-
- Now install the Passenger gem by running :-
gem install passenger
-
Next step is to install the Nginx server, but we have some pre-requisits for this.
-
It needs curl development headers which can be installed by :-
sudo apt-get install libcurl4-openssl-dev
-
It will be installed under /opt directory and your user should have permissions to that folder, so make your user as user owner for /opt directory by :-
sudo chown -R ubuntu /opt
-
-
Now install the Nginx server with passenger extension by running the following command :-
passenger-install-nginx-module
-
Set your Nginx server as service in init script by using the following commands :-
wget -O init-deb.sh
http://library.linode.com/assets/660-init-deb.sh
sudo mv init-deb.sh /etc/init.d/nginx
sudo chmod +x /etc/init.d/nginx
sudo /usr/sbin/update-rc.d -f nginx defaults
-
Setup your application path in the nginx configuration file i.e.
/opt/nginx/conf/nginx.conf.
server {
listen 80;
server_name localhost;
root /home/ubuntu/my_application/public #<-- be sure to point to 'public'
passenger_enabled on;
rails_env production;
}
-
Lastly start your server by running the following command :-
sudo service nginx start
Introduction to Cruisecontrolrb – An RoR Integration Server
./cruise add -uYou can alternatively add your project from UI as well by running the cuisecontrol application and by going to Add Project menu. Running Cruisecontrolrb After configuring your project, you can continue running it as rails app on port no 3000 or for a continuous monitoring you can start it on port 3333 by running the following command:-
./cruise startNow whenever any of the developer checks in something to the main repository, it will monitor the activity and start building the project by fetching the code from that main repository. Configuring Cruisecontrolrb Cruisecontrolrb provides a lot of configuration options to the developers. Along with the inbuilt options there are a plenty of opensource plugins available to use with cruisecontrolrb. An example configuration to notify the developers regarding build failed and build fixed, you can mention configure their email addresses in the ~/.cruise/site_config file on your server as following(supposing sendmail/smtp is already configured on server) :-
<em>project.email_notifier.emails = ['abc@xyz.com', 'xyz@abc.com']You can checkout more configuration options here. If you want to manually build the project, you can open UI on port 3333 and press the build now button. Already go to command line and type the following:-
./cruise buildAdditional functionality and Plugins Cruisecontrolrb provides a plethora of flexibility to build additional functionality and plugins. There are several complex and basic callbacks exposed to developers to achieve the functionality required including but not limited to:- polling_source_control no_new_revisions_detected new_revisions_detected build_requested queued timed_out build_initiated configuration_modified build_started build_finished build_broken build_fixed build_loop_failed sleeping Apart from that, its very easy to write a plugin in cruisecontrol.rb. All you need to do is just to create a simple file with the following format:-
class SamplePlugin < BuilderPlugin def build_finished(build) //you custom code //goes here end end Project.plugin :sample_pluginand save it in .cuise/builder_plugins folder. Enjoy the continuous integration on your latest RoR app !!
Paypal Integration with RoR application – Securing the transaction
mkdir certs cd certs openssl genrsa -out app_key.pem 1024 openssl req -new -key app_key.pem -x509 -days 365 -out app_cert.pemNow you have two files in certs directory. Login Merchant’s Account -> Options -> Encrypted Payment Settings -> Add -> browse and select app_cert.pem file -> Add. After you are done, you will see a column ‘Cert ID’ ,copy and paste (in some text file) the text under this column, its your paypal certificate id. We will use if in further steps. Select the added certificate (using radio buttton) and click Download button. Move the downloaded file to our certs directory created above. Modifying the application logic Now we need to modify the application logic to encrypt the parameters and propogate the neccessary certificate information to paypal to be able to decrypt the parameters at its end. In paypal_url method of app/models/product.rb, add :
cert_id => AppConfig.cert_id, after :notify_url => notify_url, replace :business => YOUR_MERCHANT_EMAIL with :business => AppConfig.paypal_email and replace 1="+" 2="values.to_query" 3="[/php" language="https://www.sandbox.paypal.com/cgi-bin/webscr?"]with
encrypt_for_paypal(values)24.Add following code to encrypt the information being sent to the paypal:
PAYPAL_CERT_PEM = File.read("#{Rails.root}/certs/paypal_cert.pem") APP_CERT_PEM = File.read("#{Rails.root}/certs/app_cert.pem") APP_KEY_PEM = File.read("#{Rails.root}/certs/app_key.pem") # openssl encryption. def encrypt_for_paypal(values) signed = OpenSSL::PKCS7::sign(OpenSSL::X509::Certificate.new(APP_CERT_PEM), OpenSSL::PKey::RSA.new(APP_KEY_PEM, ''), values.map { |k, v| "#{k}=#{v}" }.join("\n"), [], OpenSSL::PKCS7::BINARY) OpenSSL::PKCS7::encrypt([OpenSSL::X509::Certificate.new(PAYPAL_CERT_PEM)], signed.to_der, OpenSSL::Cipher::Cipher::new("DES3"), OpenSSL::PKCS7::BINARY).to_s.gsub("\n", "") endSet the following values in your configuration file.
development: paypal_url: "https://www.sandbox.paypal.com/cgi-bin/webscr" paypal_email: YOUR_MERCHANT_EMAIL cert_id: PAYPAL_CERT_ID production: paypal_url: "https://www.paypal.com/cgi-bin/webscr" paypal_email: YOUR_MERCHANT_EMAIL cert_id: PAYPAL_CERT_IDNote:PAYPAL_CERT_ID is the certificate id that is saved above. In app/views/products/index.html.erb, replace
product.paypal_url(products_url)with
product.paypal_url(products_url, notification_products_url)Login to merchant account -> Profile -> Website Payment Preferences -> Select ‘ON’ radio button under heading ‘Encrypted Website Payments’ -> Save. It will block non-encrypted websites to make payments. That’s it. You are now sending encrypted parameters to paypal. Troubleshooting: uninitialized constant AppConfig : Please use whatever protocol you use to load environment specific configuration settings.
Basic Paypal integration with RoR application
Paypal is now a widely accepted payment gateway by the developer community due to its global acceptability and ease of integration with all types of web applications. Here in this blog, we will learn to integrate Paypal Standard with Ruby on Rails(RoR) 3 application.
Sign up for Paypal sandbox account Paypal Sandbox lets you test your Paypal integration without actually charging your credit card or your paypal account. Sandbox is very handy tool to have while your application is in development mode. You can sign up for Paypal Sandbox here. Create Sandbox accounts We will need to create a seller and a buyer account on paypal sandbox for proper testing of payments. When you login to Paypal sandbox, you will see the following options to create accounts:- Create a preconfigured account and
- Create an account manually.
$rails generate scaffold product name: string unit_price: decimalMigrate the changes to database
$ rake db:migrateSet root for the application
root :to => 'products#index'Start rails server ($ rails server) and add some products using link “New Product”. Add a link to buy now in your views(app/views/products/index.html.erb for this example), add following code for every products record We need to define the paypal_url for each product to be sold to communicate appropriate data to paypal. The function defines the various parameters for the paypal and returns them in the form of Query String. More details about these query string parameters can be found on the paypal developer website. In app/models/product.rb
# This defines the paypal url for a given product sale def paypal_url(return_url) values = { :business => YOUR_MERCHANT_EMAIL, :cmd => '_cart', :upload => 1, :return => return_url, :invoice => UNIQUE_INTEGER } values.merge!({ "amount_1" => unit_price, "item_name_1" => name, "item_number_1" => id, "quantity_1" => '1' }) # This is a paypal sandbox url and should be changed for production. # Better define this url in the application configuration setting on environment # basis. "https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query endSome notes about the parameters to be sent to Paypal:
- : Invoice should be unique every time you make transaction.
- : Cmd i.e. ‘_cart’ specifies that it’s for shopping cart purchases.
- : upload = ‘1’ allows third party carts.
"https://www.paypal.com/cgi-bin/webscr?" + values.to_queryFor actual payments you need merchant account on PayPal. 13.In app/controllers/products_controller.rb, add following code:
flash[:notice] = "Your Transaction is #{params[:st]} for amount of $#{params[:amt]}. Thank You for shopping." if params[:st]That’s it!! Now start rails server and click on “Buy Now” link. It will land you to paypal’s payment page. Enter your buyer test account credentials and click login. Now you will see a page with some details, check them and click Pay Now. It will make transaction and will redirect you to return_url you sent from paypal_url method. Notes You will need to enable PAYMENT DATA TRANSFER in the merchant account. To do so, Login to merchant account -> Profile -> Website Payment Preferences -> Find radio buttons under PAYMENT DATA TRANSFER and set it to ON. -> Click on Save. References
- Paypal Standard Integration Guide : https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_html_wp_standard_overview
- HTML Variables for Paypal Standard Integration: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_Appx_websitestandard_htmlvariables
Setting up single user rvm on ubuntu
- Please ensure that you have curl installed on your system. If not, then its as simple as:
sudo apt-get install curl
- Follow the single user installation instructions given on the rvm site to install rvm onto your system. You will find the instructions here.
- After you are done with the single user installation, on your shell prompt, type
type rvm | head -1
- If you get the following output, then rvm is correctly installed on your system. You can stop reading here and enjoy the magic of rvm on your ubuntu box .. 🙂
rvm is a function
- If you dont get the above output, then we need to perform following additional tasks on your ubuntu box to configure and use rvm properly on your system.
- Go to your user’s home directory and open up .profile in your favorite editor such as vi/gedit and add the following lines to the end of file(This basically tells the shell to check if the rvm script exists at the default rvm script location($HOME/.rvm/scripts), and if it exists then executes all the commands in that rvm script files):
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function
- The next step is to load the rvm for both interactive and non-interactive shells. This is the step which is missed by most of the beginners and major cause of lot of frustration around troubleshooting the rvm install. Find the following lines in ~/.bashrc file of yours:
# if you see '[ -z "$PS1" ] && return' then you must change this line to: if [[ -n "$PS1" ]] ; then ... original content that was below the && return line ... fi # <= be sure to close the if. #EOF .bashrc Even if you use zsh you should still adjust the .bashrc as above.
- And that should be it. The command type rvm | head -l should work perfectly fine now.
Enjoy Multiple ruby and gem versions !!
Authorize.net and its Integration in Rails 3.x Application – Part 1
Authorize.Net is a payment gateway that enables merchants to accept credit card and electronic check payments via Web sites, retail stores, mail order/telephone order (MOTO) call centers and mobile devices. In other words, Authorize.Net enables the traditional credit card swipe machine you find in the physical retail world on the web.
Recently, we had an implementation where we had to integrate Authorize.net with a Rails 3.x application. The integration is a cake walk and is very easy for even the novice programmers to follow:
1. The first thing we need is a developer account on Authorize.net. Sign up for test account to get API Login ID and Transaction Key. You can sign up from here. Enter you details and select “Card Not Present” as Account Type. Click submit.
2. After successful sign up, you will get a welcome email from authorize.net developer center which contains some test credit cards numbers.
3. Now simply log in to the Merchant Interface and click “Account.” Then click “API Login ID and Transaction Key.” Your API Login ID will be displayed. For security reasons, you cannot view your Transaction Key. Instead, you must generate a new one. To do this you will need the Secret Answer to the system-generated Secret Question, which is “Simon”.
4. There are 3 major ways to implement authorize.net in your application:
- Server Integration Method (SIM)
- Direct Post Method (DPM) and
- Advanced Integration Method (AIM)
In this particular blog post, I am going to discuss Server Integration Method (SIM). There are two main features of this method:
- Provides a customizable, secure hosted payment form.
- Authorize.Net handles all the steps in the secure transaction process.
- We will use authorize-net gem for this particular case. To integrate SIM in your rails application, open the file “Gemfile” in the root directory of your new rails application and add the following line to the end of the file:
gem 'authorize-net'
and run “bundle install” command from console.
- Run the following command it will scaffold everything which we need for integration.
$ rails generate authorize_net:sim payments YOUR_API_LOGIN_ID YOUR_TRANSACTION_KEY YOUR_API_LOGIN_ID
- Open config/routes.rb and add the route to the method to claim the payments:
root :to => 'payments#payment'
- Now your application is ready to run. Start the server using following command:
$ rails server
You will see a page displaying total amount to be paid and a payment button. If you are facing some errors while starting server, refer to Troubleshoot section of the blog.
- Terminate the server and open app/views/payments/payment.erb. It will looks like:
</pre> <%= form_for :sim_transaction, :url => AuthorizeNet::SIM::Transaction::Gateway::TEST do |f| %> <%= sim_fields(@sim_transaction) %> <%= label_tag 'x_amount', "Total: #{number_to_currency(@amount)}" %> <br /> <%= f.submit 'Purchase'%> <% end %>
- Add following code after the label_tag:
</pre> <%= hidden_field_tag("x_invoice_num", UNIQUE_INVOICE_NUMBER, {:id => "x_invoice_num"}) %> <%= hidden_field_tag("x_cust_id", CUSTOMER_ID, {:id => "x_cust_id"}) %> <%= hidden_field_tag("x_email", EMAIL_ID, {:id => "x_email"}) %>
In above code you have to replace UNIQUE_INVOICE_NUMBER , CUSTOMER_ID, EMAIL_ID with some values or variables. Invoice number should be unique for every payment transaction.
- Open app/views/payments/thank_you.erb and add a link to root of your application.
</pre> <%= link_to "Home", root_path %> <pre>
5. Start your rails server and open the application on browser. Click the “Purchase” button and complete the payment form that appears on the hosted payment page.
6. Select “Visa” and enter any test credit card, any expiration date (MMYY) in the future (such as “1120”), and hit “Submit”.
7. That’s it!! The payment is completed and the user will be redirected to thank you page.
Please feel free to drop a comment in case you have any queries.
Troubleshooting:
- uninitialized constant RAILS_ROOT: Open config/initializers/authorize_net.rb and replace RAILS_ROOT with Rails.root
- uninitialized constant RAILS_ENV: Open config/initializers/authorize_net.rb and replace RAILS_ENV with Rails.env
Source Code : The source code for this blog can be found at github.
Installing redmine on a shared host(Bluehost/Dreamhost/Apthost/Hostgator etc)
- Ensure that you have the ssh access to your server. If you dont have currently, then please apply for ssh access to your host.
- Once you have ssh access. Login into server via ssh.
- Please check the ruby and the rails version on your host and download the appropriate redmine source code from http://www.redmine.org/projects/redmine/wiki/Download
- Extract redmine to the target folder. For the ease of this guide, we assume that redmine was extracted to ~/redmine.
- Create a database using mysql on your server(most probably using cpanel) and add appropriate database settings to the rails config/database.yml.
- Install the gems required by redmine using rake gems:install. The command will install gems onto your user home directory and you might need to add the gem path to your .bash_profile.
- If your .bash_profile does not contain the following directives, please add them to it:
- export GEM_PATH=/usr/lib/ruby/gems/1.8:~/ruby/gems export GEM_HOME=~/ruby/gems (here ~/ruby/gems is the path where local gems are usually installed)
- Redmine stores session data in cookies by default, which requires a secret to be generated. So we need to generate session store secret. Under the application main directory run: rake generate_session_store
- Create the database structure by running the redmine migrations: RAILS_ENV=production rake db:migrate
- Migrations will create all the tables and an administrator account with admin/admin as username/password.
- The user who runs Redmine must have write permission on the following subdirectories: files, log, tmp & public/plugin_assets:- chown -R user:group files log tmp public/plugin_assets chmod -R 755 files log tmp public/plugin_assets
- Redmine comes with a prebuilt dispatcher and .htaccess files. Rename the .example dispatcher files to their respective extensions. Similarly rename the example .htaccess to .htaccess
- Test the installation by running the WEBrick web server. Under the main application directory run: ruby script/server -e production
- If there is no error in step 14, then the redmine is all set and now you should move ahead to configure apache to serve the redmine. Otherwise, please move back and check the errors.
- We will install redmine on a subdomain in this guide since most of the shared hosts support subdomaining.
- Create a subdomain using cpanel’s subdomain management option. Give it some path in the apache directory. Normally ~/public_html. Lets say the path is ~/public_html/redmine and the subdomain is redmine.tld.com for the purpose of this guide.
- Now move to shell again and make a symbolic link in ~/public_html/redmine to your redmine install’s public directory (~/redmine) in this case. This command will create a symbolic link : ln -s ~/redmine/public ~/public_html/redmine
- Add the local gem path in your config/environment.rb file , ENV[‘GEM_PATH’]=’/home/username/ruby/gems:/usr/lib/ruby/gems/1.8′
- Run the application by entering your application’s url in browser and your shiny new redmine install should be there.
uninitialized constant Delayed::Job in rails 2
uninitialized constant Delayed::JobThen you need to add the following to config/initializers/delayed_job.rb
Delayed::Worker.backend = :active_recordThis will remove the error and you will now be able to work with delayed job in your rails application. Enjoy the sweetness of backgrounded jobs.
Join Us