我有一个用户可以登录我的Ruby on Rails应用程序 . 我自己用会话控制器编写了这些函数 . 当会话到期时,我还在session_store.rb中设置了一个时间 .
这一切都很好,但另外我想跟踪用户登录或注销的时间 . 现在,当用户手动完成登录和注销时,我可以跟踪它 . 但是当会话到期时,我的“sessions#destroy”选项不会被触发,因此不会设置注销时间 .
是否有可能在会话过期或会话被rails杀死时触发操作?
谢谢!
UPDATE:
对不起,我应该包含一些代码:
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
if !current_user.nil?
redirect_to start_path
end
end
def create
user = User.find_by_username(params[:username])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
UserTracing.create(user_id: user.id, sign_in_at: DateTime.now)
redirect_to start_path, notice: I18n.t("text logged_in")
else
flash.now.alert = I18n.t("error username_or_password_invalid")
render "new"
end
end
def destroy
@id = current_user.id
session[:user_id] = nil
UserTracing.where(user_id: @id).order(sign_in_at: :asc).last.update_attributes(sign_out_at: DateTime.now)
redirect_to root_url, notice: I18n.t("text logged_out")
end
end
1 回答
这很简单 .
您所要做的就是使用会话帮助方法
创建会话设置为过期会话的时间[:expires_at] = Time.now minutes_to_run * 60
创建一个检索此时间的函数 .
在加载此页面之前,在控制器中运行一个函数,以检查当前时间是否大于会话设置为到期的时间 . 该解决方案使用javascript setTimeout()来确保刷新页面,否则您将不得不等待用户重新加载 . 这样您的应用就会刷新页面 .
这是一篇博客文章,详细介绍了这个想法 . https://medium.com/@thatlovelypract/rubyonrails-timed-session-a5de0cf70f3b