Friday, 17 March 2017

WebRTC Opentok in Ruby On Rails for Text chat


This post will take you through adding text chat functionality using Opentok (a WebRTC platform) in Ruby on Rails. OpenTok is a WebRTC platform for embedding live video, voice, and messaging into your websites and mobile apps. Opentok has its own signalling server. We will be using the OpenTok signaling API.
First, we will make the basic setup for using Opentok service. Here we will be using ‘opentok’ ruby gem.

1) Add opentok gem to your Gemfile.

gem ‘opentok’

2) Then create a session that will attempt to transmit streams directly between clients.

Store session id and token somewhere in the database, so that you can use it later on.
Here token gets expired in 30 days(default value). You will need to regenerate after 30 days.

3) Now it’s time to connect to session that we have created above, Add this to your HTML page,

A signal is sent using the signal() method of the Session object. One can receive a signal by listening to a signal event dispatched by session object.
So, All clients who are connected to the same session and listening to same signal type(‘text_chat’ here) will receive a message as soon as someone publishes to channel ‘text_chat’.

Thursday, 16 June 2016

Google Big query API integration in Ruby

Recently, I worked on Google Big query integration. I found it bit difficult get it working quickly to make all setup for integrating Google API since documentation is also bit verbose. So, I would like to share that with you all. This post will take you through integrating Google Big query integration in Ruby application.

First you will need to enable API in google compute console, then generate secret key if you haven't.
Here is google big query API service that I have written. Currently, It only has API integrated for fetching data from google big query.

Then call it with,
big_query_service = GoogleBigQueryService.new(query)
big_query_service.execute_query

Here is more info about Big Query API,  https://developers.google.com/apis-explorer/#p/bigquery/v2/

One can also use command-line tool, https://cloud.google.com/compute/docs/gcloud-compute/
Though CLI tool gives you data in required format unlike in APIs it returns data in bit confused format but it's also not intended to be an API, since formatting and output are subject to change.

Wednesday, 11 March 2015

Simple Captcha in Ruby On Rails

When your application has a form that's available to everyone for eg. Contact us, you will be spammed! So what can we do about it? Well, one option is to have all forms secured by authentication... OR we can use a captcha. So, Here is how you can implement your own simple captcha in Ruby on Rails,

First of all we will create Captcha class in lib folder,


Here we are dumping the variables into a string using YAML and then encrypt/decrypt.

Then in your Controller,

class ContactsController < ApplicationController

  def new
    @captcha = Captcha.new
  end

  def create
    @captcha = Captcha.decrypt(params[:captcha_secret])

    unless @captcha.correct?(params[:captcha])
      flash.now[:alert] = "Please make sure you entered correct value for captcha."
      # Here we need to initialize @captcha with new object in order to show 
      # different captcha each time on form 
      @captcha = Captcha.new
      render :new
    else
      ContactsMailer.notify(contact).deliver
      flash[:notice] = "Your message has been sent successfully"
      redirect_to root_path
    end
  end
end

 In your view,

<div class="field">
  <%= hidden_field_tag :captcha_secret, @captcha.encrypt %>
  <%= label_tag :captcha, @captcha.question %>
  <%= text_field_tag :captcha, "" %>
</div>

That's it. And it will look similar to this,




Wednesday, 4 June 2014

Client side SSL Certificate Authentication with Rails and Nginx

Hi,
     Recently i worked on one application which required SSL client certificate based authentication.
So just wanted to share it with you all about how it can be integrated in Rails application.This article is about using SSL certificates installed into a web browser to authenticate against a Ruby on Rails application with Nginx.

Steps for creating certificates,

1) First thing you will need is to configure openssl.cnf, check following gist for configuring your openssl.cnf , as its big file so cant embed here. https://gist.github.com/pandurang90/dbe6a67339747ef5bacf 
In this configuration important thing is setting path to CA dir,
[ CA_default ]
dir = /path/to/ca
this is the path where you are going create your CA.

