discourse/lib/current_user.rb

59 lines
1.5 KiB
Ruby
Raw Normal View History

2013-02-05 14:16:51 -05:00
module CurrentUser
2013-02-15 03:23:40 -05:00
def self.lookup_from_env(env)
request = Rack::Request.new(env)
lookup_from_auth_token(request.cookies["_t"])
end
def self.lookup_from_auth_token(auth_token)
2013-02-15 03:23:40 -05:00
if auth_token && auth_token.length == 32
2013-02-25 11:42:20 -05:00
User.where(auth_token: auth_token).first
end
end
def log_on_user(user)
session[:current_user_id] = user.id
unless user.auth_token
user.auth_token = SecureRandom.hex(16)
user.save!
2013-02-15 03:23:40 -05:00
end
set_permanent_cookie!(user)
end
def set_permanent_cookie!(user)
cookies.permanent["_t"] = { :value => user.auth_token, :httponly => true }
2013-02-15 03:23:40 -05:00
end
2013-02-05 14:16:51 -05:00
def current_user
return @current_user if @current_user || @not_logged_in
if session[:current_user_id].blank?
2013-02-25 11:42:20 -05:00
# maybe we have a cookie?
@current_user = CurrentUser.lookup_from_auth_token(cookies["_t"])
session[:current_user_id] = @current_user.id if @current_user
2013-02-05 14:16:51 -05:00
else
@current_user ||= User.where(id: session[:current_user_id]).first
2013-02-25 11:42:20 -05:00
# I have flip flopped on this (sam), if our permanent cookie
# conflicts with our current session assume session is bust
# kill it
if @current_user && cookies["_t"] != @current_user.auth_token
@current_user = nil
end
2013-02-05 14:16:51 -05:00
end
2013-02-25 11:42:20 -05:00
if @current_user && @current_user.is_banned?
2013-02-05 14:16:51 -05:00
@current_user = nil
end
@not_logged_in = session[:current_user_id].blank?
if @current_user
2013-02-25 11:42:20 -05:00
@current_user.update_last_seen!
@current_user.update_ip_address!(request.remote_ip)
2013-02-05 14:16:51 -05:00
end
@current_user
end
end