Skip to content

Instantly share code, notes, and snippets.

@A1iAshoor
Created August 24, 2015 22:59
Show Gist options
  • Save A1iAshoor/d666296a970c65e47187 to your computer and use it in GitHub Desktop.
Save A1iAshoor/d666296a970c65e47187 to your computer and use it in GitHub Desktop.
Rails + Devise + Facebook Login API + iOS Facebook SDK | Controller
class Api::V1::OmniauthController < ApplicationController
skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }
before_filter :authenticate_user!, :except => [:create, :failure]
def new
end
def create
params[:access_token] = decrypt(params[:access_token])
auth_access_token = params[:access_token]
@graph = Koala::Facebook::API.new(auth_access_token, ENV['FB_APP_SECRET'])
profile = @graph.get_object('me')
@auth = Authentication.find_by_provider_and_uid(params[:provider], profile['id'])
if @auth
user = User.find_for_database_authentication :email => profile['email']
return invalid_login_attempt unless user
sign_in(:user, user)
render :status => 200,
:json => { :success => true,
:info => "You've logged in.",
:data => { :user_email => encrypt(user.email),
:auth_token => encrypt(user.authentication_token) } }
else
user = User.find_for_database_authentication :email => profile['email']
unless user
user = User.new :email => profile['email']
user.generate_password!
end
user.authentications.build :provider => params[:provider], :uid => profile['id']
user.save
sign_in(:user, user)
render :status => 200,
:json => { :success => true,
:info => "You've signed up.",
:data => { :user_email => encrypt(user.email.to_s),
:auth_token => encrypt(user.authentication_token.to_s) } }
end
end
protected
def invalid_login_attempt
render :status => 401,
:json => { :success => false,
:message => 'Error with your login or password'}
end
def failure
render :status => 401,
:json => { :success => false,
:info => 'Login Failed',
:data => {} }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment