2014-01-15 89 views
1

我在Rails 3應用程序中使用Devise進行用戶認證。此應用程序還向移動應用程序提供API響應。我讀的設計消除了他們的令牌認證功能由於種種原因,我已經在我的應用程序在此基礎上依據實現它:https://gist.github.com/josevalim/fb706b1e933ef01e4fb6Devise令牌認證的API路由

class ApplicationController < ActionController::Base 
    protect_from_forgery 

    # before_filter :authenticate_user_from_token! 
    before_filter :authenticate_user! # Devise's default auth 

    private 

    def authenticate_user_from_token! 
    user_email = params[:user_email].presence 
    user  = user_email && User.find_by_email(user_email) 

    if user && Devise.secure_compare(user.authentication_token, params[:user_token]) 
     sign_in user, store: false 
    end 
    end 

end 

這裏的負責API響應控制器的第一部分:

class ApiController < ApplicationController 

    before_filter :cors_preflight_check 
    after_filter :cors_set_access_control_headers 

    before_filter :authenticate_user_from_token! 

    # For all responses in this controller, return the CORS access control headers. 

    def cors_set_access_control_headers 
    headers['Access-Control-Allow-Origin'] = '*' 
    headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, OPTIONS' 
    headers['Access-Control-Max-Age'] = "1728000" 
    end 

    # If this is a preflight OPTIONS request, then short-circuit the 
    # request, return only the necessary headers and return an empty 
    # text/plain. 

    def cors_preflight_check 
    if request.method == :options 
     headers['Access-Control-Allow-Origin'] = '*' 
     headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, OPTIONS' 
     headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version' 
     headers['Access-Control-Max-Age'] = '1728000' 
     render :text => '', :content_type => 'text/plain' 
    end 
    end 

    ... (response methods) 

我的路線的HTTP請求:

scope(:path => '/api/v1.0/') do 
    match '/candidates' => "api#candidates" 
    match '/districts' => "api#districts" 
    match '/articles' => "api#articles" 

    match '/candidates/:id' => "api#candidate" 
    match '/districts/:id' => "api#district" 
    match '/articles/:id' => "api#article" 

    match '/search' => "api#search" 
end 

如何創建用於通過API登錄路由(用戶提交的請求與一封電子郵件和密碼,並收到一個令牌)?

回答

1

你是什麼意思與「如何創建路線」?可能你想用一種方法創建一個類來檢查返回令牌的電子郵件和密碼,例如

class Tokens < ApplicationController 

    def create 

     @user = User.find_by_email(params[:email]) 
     # Check for password too!! 

     if @user && @user.valid_password?(params[:password]) 
      render status: 200, json: { token: @user.authentication_token } 
     else 
      render status: 411, json: { error: "Error message..." } 
     end 
    end 
end 

最後添加到您的路線:

post '/tokens' => "tokens#create" 

希望它能幫助。