handles_devices.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 initial page
  13. return true if switched_from_user_id
  14. return true if !user
  15. return true if !user.permissions?('user_preferences.device')
  16. return true if type == 'SSO'
  17. time_to_check = true
  18. user_device_updated_at = session[:user_device_updated_at]
  19. if ENV['USER_DEVICE_UPDATED_AT']
  20. user_device_updated_at = Time.zone.parse(ENV['USER_DEVICE_UPDATED_AT'])
  21. end
  22. if user_device_updated_at
  23. # check if entry exists / only if write action
  24. diff = Time.zone.now - 10.minutes
  25. if %w[GET OPTIONS HEAD].include?(request.method)
  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. UserDevice.fingerprint_validation(params[:fingerprint])
  44. session[:user_device_fingerprint] = params[:fingerprint]
  45. end
  46. end
  47. session[:user_device_updated_at] = Time.zone.now
  48. # add device if needed
  49. http_user_agent = ENV['HTTP_USER_AGENT'] || request.env['HTTP_USER_AGENT']
  50. UserDeviceLogJob.perform_later(
  51. http_user_agent,
  52. remote_ip,
  53. user.id,
  54. session[:user_device_fingerprint],
  55. type,
  56. )
  57. end
  58. end