Integrating Omniauth for Github

Hey!

A good news for you! Our Github Editor is on its  way! In Today’s post, I am going to discuss integrating omniauth for Github using Devise gem in Ruby On Rails.

Omniauth is basically a library that standardizes the authentication for our web application. You might have seen on the various application while you are log in there is a special feature which allows you to login in from Google or from Facebook or GitHub!. You don’t have to sign up again and again just click on it and log in from somewhere else.

So Here I am going to tell you about. How to integrate it in Ruby On Rails application.

Prerequisite,

Before moving on to Omni auth, You have to integrate Devise Authentication in your app

Simple Steps to integrate omniauth in Ruby On Rails app
First Step is to add gem in gemfile
gem 'omniauth-github'

Here we will use github but you can add omniauth for other apps also like facebook or google just replace github with any of this Stratergies

Next up, you should add the columns “provider” (string) and “uid” (string) to your User model.

rails g migration AddOmniauthToUsers provider:string uid:string
rake db:migrate

Next, Declare the provider in your

config/initializers/devise.rb:

config.omniauth :github, "APP_ID", "APP_SECRET", scope: 'user,public_repo

and replace APP_ID and APP_SECRET with your app id and secret.

You can generate App ID and secret from your Github account

After configuring your strategy, you need to make your model

app/models/user.rb

devise :omniauthable, :omniauth_providers => [:github]

Then add,

Then update your routes in config/routes.rb,
devise_for :users, :controllers => { :omniauth_callbacks =>"users/omniauth_callbacks" }

Now add the file

app/controllers/users/omniauth_callbacks_controller.rb:


class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
end

The callback should be implemented as an action with the same name as the provider like this,

