handles_devices.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. module ApplicationController::HandlesDevices
  2. extend ActiveSupport::Concern
  3. included do
  4. before_action :user_device_check
  5. end
  6. def user_device_check
  7. return false if !user_device_log(current_user, 'session')
  8. true
  9. end
  10. def user_device_log(user, type)
  11. switched_from_user_id = ENV['SWITCHED_FROM_USER_ID'] || session[:switched_from_user_id]
  12. return true if params[:controller] == 'init' # do no device logging on static inital page
  13. return true if switched_from_user_id
  14. return true if !user
  15. return true if !user.permissions?('user_preferences.device')
  16. time_to_check = true
  17. user_device_updated_at = session[:user_device_updated_at]
  18. if ENV['USER_DEVICE_UPDATED_AT']
  19. user_device_updated_at = Time.zone.parse(ENV['USER_DEVICE_UPDATED_AT'])
  20. end
  21. if user_device_updated_at
  22. # check if entry exists / only if write action
  23. diff = Time.zone.now - 10.minutes
  24. method = request.method
  25. if method == 'GET' || method == 'OPTIONS' || method == 'HEAD'
  26. diff = Time.zone.now - 30.minutes
  27. end
  28. # only update if needed
  29. if user_device_updated_at > diff
  30. time_to_check = false
  31. end
  32. end
  33. # if ip has not changed and ttl in still valid
  34. remote_ip = ENV['TEST_REMOTE_IP'] || request.remote_ip
  35. return true if time_to_check == false && session[:user_device_remote_ip] == remote_ip
  36. session[:user_device_remote_ip] = remote_ip
  37. # for sessions we need the fingperprint
  38. if type == 'session'
  39. if !session[:user_device_updated_at] && !params[:fingerprint] && !session[:user_device_fingerprint]
  40. raise Exceptions::UnprocessableEntity, 'Need fingerprint param!'
  41. end
  42. if params[:fingerprint]
  43. session[:user_device_fingerprint] = params[:fingerprint]
  44. end
  45. end
  46. session[:user_device_updated_at] = Time.zone.now
  47. # add device if needed
  48. http_user_agent = ENV['HTTP_USER_AGENT'] || request.env['HTTP_USER_AGENT']
  49. Delayed::Job.enqueue(
  50. Observer::UserDeviceLogJob.new(
  51. http_user_agent,
  52. remote_ip,
  53. user.id,
  54. session[:user_device_fingerprint],
  55. type,
  56. )
  57. )
  58. end
  59. end