How to send Basic Authentication (BA) credentials in ruby on rails

HTTP Basic authentication is a simple authentication scheme in which user authentication is done by a username and password eliminating the needs of cookies, sessions and login pages. It is base64 encoded.

Rails provides a method for this type of authentication: authenticate_with_http_basic

This method can be used as follows:

authenticate_with_http_basic do |username, password|
  ——
end

Inside the block you can access the username and password.

But how to send a request with basic auth in rails ?

This is really tricky and I didn’t find any documentation for this. Here I am describing how to send a request with basic auth.

1. Use Faraday library (Faraday is an HTTP client lib)
https://github.com/lostisland/faraday

Create a connection:

connection = Faraday.new(:url => HOST) do |faraday|
      faraday.request  :url_encoded             # form-encode POST params
      faraday.response :logger                  # log requests to STDOUT
      faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
      faraday.basic_auth(USERNAME, PASSWORD)
end

parameters = params[‘user’].permit!.to_h

response = connection.get do |req|
      req.url(params[:url])
      req.headers['Content-Type'] = 'application/json'
      req.params.merge!(parameters)
end

response = connection.post do |req|
        req.url(params[:url])
        req.headers['Content-Type'] = 'application/json'
        req.body = parameters
end

render json: response.body

Here,

HOST = 'http://lvh.me:3002'
USERNAME = 'EdcddzrbmET55016'
PASSWORD = 'UXBJnS309S49st3rHqmH5934'
params['url'] = '/users/profile'

We can use Faraday’s (‘faraday.basic_auth’) basic auth method to reach out our solution.

If you are getting any error like follows in post request

NoMethodError (undefined method `bytesize' for {}:ActiveSupport::HashWithIndifferentAccess):

Don’t forget to convert the ruby hash ‘parameters’ to json by calling ‘to_json’ upon it.

        req.body = parameters.to_json 

In Other way you can use something like this to generate the basic auth header

request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(USERNAME, PASSWORD)

How to use Ruby Rest Client:

require 'rest_client'

headers = {
  :authorization => 'Basic FytxhZGKpbjpvcGVuIHNlc2FtHUHU'
}

response = RestClient.get 'https://yourdomain.com/api/users.json?activityId=02ddf868-6484-440f-8c39-c7d4fb4e7b33', headers
puts response
Advertisements

Rbenv: Start with new ruby and rails versions

Check for the new ruby and rails versions
https://www.ruby-lang.org/en/downloads/
https://rubygems.org/gems/rails/versions

Suppose we are going to install Ruby – 2.4.1 & Rails – 5.1.3

Get rbenv into action

1. $ rbenv install --list # Gets the list of ruby versions available

$ rbenv install 2.4.1

ruby-build: definition not found: 2.4.1

The following versions contain `2.4.1' in the name:
  rbx-2.4.1

See all available versions with `rbenv install --list'.

If the version you need is missing, try upgrading ruby-build:

  brew update && brew upgrade ruby-build

Oops..!

rbenv cannot find the version: 2.4.1

Upgrade ruby-build

Mac:

$ brew upgrade ruby-build --HEAD

Now install ruby 2.4.1

$ rbenv install 2.4.1

Create a new gemset:

$ rbenv gemset create 2.4.1 demo-app
That set up a directory for you in ~/.rbenv/versions/2.4.1/gemsets/demo-app

Set the ruby version to the newest

$ rbenv local 2.4.1

$ rbenv version
=> 2.4.1

    Activate New Gemset


For activating a gemset we need to create a .rbenv-gemsets file in the current directory.

$ touch .rbenv-gemsets
$ echo demo-app > .rbenv-gemsets

Check active gemset:

$ rbenv gemset active

Install Rails 5.1.3

$ gem install rails -v '5.1.3'
$ gem install --no-rdoc --no-ri rails -v '5.1.3' # skips the documentation

Later we can delete this .rbenv-gemsets file and add a new file named ‘.ruby-gemset’ in the rails project directory. I cannot see any other good way of doing this. If anybody know about some other good way of doing this please give a comment.

Create a New Rails app

$ rails new demo-app

$ rm .rbenv-gemsets

$ cd demo-app
$ touch .ruby-gemset
$ echo demo-app > .ruby-gemset
$ touch .ruby-version
$ echo 2.4.1 > .ruby-version
$ rails s
=> Booting Puma
=> Rails 5.1.3 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.9.1 (ruby 2.4.1-p111), codename: Private Caller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop

Goto http://localhost:3000/

rails-5-new.png

Done! Lets go…

Set up capistrano deployment for Ruby On Rails

STEP 1:
Install capistrano gem

group :test, :development do
  gem 'capistrano'
end

Install capistrano with rvm

gem 'rvm-capistrano'

STEP 2:
Prepare your Project for Capistrano
Capify your project. The following command initialise your project with Capistrano.

$ capify .

STEP 3:
Do proper modificatons in Capistrano Recipe (config/deploy.rb)
http://guides.beanstalkapp.com/deployments/deploy-with-capistrano.html

Lets do the deployment for staging environment.
Create a ruby file under config/deploy/ folder named staging.rb
Copy the following content

set :domain, "mydomain.in"
role :app, domain
role :web, domain
role :db, domain, :primary => true
role :resque_worker, domain   # if you are using workers in your project, set role for them if needed
role :resque_scheduler, domain # if you are using workers in your project

set :deploy_to, "/home/my_deploy_path/"  # the deployment directory
set :environment, "staging"
set :rails_env, "staging"
set :branch, "staging"
set :previous_environment, "develop"

STEP 4:
Setup capistrano in deployment server

$ cap staging deploy:setup

This will Create folder structure that capistrano uses in the process.

Make sure that everything is set up correctly on the server by the command

$ cap staging deploy:check

Now you can see a message like:
“You appear to have all necessary dependencies installed”

Create shared/config folder in your deploy_to path
and copy database.yml and other config files as you written in the symlink_shared task in cap recipie (if any)

STEP 5:
Deploy your project:

cap staging deploy

How to implement a simple captcha in Rails using gem ‘simple_captcha’

Here it is, a simple captcha for Rails applications.

To set up, add the following line to your Gemfile

gem "galetahub-simple_captcha", :require => "simple_captcha"

Run rails generator

rails generate simple_captcha

Do db Migration

rake db:migrate -t

In your view file add

%= show_simple_captcha %

Add the following in yml file
en.yml:

en:
  simple_captcha:
    label: "Enter the above code"
    placeholder: "Enter here"

In controller just include captcha helpers module

class ApplicationController < ActionController::Base
  include SimpleCaptcha::ControllerHelpers
end

Use this code in the controller for the captcha validation

if simple_captcha_valid?
  do this
else
  do that
end