w2bro
w2bro

Reputation: 1016

Omniauth for provider authentication in Rails API

I've got omniauth working flawlessly for my rails app on the web. I've also created an API for our iPhone app to interact and I'm trying to get omniauth to work.

Is there a way to pass an access token (received from the integrated iOS integration with the Facebook.app) to omniauth to create the provider entry in the database?

Right now in my web app I have an authentications controller with the following code

  def create
    omniauth = request.env["omniauth.auth"]
    user = User.where("authentications.provider" => omniauth['provider'], "authentications.uid" => omniauth['uid']).first

    if user
      session[:user_id] = user.id
      flash[:notice] = t(:signed_in)
      redirect_to root_path
    elsif current_user
      user = User.find(current_user.id)
      user.apply_omniauth(omniauth)
      user.save
      flash[:notice] = t(:success)
      redirect_to root_path
    else
      session[:omniauth] = omniauth.except('extra')
      flash[:notice] = "user not found, please signup, or login. Authorization will be applied to new account"
      redirect_to register_path
    end
  end

Upvotes: 4

Views: 1955

Answers (1)

w2bro
w2bro

Reputation: 1016

In my user controller for the API I created the following:

  def create
    @user = User.new(params[:user])
    @user.save

    # Generate data for omni auth if they're a facebook user
    if params[:fb_access_token]
      graph = Koala::Facebook::API.new(params[:fb_access_token])
      profile = graph.get_object('me')

      @user['fb_id'] = profile['id']
      @user['fb_token'] = params[:fb_access_token]
      @user['gender'] = profile['gender']

      # Generate omnihash
      omnihash = Hash.new
      omnihash['provider'] = 'facebook'
      omnihash['uid'] = profile['id']

      omnihash['info'] = Hash.new
      omnihash['info']['nickname'] = profile['username']
      omnihash['info']['name'] = profile['name']
      omnihash['info']['email'] = profile['email']
      omnihash['info']['first_name'] = profile['first_name']
      omnihash['info']['last_name'] = profile['last_name']
      omnihash['info']['verified'] = profile['verified']

      omnihash['info']['urls'] = Hash.new
      omnihash['info']['urls']['Facebook'] = profile['link']

      omnihash['credentials'] = Hash.new
      omnihash['credentials']['token'] = params[:fb_access_token]

      omnihash['extra'] = Hash.new
      omnihash['extra']['raw_info'] = Hash.new

      puts omnihash

      # Save the new data
      @user.apply_omniauth(omnihash)
      @user.save
    end

Upvotes: 3

Related Questions