sessions_controller.rb 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class SessionsController < ApplicationController
  3. prepend_before_action -> { authentication_check && authorize! }, only: %i[switch_to_user list delete]
  4. skip_before_action :verify_csrf_token, only: %i[show destroy create_omniauth failure_omniauth saml_destroy]
  5. skip_before_action :user_device_log, only: %i[create_sso create_omniauth]
  6. def show
  7. user = authentication_check_only
  8. raise Exceptions::NotAuthorized, 'no valid session' if user.blank?
  9. # return current session
  10. render json: SessionHelper.json_hash(user).merge(config: config_frontend)
  11. rescue Exceptions::NotAuthorized => e
  12. render json: SessionHelper.json_hash_error(e).merge(config: config_frontend)
  13. end
  14. # "Create" a login, aka "log the user in"
  15. def create
  16. user = authenticate_with_password
  17. initiate_session_for(user)
  18. # return new session data
  19. render status: :created,
  20. json: SessionHelper.json_hash(user).merge(config: config_frontend)
  21. end
  22. def create_sso
  23. raise Exceptions::Forbidden, 'SSO authentication disabled!' if !Setting.get('auth_sso')
  24. user = begin
  25. login = request.env['REMOTE_USER'] ||
  26. request.env['HTTP_REMOTE_USER'] ||
  27. request.headers['X-Forwarded-User']
  28. User.lookup(login: login&.downcase)
  29. end
  30. raise Exceptions::NotAuthorized, __("Neither an SSO environment variable 'REMOTE_USER' nor a 'X-Forwarded-User' header could be found.") if login.blank?
  31. raise Exceptions::NotAuthorized, "User '#{login}' could not be found." if user.blank?
  32. session.delete(:switched_from_user_id)
  33. authentication_check_prerequesits(user, 'SSO', {})
  34. initiate_session_for(user)
  35. redirect_to '/#'
  36. end
  37. # "Delete" a login, aka "log the user out"
  38. def destroy
  39. if %w[test development].include?(Rails.env) && ENV['FAKE_SELENIUM_LOGIN_USER_ID'].present?
  40. ENV['FAKE_SELENIUM_LOGIN_USER_ID'] = nil # rubocop:disable Rails/EnvironmentVariableAccess
  41. ENV['FAKE_SELENIUM_LOGIN_PENDING'] = nil # rubocop:disable Rails/EnvironmentVariableAccess
  42. end
  43. if session['saml_uid'] || session['saml_session_index']
  44. return saml_destroy
  45. end
  46. reset_session
  47. # Remove the user id from the session
  48. @_current_user = nil
  49. # reset session
  50. request.env['rack.session.options'][:expire_after] = nil
  51. render json: {}
  52. end
  53. def create_omniauth
  54. # in case, remove switched_from_user_id
  55. session[:switched_from_user_id] = nil
  56. auth = request.env['omniauth.auth']
  57. redirect_url = request.env['omniauth.origin']&.include?('/mobile') ? '/mobile' : '/#'
  58. if !auth
  59. logger.info('AUTH IS NULL, SERVICE NOT LINKED TO ACCOUNT')
  60. # redirect to app
  61. redirect_to redirect_url
  62. return
  63. end
  64. # Create a new user or add an auth to existing user, depending on
  65. # whether there is already a user signed in.
  66. authorization = Authorization.find_from_hash(auth)
  67. if !authorization
  68. authorization = Authorization.create_from_hash(auth, current_user)
  69. end
  70. if in_maintenance_mode?(authorization.user)
  71. redirect_to redirect_url
  72. return
  73. end
  74. # set current session user
  75. current_user_set(authorization.user)
  76. # log new session
  77. authorization.user.activity_stream_log('session started', authorization.user.id, true)
  78. # remember last login date
  79. authorization.user.update_last_login
  80. # Set needed fingerprint parameter.
  81. if request.env['omniauth.params']['fingerprint'].present?
  82. params[:fingerprint] = request.env['omniauth.params']['fingerprint']
  83. user_device_log(authorization.user, 'session')
  84. end
  85. # redirect to app
  86. redirect_to redirect_url
  87. end
  88. def failure_omniauth
  89. raise Exceptions::UnprocessableEntity, "Message from #{params[:strategy]}: #{params[:message]}"
  90. end
  91. # "switch" to user
  92. def switch_to_user
  93. # check user
  94. if !params[:id]
  95. render(
  96. json: { message: 'no user given' },
  97. status: :not_found
  98. )
  99. return false
  100. end
  101. user = User.find(params[:id])
  102. if !user
  103. render(
  104. json: {},
  105. status: :not_found
  106. )
  107. return false
  108. end
  109. # remember original user
  110. session[:switched_from_user_id] ||= current_user.id
  111. # log new session
  112. user.activity_stream_log('switch to', current_user.id, true)
  113. # set session user
  114. current_user_set(user)
  115. render(
  116. json: {
  117. success: true,
  118. location: '',
  119. },
  120. )
  121. end
  122. # "switch" back to user
  123. def switch_back_to_user
  124. # check if it's a switch back
  125. raise Exceptions::Forbidden if !session[:switched_from_user_id]
  126. user = User.lookup(id: session[:switched_from_user_id])
  127. if !user
  128. render(
  129. json: {},
  130. status: :not_found
  131. )
  132. return false
  133. end
  134. # remember current user
  135. current_session_user = current_user
  136. # remove switched_from_user_id
  137. session[:switched_from_user_id] = nil
  138. # set old session user again
  139. current_user_set(user)
  140. # log end session
  141. current_session_user.activity_stream_log('ended switch to', user.id, true)
  142. render(
  143. json: {
  144. success: true,
  145. location: '',
  146. },
  147. )
  148. end
  149. def available
  150. render json: {
  151. app_version: AppVersion.get
  152. }
  153. end
  154. def list
  155. assets = {}
  156. sessions_clean = []
  157. SessionHelper.list.each do |session|
  158. next if session.data['user_id'].blank?
  159. sessions_clean.push session
  160. next if session.data['user_id']
  161. user = User.lookup(id: session.data['user_id'])
  162. next if !user
  163. assets = user.assets(assets)
  164. end
  165. render json: {
  166. sessions: sessions_clean,
  167. assets: assets,
  168. }
  169. end
  170. def delete
  171. SessionHelper.destroy(params[:id])
  172. render json: {}
  173. end
  174. private
  175. def authenticate_with_password
  176. auth = Auth.new(params[:username], params[:password])
  177. raise_unified_login_error if !auth.valid?
  178. session.delete(:switched_from_user_id)
  179. authentication_check_prerequesits(auth.user, 'session', {})
  180. end
  181. def initiate_session_for(user)
  182. request.env['rack.session.options'][:expire_after] = 1.year if params[:remember_me]
  183. # Mark the session as "persistent". Non-persistent sessions (e.g. sessions generated by curl API call) are
  184. # deleted periodically in SessionHelper.cleanup_expired.
  185. session[:persistent] = true
  186. user.activity_stream_log('session started', user.id, true)
  187. end
  188. def config_frontend
  189. # config
  190. config = {}
  191. Setting.select('name, preferences').where(frontend: true).each do |setting|
  192. next if setting.preferences[:authentication] == true && !current_user
  193. value = Setting.get(setting.name)
  194. next if !current_user && (value == false || value.nil?)
  195. config[setting.name] = value
  196. end
  197. Setting::Processed.process_frontend_settings! config
  198. # NB: Explicitly include SAML display name config
  199. # This is needed because the setting is not frontend related,
  200. # but we still to display one of the options
  201. # https://github.com/zammad/zammad/issues/4263
  202. config['auth_saml_display_name'] = Setting.get('auth_saml_credentials')[:display_name]
  203. # remember if we can switch back to user
  204. if session[:switched_from_user_id]
  205. config['switch_back_to_possible'] = true
  206. end
  207. # remember session_id for websocket logon
  208. if current_user
  209. config['session_id'] = session.id.public_id
  210. end
  211. config
  212. end
  213. def saml_destroy
  214. options = SamlDatabase.setup
  215. settings = OneLogin::RubySaml::Settings.new(options)
  216. logout_request = OneLogin::RubySaml::Logoutrequest.new
  217. # Since we created a new SAML request, save the transaction_id
  218. # to compare it with the response we get back
  219. session['saml_transaction_id'] = logout_request.uuid
  220. settings.name_identifier_value = session['saml_uid']
  221. settings.sessionindex = session['saml_session_index']
  222. url = logout_request.create(settings)
  223. render json: { url: url }
  224. end
  225. end