class Users::OmniauthCallbacksController :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, :kind => "Github") if is_navigational_format?
else
session["devise.github_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end

def failure
redirect_to root_path
end
end

This action has a few aspects worth describing:

When a valid user is found, they can be signed in with one of two Devise methods: sign_in or sign_in_and_redirect. Passing :event => :authentication is optional. You should only do so if you wish to use Warden callbacks.

After the controller is defined, we need to implement the from_omniauth method in our model

app/models/user.rb

:

def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.name = auth.info.name # assuming the user model has a name
user.image = auth.info.image # assuming the user model has an image
# If you are using confirmable and the provider(s) you use validate emails,
# uncomment the line below to skip the confirmation emails.
# user.skip_confirmation!
end
end

This method tries to find an existing user by the provider and uid fields. If no user is found, a new one is created with a random password and some extra information.

Notice that Devise’s RegistrationsController by default calls User.new_with_session before building a resource. This means that, if we need to copy data from session whenever a user is initialized before sign up, we just need to implement new_with_session in our model. Here is an example that copies the github email if available

class User < ApplicationRecord
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
user.email = data["email"] if user.email.blank?
end
end
end
end

For more infor you can go to Documentation
 And here you are done. 🙂
Leave Comments if you are getting any trouble.
I am always ready for help!
Keep Rocking!

Ace Syntax Highlighter

Now I have configured Ace to work within my editor so It’s time to add the feature of Syntax Highlighter.

Generally, we’ll manually set mode to editor like

editor.mode(‘ace/mode/javascript’);

for this File extension must be known to us so that we can manually add mode but we don’t know the file extension before hand. so we have to use some intermediator which will tell the file extension.

Ace editor already have a built-in functionality

i.e modelist

now How we can use it?
1. Initialize modelist
var modelist = ace.require("ace/ext/modelist");
2. Get the mode for particular file
var mode = modelist.getModeForPath(path).mode;
3. Set the mode to editor
editor.session.setMode(mode);

That’s it, all this is done under javascript file.

 

Action Cable(Rails 5)

Action cables

Action cable is introduced in rails5. It uses for Real-time communication.
Now here we discuss how to configure action cables in your websites.

1. Setup Action cable connection
For this, Open app/channels/application_cables/connection.rb

Here we will define 2 methods

class Connection < ActionCable::Connection::Base
#Totally rely on siged in user
identified_by :current_user
def connect
self.current_user= find_current_user
end

def disconnect

end
def find_current_user
if current_user = User.find_by(id: cookies.signed[‘user.id’])
current_user
else
reject_unauthorized_connection
end
end

end
end

Here generally we find the current user from cookies of browser and get the user id

2. Authenticate the user on Web server

Open config/initializers/warden.rb

Warden::Manager.after_set_user do |user, auth, opts|
scope = opts[:scope]
auth.cookies.signed[“#{scope}.id”] = user.id
end

#Delete the cookies when user is signed out
Warden::Manager.before_logout do |user, auth, opts|
scope = opts[:scope]
auth.cookies.signed[“#{scope}.id”] = nil
end

this will perform 2 actions

First, this will set cookies for signed in user and then make it available for the user and secondly this will erase the cookies when user signed out

3. Acces Action cable server through rails server

For this, Open config/application.rb

and add a line under

Class Application <Rails::Application

i.e.

config.action_cable.mount_path=’/cable’

By default action cable works on mount under ‘/cables’

after that, we have to mount this /cable in routes.

4. Open Routes.rb

Add this line in the end

mount ActionCable.server => ‘/cable’

5. Create a messaging

After all this, We have to create a messaging channel.

Here, we are creating channel for comments.

Type

$rails generate channel comments

will create 3 files.

Screenshot from 2017-01-27 12-38-34.png

6. Open comments_channel.rb

Here uncomment the line written in subscribed method

def subscribed

stream_from “comments”

end

I created channel comments so I have replaced stream from comments.

7. Broadcast the comment

Open  comments_controller.rb

here add 2 lines under we save the comment

  if @comment.save

ActionCable.server.broadcast “comments”,
render(partial:’comments/comment’,object: @comment)

flash[:success] = “Comment has been created”

this code will generally  broadcast the comment and rendAer a partial named as comment

8. Create a partial for this

Open views/comments/_comment.html.erb

<%= comment.body %>
<%= time_ago_in_words(comment.created_at) %>
ago by <%= comment.user.email %>

and Add a line where you have created the form for controller

remote: true

like this

my comment form is present in show.html.erb

 <%= form_for [@article,@comment], remote: true, :html => {class: “form-horizontal”, role: “form”} do |f| %>

this will specify we are using Ajax

9.  Update comments.coffee file

open app/assests/javascripts/channels/comments.coffee

add a line

recieved: (data) ->

$(“#messages”).prepend(data)

this will call when there is an upcoming message on the web socket for this channel

in this make sure you have indented the line properly here indentation matters.

now check your app in the browser and if you have any problem leave a comment below.

Messaging Server

Messaging server is basically  a middleware program that handles messages that are sent for use by other programs using a messaging application program interface (API).

To install a messaging server we need a server as well as a client.

We have a lot of messaging servers present, based on XMP (Extensible Messaging Presence) Protocol like

  • Open Fire
  • Ejabbered
  • ichat server

and many more

Now we will install Open Fire messaging server.

Steps to install Open Fire server

  • $sudo apt-get update
  • Install java using
    $sudo apt-get install default-jre
  • Download Open Fire from here
  • install it using
     $dpkg -i openfire *.deb
  • Then open Localhost:9090 and configure it.

Starting and Stoping Of server

If you want to stop Openfire, you can do that using:

sudo /etc/init.d/openfire stop

To start it again, execute:

sudo /etc/init.d/openfire start

Congrats we installed the server.

Now we have to add users in it.

Add user in Open fire

Go to user/Group
and create a new user in it.

Screenshot from 2016-08-31 23-10-42

Like here we create a user name Mike.

Now we need a client where the user can Login.

XMPP provides various cross-platform clients.

XMPP Clients
You can Download clients from here
For example Lets Download a Client named as Spark.
Spark is a Cross-platform real-time collaboration client optimized for business and organizations.
Download Spark from here

Open the spark.
Enter the username which is created in open fire like we create mike.
and then enter the password
The Server name is your Domain name or your IP address where open fire is installed.

and Now Enjoy chatting. 😀

Rack offline

Let’s do some interesting stuff. Today we are going to offline the single page of a web application. For this, we will use Rack offline in Ruby on Rails version 4.

 

Installation and configuration

To install write

$gem install ‘rack-offline’

then open Gemfile and add

gem ‘rack-offline’

 

after that open config/routes.rb file and add

match “/application.manifest”=>Rails::Offline,:via=>[:get], :as=> :manifest

then open view/layouts/aaplication.html.erb

<html lang=’en’ manifest=’/fr/application.manifest’>

and then Run the server using

$rails server

and here’s you are done. 🙂 your web page will work offline.

Integrating VPL plugin in moodle

VPL plugin is used so that student can make and compile program online.

VPL stands for Virtual programming language. Generally, it is an activity module for Moodle that manage programming assignments.

Steps to install VPL Plugin

  • Download the plugin from here.
  • Extract the plugin in moodle/mod directory
  • Change the permission. by using$chmod -R 755 vpl or
    $chmod -R 777 vpl
  • Then open localhost/moodle in browser.
  • and go to dashbord>check for plugin dashboard.

That’s it your plugin is integrated with moodle.

This will give the output. But it is for a couple of days. We have to install Jail server which I will discuss in my next post.

Stay Awsome.

Any queries comment below. 🙂

 

Moodle.

Moodle sounds like doodle :p But no its totally different.

Modular Object-Oriented Dynamic Learning Environment abbreviated as Moodle is the learning platform based on strong pedagogical principles, providing a private learning space for you to design online courses with flexible content and collaborative activities so your students are constantly experiencing feedback.

Why Moodle?

More than 68 million users along the globe widely using Moodle as Learning Management System(LMS) Because of its 3 main features.

  1. Moodle is Open Source and Free
    Yeah! Moodle LMS itself is free as in terms of freedom and Cost. It is an open source software distributed under the GNU General Public License. In less technical terms, this means that users and organizations have the freedom to run, study, share, and modify the software to meet their unique needs.
  2. Moodle is supported by a global community
    One of the reasons why Moodle is the world’s best LMS is because it supported by a global community of developers. A large benefit of open-source software is that the code is open for scrutiny. This means that developers from all over the world can access the code, and modify it so that it is more secure.
    Also, there are 144 million forum posts and 72 million Moodle learning resources.
  3. Moodle is Configurable, Highly flexible and feature rich.
    With over 500 Moodle plugins developed by the global community, your learners, managers and administrators have the opportunity to flourish in an environment that makes learning collaborative, engaging and fun.

How to install Moodle?

  • Download latest version of Moodle from here
  • Extract it and place this directory into your server(/var/www/).
  • Open localhost/moodle from the browser and follow the steps.

That’s It!
Congratulation, You are done.
For more details click here.
Any queries? comment below