backbone.js - From Rails devise auth to backbone & api? -


i want rebuild app typical rails 3.2 mvc app api + frontend (backbone) only. have no experience in building apis in rails including authenticatin:

  • what's best way authenticate devise using backbone? using auth_tokens?
  • how should make api? printing out json or use gem grape?

thanks in advance!

i can explain way :

first, install standard rails application devise. after that, create own session controller :

class sessionscontroller < applicationcontroller    def authenticate     # method logs in , returns single_access_token token 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 can see, send request url json looking :

{     user => {       email => "myemail@toto.com",       password => "monpass"    } }  

and controller return me json user data if every thing fine, or error. on json user, return access_token used on next requests check user allowed request. made filters in 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 can see, on each next request, add access_token in html header on key : http_user_access_token

so, can check if user allowed make request.

to make api, can use rails api gem see here :

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

good luck.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -