Skip to content

Instantly share code, notes, and snippets.

@shlomizadok
Created May 19, 2012 10:37
Show Gist options
  • Save shlomizadok/2730414 to your computer and use it in GitHub Desktop.
Save shlomizadok/2730414 to your computer and use it in GitHub Desktop.
How to integrate Omniauth and API
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
@user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
if @user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
sign_in_and_redirect @user, :event => :authentication
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
namespace "api" do
resources :notebooks do
resources :lessons
end
end
## Facebook auth (via omniauth)
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
## API auth
devise_for :users, :controllers => {:sessions => 'api/sessions'}, :skip => [:sessions] do
match 'api/login' => 'api/sessions#create', :via => [:get, :post]
get 'api/logout' => 'api/sessions#destroy', :as => :destroy_user_session
end
# Devise auth
devise_for :users
class Api::SessionsController < Devise::SessionsController
include Devise::Controllers::InternalHelpers
before_filter :authenticate_user!, :except => [:create, :destroy]
before_filter :ensure_params_exist
respond_to :json
def create
user = warden.authenticate(:scope => :user)
if user
user.reset_authentication_token!
render :json => {:access_token => user.authentication_token, :token_type => "persistant", :name => user.name}, :callback => params[:callback]
else
render :json => {:error => "invalid_grant"}, :callback => params[:callback]
end
end
def destroy
resource = User.find_for_database_authentication(:email => params[:user_login][:email])
resource.authentication_token = nil
resource.save
render :json=> {:success=>true}
end
protected
def ensure_params_exist
return unless params[:user].blank?
render :json=>{:success=>false, :message=>"missing user_login parameter"}, :status=>422
end
def invalid_login_attempt
render :json=> {:success=>false, :message=>"Error with your login or password"}, :status=>401
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment