has_user.rb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. module ApplicationController::HasUser
  2. extend ActiveSupport::Concern
  3. included do
  4. before_action :set_user, :session_update
  5. end
  6. private
  7. # Finds the User with the ID stored in the session with the key
  8. # :current_user_id This is a common way to handle user login in
  9. # a Rails application; logging in sets the session value and
  10. # logging out removes it.
  11. def current_user
  12. return @_current_user if @_current_user
  13. return if !session[:user_id]
  14. @_current_user = User.lookup(id: session[:user_id])
  15. end
  16. def current_user_set(user, auth_type = 'session')
  17. session[:user_id] = user.id
  18. @_auth_type = auth_type
  19. @_current_user = user
  20. set_user
  21. end
  22. # Sets the current user into a named Thread location so that it can be accessed
  23. # by models and observers
  24. def set_user
  25. if !current_user
  26. UserInfo.current_user_id = 1
  27. return
  28. end
  29. UserInfo.current_user_id = current_user.id
  30. end
  31. # update session updated_at
  32. def session_update
  33. #sleep 0.6
  34. session[:ping] = Time.zone.now.iso8601
  35. # check if remote ip need to be updated
  36. if session[:user_id]
  37. if !session[:remote_ip] || session[:remote_ip] != request.remote_ip
  38. session[:remote_ip] = request.remote_ip
  39. session[:geo] = Service::GeoIp.location(request.remote_ip)
  40. end
  41. end
  42. # fill user agent
  43. return if session[:user_agent]
  44. session[:user_agent] = request.env['HTTP_USER_AGENT']
  45. end
  46. def valid_session_with_user
  47. return true if current_user
  48. raise Exceptions::UnprocessableEntity, 'No session user!'
  49. end
  50. end