Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From Rails devise auth to backbone & api?

i want to rebuild an app which is a typical rails 3.2 mvc app into a API + Frontend (Backbone) only. As I have no experience in building APIs in rails including authenticatin:

  • What's the best way to authenticate with devise using backbone? Using auth_tokens?
  • How should I make he API? Just printing out JSON or use a gem like Grape?

thanks in advance!

like image 907
trnc Avatar asked Dec 27 '22 23:12

trnc


1 Answers

I can explain you the way i do this :

First, i install a standard rails application with devise. After that, i create my own session controller :

class SessionsController < ApplicationController

  def authenticate
    # this method logs you in and returns you a single_access_token token for authentication.
    @user = User.find_for_authentication(:email => params[:user][:email])

    if @user && @user.valid_password?(params[:user][:password])
      render :json => {:user => {:email => @user.email, :id => @user.id, :firsname => @user.firstname, :lastname => @user.lastname, :team_id => @user.team_id, :singleAccessToken => @user.generate_access_token}}
    else
      render :json => {:errors => ["Nom d'utilisateur ou mot de passe invalide"]}, :status => 401
    end
  end
end

As you can see, i send a request to this url with the json looking like :

{ 
   user => {
      email => "[email protected]",
      password => "monpass"
   }
} 

And my controller return me the json with user data if every thing is fine, or an error. On json with user, i return an access_token used on next requests to check that the user is allowed to request. I made this filters in my application controller :

class ApplicationController < ActionController::Base
  protect_from_forgery

  protected
  def user_access_token
    request.headers["HTTP_X_USER_ACCESS_TOKEN"] || request.headers["HTTP_USER_ACCESS_TOKEN"]
  end

  def current_user
    if token = user_access_token
      @user ||= User.find_by_access_token(token)
    end
  end

  def require_user
    unless current_user
      render :json => {:error => "Invalid Access Token"}, :status => 401
    end
  end

  def require_owner
    unless current_user && current_user == object.user
      render :json => {:error => "Unauthorized"}
    end
  end

end

As you can see, on each next request, i will add the access_token in html header on key : HTTP_USER_ACCESS_TOKEN

So, i can check if the user is allowed to make the request.

To make an API, you can use the Rails API gem as see here :

http://railscasts.com/episodes/348-the-rails-api-gem

Good luck.

like image 60
Sebastien Avatar answered Feb 06 '23 13:02

Sebastien