2) Then you will need to create your own CA(Certificate Authority) that issues Digital certificates.
For that we will use CA.pl script is a perl script that supplies the relevant command line arguments to the openssl command for some common certificate operations. It is intended to simplify the process of certificate creation and management by the use of some simple options.
cd /path/to/ca
CA.pl -newca 
Make sure here you enter domain name in common name field when asked in this.

3) Now generate web server CSR
openssl req -new -nodes -keyout www.example.org.key -out www.example.org.csr
then self sign web server Certificate
openssl ca -config /etc/openssl.cnf -policy policy_anything -out www.example.org.crt -infiles www.example.org.csr
that gives you web server certificates

4) Now its time to configure nginx server,
 https://gist.github.com/pandurang90/8f0c11819db4c866d985

5) Generating Client certificate, 
CERT_DIR = "path/to/ca"
  user_name = "test user"
  id = 1

  def create_p12
    subj = "/C=US/ST=YourState/L=city/O=example/OU=example/CN=#{user_name})/emailAddress=#{email}"
    dir_name  = "#{CERT_DIR}#{id}"
    Dir.mkdir(dir_name) unless File.directory?(dir_name)
    create_cert(subj)
    sign_cert
    generate_p12
  end

  def create_cert(subj)
    system("openssl req -new -sha1 -newkey rsa:1024 -nodes -keyout #{CERT_DIR}#{id}/#{user_name}.key -out #{CERT_DIR}#{id}/#{user_name}.csr -subj '#{subj}'")
  end

  def sign_cert
    system("openssl ca -batch -config /usr/lib/ssl/openssl.cnf -policy policy_anything -extensions ssl_client -out #{CERT_DIR}#{id}/#{user_name}.crt -infiles #{CERT_DIR}#{id}/#{user_name}.csr")
  end

  def generate_p12
    system("openssl pkcs12 -export -clcerts -in #{CERT_DIR}#{id}/#{user_name}.crt -certfile #{CERT_DIR}demoCA/cacert.pem -inkey #{CERT_DIR}#{id}/#{user_name}.key -out #{CERT_DIR}#{id}/#{user_name}.p12 -name '#{name}' -passout pass:#{export_password} ")
  end
Here ,
subj = "/C=US/ST=YourState/L=city/O=example/OU=example/CN=#{user_name})/emailAddress=#{email}"
is a subject for certificate which can be unique for each user or same based on settings in your openssl.cnf.

6) Install your certificate on web browser(p12 file), then hit url of website and it will ask to submit client certificate , just select required certificate from list and submit. Then in your controller you can get certificate using,
cert = request.env["HTTP_X_SSL_CLIENT_S_DN"]
 as we have initialized variable in nginx configuration.
proxy_set_header X-SSL-Client-S-DN   $ssl_client_cert 
You can check more options on http://nginx.org/en/docs/http/ngx_http_ssl_module.html

7) You can verify whether certificate submitted by user is valid or not , using
request.env["HTTP-X-CLIENT-VERIFY"]
returns the result of client certificate verification: “SUCCESS”, “FAILED”, and “NONE” if a certificate was not present.







Wednesday, 22 January 2014

Transfer files over netcat using Applescript

Hi,
    At my workplace me and one of my colleague used to transfer files like database dumps etc. for projects from one machine to another.
I came across netcat (nc command) and when we tried that it just worked so quickly, i got surprised with the speed with which it got transferred. :)
So i wrote applescript that transfers file using netcat, with dialog boxes.

after saving(netcat.scpt) this file to your machine just type in your terminal
osascript your_path/netcat.scpt
It will simplify your work to transfer file rather than remembering syntax for netcat 
  OR 
if you want more shortcut to do this you can add it to .bash_profile file
alias netcat='osascript your_path/netcat.scpt'

and then just type netcat in terminal.. enjoy :)