ruby-on-rails - 设计令牌身份验证的API路由

  显示原文与译文双语对照的内容

我正在 Rails 3应用程序中使用设计来进行用户身份验证。 这个应用程序也为移动应用程序提供API响应。 我阅读了以各种原因删除标记身份验证功能,并根据这个要求在应用程序中实现它: https://gist.github.com/josevalim/fb706b1e933ef01e4fb6


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 ( 用户提交带有电子邮件和密码的请求并接收令牌) 登录的路由?

时间: 作者:

什么是"如何创建路由"? 你可能希望创建一个类,以检查返回令牌的电子邮件和密码,e.g.


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"

希望有帮助。

作者:
...