2013-05-07 21 views
0

在我的项目上,devise为管理面板提供用户注册/身份验证。我需要添加API方法,它将sign_in用户并返回JSON状态+会话cookie。Rails使用定期授权和API设计

的routes.rb

devise_for :user, :controllers => {sessions: 'sessions'} 

会话控制器

class SessionsController < Devise::SessionsController 
    skip_before_filter :verify_authenticity_token 

    def create 
    resource = warden.authenticate!(:scrope => resource_name, :recall => "#{controller_path}#failure") 
    sign_in(resource_name, resource) 

    respond_to do |format| 
     format.html { respond_with resource, :location => after_sign_in_path_for(resource) } 
     format.json { render json: {:success => 1}} 
    end 
    end 

如果我将发布数据到用户/ sign_in.json,它将使{ “成功”:1}这正是我需要。

但问题是如何移动user/sign_in.json上的一些自定义url,如/ api/sign_in?

回答

0

环绕在一个命名空间的路线:

namespace :api do 
    devise_for :user, :controllers => {sessions: 'sessions'} 
end 
+0

这将在里面创建所有设计路线:api namespace/api/user /。 我只需要1个方法/ api/sign_in – 2013-05-08 08:13:07

+0

@RuslanSavenok你可以使用'skip'来只使用你想要的某些:'skip:[:registrations,:unlocks,:passwords,:confirmations]' – 2013-05-08 16:04:23

+0

用这种方法我仍然会有2条我不需要的路线。 获取/ sign_in /呈现登录表单 获取/ sign_out /注销用户 添加了我的解决方案。 – 2013-05-09 10:22:20

0

难道会这样:

api_controller.rb

def create_session 
    resource = User.find_for_database_authentication(:email => params[:user][:email]) 

    if resource.nil? 
     render :json=> {:success => 0, :error => "No Such User"}, :status=>401 
    else 
     if resource.valid_password?(params[:user][:password]) 
     sign_in(:user, resource) 
     render :json=> {:success => 1} 
     else 
     render :json=> {:success => 0, :error => "Wrong Password"}, :status=>401 
     end 
    end 
    end 

的routes.rb

namespace :api do 
    namespace :v1 do 
     get :sign_in, :to => 'api#create_session' 
    end 
    end