REST API:使用cookie和session定制方法 [英] REST API: Custom method using cookies and sessions
问题描述
我想使用REST API,所以我想从回报率获得的 APP2 @current_user APP1
I am trying to use REST API, so I want get a @current_user in APP2 from a RoR APP1.
在 APP1 /config/routes.rb我有这个code:
In APP1/config/routes.rb I have this code:
resources :users do
collection do
get 'current'
end
end
在 APP1 /controllers/application_controller.rb我有这个code:
In APP1/controllers/application_controller.rb I have this code:
before_filter :current_user
def current_user
if cookies[:remember_me]
current_user = user_from_cookie
else
current_user = User.find_by_id(session[:current_user_id])
end
unless !current_user.nil?
default_current_user = User.find_by_id(1)
end
return @current_user = current_user.nil? ? default_current_user : current_user
end
在 APP1 /controllers/users_controller.rb我有这个code:
In APP1/controllers/users_controller.rb I have this code:
def index
...
end
def show
...
end
...
def current
respond_to do |format|
format.xml { render :xml => @current_user }
end
end
在 APP2 /models/user.rb我有这个code:
In APP2/models/user.rb I have this code:
class User < ActiveResource::Base
self.site = "http://APP1"
end
在 APP2 /controllers/application_controller.rb我有这个code:
In APP2/controllers/application_controller.rb I have this code:
before_filter :current_profile
def current_profile
@current_profile = User.get(:current)
end
现在,如果我登录我的用户2 的在 APP1 并我去到http:// APP1 /users/current.xml网址我得到正确的@current_user(用户2对象),但如果我去到http:// APP2 /,即使我有'的before_filter年代,@current_profile将始终default_current_user(User.find_by_id( 1)对象),而不是的用户2 的
Now, if I Sign in my User2 in APP1 and I go to http://APP1/users/current.xml URL I get the correct @current_user (User2 object), but if I go to http://APP2/, even though I have 'before_filter's, the @current_profile will be always the default_current_user (User.find_by_id(1) object) instead of User2.
这似乎并不在乎这一code APP1 /controllers/application_controller.rb:
It seems do not care this code from APP1/controllers/application_controller.rb:
if cookies[:remember_me]
current_user = user_from_cookie
else
current_user = User.find_by_id(session[:current_user_id])
end
什么是错的?
的 EDITED 的
也许我们可以通过解决这个问题的 APP1 /config/routes.rb参数(?!)
Maybe we can solve this problem through APP1/config/routes.rb parameters (?!):
实例: APP1 /config/routes.rb
Example: in APP1/config/routes.rb
resources :users do
collection do
get 'current', :current_user => @current_user # ?!
end
end
或类似的东西。
推荐答案
当你做其他网站的请求,当前用户的cookie是不可访问。该请求是从服务器到服务器,因此应用程序一无所知,要求它的用户。我认为一个解决办法是自己发送的参数,并检查这些。
When you do a request to another website, the cookies of the current user are not accessible. The request is from server to server, so the application knows nothing about the user requesting it. I think a solution would be to send the parameters yourself and check for those.
这篇关于REST API:使用cookie和session定制方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!