Posts Tagged ‘restful_authentication’

use current_user in Model

Friday, July 10th, 2009

我所有的项目几乎都用 restful_authentication 做了用户管理这部分,应用中经常要在 model 中调用 current_user,而这个是 session 相关的信息,在 Model 中不应直接读到,Google 到一个比较不错的办法,是 Beast 的作者提供的。

首先在 User Model 中加入一个类变量:

class User < ActiveRecord::Base
  cattr_accessor :current_user
  ...
end

之后在 ApplicationController 中用 before_filter 给刚才的类变量赋值:

class ApplicationController < ActionController::Base
  include AuthenticatedSystem
  before_filter { |c| User.current_user = c.current_user }
end

看似完美,测试报错,说 current_user 方法是 protected,不能调用。看看 lib/authenticated_system.rb,果然 current_user 方法是 protected,为了不破坏 restful_authenticated plugin 的结构,对 controller 里面的方法做个修改:

class ApplicationController < ActionController::Base
  include AuthenticatedSystem
  before_filter :set_current_user

  protected
  def set_current_user
    User.current_user = self.current_user
  end
end

–EOF–

restful_authentication plugin 在IE上弹出登录窗口的问题

Sunday, May 3rd, 2009

我在做过的 Rails 项目中一直使用 restful_authentication plugin,前一段有个别人向我反应用IE访问 1KG.org,点击一些需要登录后才能用的功能时,不能跳转到登录界面,而是弹出一个窗口提示输入 username & password,起初我在 VMWare 虚拟的XP中拿IE6测了一下,没有这样的情况,又拿周围一两台机器试了试,也没发现问题,于是想当然的以为是那哥们的机器中了流氓插件,导致IE不正常。

这两天配合易助网的 Boyu 同学在 1KG.org 上添加 Google AdWords Tracking code 时,他说自己身边的 IE 都有真个问题,我才意识到问题可能具有普遍性!

老婆电脑上有IE7,测试一下,也有弹窗的问题!

Google 一番,发现问题是 IE 发送不太合格的 Accepts,导致 rails 不能正确识别请求的类型造成的弹窗。

整个问题在一个 ticket 中讲的很详细

我用的解决办法是将 format.any 改成 format.any(:js, :xml):

def access_denied
    respond_to do |format|
      format.html do
        store_location
        redirect_to new_session_path
      end
      format.any(:js, :xml) do
        request_http_basic_authentication 'Web Password'
      end
    end
  end

欢迎各位用 IE 到 1KG.org 上测试一下。

restful_authentication with state machine

Wednesday, October 22nd, 2008

一直使用 restful_authentication 作用户认证,最近它加上的状态机功能(用了 acts_as_state_machine),装上以后遇到灵异事件,系统发出的激活邮件里面的激活码和数据库里面存的不一样。我并不了解 acts_as_state_machine 的具体机制,只是觉得下面一行可能运行了两遍:

state :pending, :enter => :make_activation_code

Google 了一下,在作者的 README 里找到答案:

Pay attention, may be this is not an issue for everybody, but if you should have problems, that the sent activation_code does match with that in the database stored, reload your user object before sending its data through email something like:

 

 

class UserObserver < ActiveRecord::Observer
      def after_create(user)
        user.reload
        UserMailer.deliver_signup_notification(user)
      end
      def after_save(user)
        user.reload
        UserMailer.deliver_activation(user) if user.recently_activated?
      end
end