sessions_controller.rb 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. # Copyright (C) 2012-2025 Zammad Foundation, https://zammad-foundation.org/
  2. class SessionsController < ApplicationController
  3. include HandlesOidcAuthorization
  4. prepend_before_action :authenticate_and_authorize!, only: %i[switch_to_user list delete]
  5. skip_before_action :verify_csrf_token, only: %i[show destroy
  6. create_omniauth failure_omniauth
  7. saml_destroy]
  8. skip_before_action :user_device_log, only: %i[create_sso create_omniauth]
  9. def show
  10. user = authentication_check_only
  11. raise Exceptions::NotAuthorized, 'no valid session' if user.blank?
  12. # return current session
  13. render json: SessionHelper.json_hash(user).merge(config: config_frontend, after_auth: Auth::AfterAuth.run(user, session))
  14. rescue Exceptions::NotAuthorized => e
  15. render json: SessionHelper.json_hash_error(e).merge(config: config_frontend)
  16. end
  17. # "Create" a login, aka "log the user in"
  18. def create
  19. user = authenticate_with_password
  20. initiate_session_for(user)
  21. # return new session data
  22. render status: :created,
  23. json: SessionHelper.json_hash(user).merge(config: config_frontend, after_auth: Auth::AfterAuth.run(user, session))
  24. rescue Auth::Error::TwoFactorRequired => e
  25. render json: {
  26. two_factor_required: {
  27. default_two_factor_authentication_method: e.default_two_factor_authentication_method,
  28. available_two_factor_authentication_methods: e.available_two_factor_authentication_methods,
  29. recovery_codes_available: e.recovery_codes_available
  30. }
  31. }, status: :unprocessable_entity
  32. rescue Auth::Error::Base => e
  33. raise Exceptions::NotAuthorized, e.message
  34. end
  35. def create_sso
  36. raise Exceptions::Forbidden, 'SSO authentication disabled!' if !Setting.get('auth_sso')
  37. user = begin
  38. login = request.env['REMOTE_USER'] ||
  39. request.env['HTTP_REMOTE_USER'] ||
  40. request.headers['X-Forwarded-User']
  41. User.lookup(login: login&.downcase)
  42. end
  43. raise Exceptions::NotAuthorized, __("Neither an SSO environment variable 'REMOTE_USER' nor a 'X-Forwarded-User' header could be found.") if login.blank?
  44. raise Exceptions::NotAuthorized, "User '#{login}' could not be found." if user.blank?
  45. session.delete(:switched_from_user_id)
  46. authentication_check_prerequesits(user, 'SSO')
  47. initiate_session_for(user, 'SSO')
  48. redirect_to '/#'
  49. end
  50. # "Delete" a login, aka "log the user out"
  51. def destroy
  52. if %w[test development].include?(Rails.env) && ENV['FAKE_SELENIUM_LOGIN_USER_ID'].present?
  53. ENV['FAKE_SELENIUM_LOGIN_USER_ID'] = nil # rubocop:disable Rails/EnvironmentVariableAccess
  54. ENV['FAKE_SELENIUM_LOGIN_PENDING'] = nil # rubocop:disable Rails/EnvironmentVariableAccess
  55. end
  56. return saml_destroy if saml_session?
  57. return oidc_destroy if oidc_session?
  58. reset_session
  59. # Remove the user id from the session
  60. @_current_user = nil
  61. # reset session
  62. request.env['rack.session.options'][:expire_after] = nil
  63. render json: {}
  64. end
  65. def create_omniauth
  66. # in case, remove switched_from_user_id
  67. session[:switched_from_user_id] = nil
  68. auth = request.env['omniauth.auth']
  69. redirect_url = if request.env['omniauth.origin']&.include?('/mobile')
  70. '/mobile'
  71. elsif request.env['omniauth.origin']&.include?('/desktop')
  72. '/desktop'
  73. else
  74. '/#'
  75. end
  76. if !auth
  77. logger.info('AUTH IS NULL, SERVICE NOT LINKED TO ACCOUNT')
  78. # redirect to app
  79. redirect_to redirect_url
  80. return
  81. end
  82. # Create a new user or add an auth to existing user, depending on
  83. # whether there is already a user signed in.
  84. authorization = Authorization.find_from_hash(auth)
  85. if !authorization
  86. authorization = Authorization.create_from_hash(auth, current_user)
  87. end
  88. if in_maintenance_mode?(authorization.user)
  89. redirect_to redirect_url
  90. return
  91. end
  92. # set current session user
  93. current_user_set(authorization.user)
  94. # log new session
  95. authorization.user.activity_stream_log('session started', authorization.user.id, true)
  96. # remember last login date
  97. authorization.user.update_last_login
  98. # remember omnitauth login
  99. session[:authentication_type] = 'omniauth'
  100. if auth['credentials']['id_token'].present?
  101. session[:oidc_id_token] = auth['credentials']['id_token']
  102. session[:oidc_sid] = auth['extra']['raw_info']['sid']
  103. end
  104. # Set needed fingerprint parameter.
  105. if request.env['omniauth.params']['fingerprint'].present?
  106. params[:fingerprint] = request.env['omniauth.params']['fingerprint']
  107. user_device_log(authorization.user, 'session')
  108. end
  109. # redirect to app
  110. redirect_to redirect_url
  111. rescue Authorization::Provider::AccountError => e
  112. forbidden(e)
  113. end
  114. def failure_omniauth
  115. raise Exceptions::UnprocessableEntity, "Message from #{params[:strategy]}: #{params[:message]}"
  116. end
  117. # "switch" to user
  118. def switch_to_user
  119. # check user
  120. if !params[:id]
  121. render(
  122. json: { message: 'no user given' },
  123. status: :not_found
  124. )
  125. return false
  126. end
  127. user = User.find(params[:id])
  128. if !user
  129. render(
  130. json: {},
  131. status: :not_found
  132. )
  133. return false
  134. end
  135. # remember original user
  136. session[:switched_from_user_id] ||= current_user.id
  137. # log new session
  138. user.activity_stream_log('switch to', current_user.id, true)
  139. # set session user
  140. current_user_set(user)
  141. render(
  142. json: {
  143. success: true,
  144. location: '',
  145. },
  146. )
  147. end
  148. # "switch" back to user
  149. def switch_back_to_user
  150. # check if it's a switch back
  151. raise Exceptions::Forbidden if !session[:switched_from_user_id]
  152. user = User.lookup(id: session[:switched_from_user_id])
  153. if !user
  154. render(
  155. json: {},
  156. status: :not_found
  157. )
  158. return false
  159. end
  160. # remember current user
  161. current_session_user = current_user
  162. # remove switched_from_user_id
  163. session[:switched_from_user_id] = nil
  164. # set old session user again
  165. current_user_set(user)
  166. # log end session
  167. current_session_user.activity_stream_log('ended switch to', user.id, true)
  168. render(
  169. json: {
  170. success: true,
  171. location: '',
  172. },
  173. )
  174. end
  175. def available
  176. render json: {
  177. app_version: AppVersion.get
  178. }
  179. end
  180. def list
  181. assets = {}
  182. sessions_clean = []
  183. SessionHelper.list.each do |session|
  184. next if session.data['user_id'].blank?
  185. sessions_clean.push session
  186. user = User.lookup(id: session.data['user_id'])
  187. next if !user
  188. assets = user.assets(assets)
  189. end
  190. render json: {
  191. sessions: sessions_clean,
  192. assets: assets,
  193. }
  194. end
  195. def delete
  196. SessionHelper.destroy(params[:id])
  197. render json: {}
  198. end
  199. def two_factor_authentication_method_initiate_authentication
  200. %i[username password method].each do |param|
  201. raise Exceptions::UnprocessableEntity, "The required parameter '#{param}' is missing." if params[param].blank?
  202. end
  203. auth = Auth.new(params[:username], params[:password], only_verify_password: true)
  204. begin
  205. auth.valid!
  206. rescue Auth::Error::AuthenticationFailed
  207. raise Exceptions::UnprocessableEntity, __('The username or password is incorrect.')
  208. end
  209. two_factor_method = auth.user.auth_two_factor.authentication_method_object(params[:method])
  210. raise Exceptions::UnprocessableEntity, __('The two-factor authentication method is not enabled.') if !two_factor_method&.enabled? || !two_factor_method&.available?
  211. render json: two_factor_method.initiate_authentication, status: :ok
  212. end
  213. private
  214. def authenticate_with_password
  215. auth = Auth.new(params[:username], params[:password],
  216. two_factor_method: params[:two_factor_method], two_factor_payload: params[:two_factor_payload])
  217. auth.valid!
  218. session.delete(:switched_from_user_id)
  219. authentication_check_prerequesits(auth.user, 'session')
  220. end
  221. def initiate_session_for(user, type = 'password')
  222. request.env['rack.session.options'][:expire_after] = 1.year if params[:remember_me]
  223. # Mark the session as "persistent". Non-persistent sessions (e.g. sessions generated by curl API call) are
  224. # deleted periodically in SessionHelper.cleanup_expired.
  225. session[:persistent] = true
  226. session[:authentication_type] = type
  227. user.activity_stream_log('session started', user.id, true)
  228. end
  229. def config_frontend
  230. # config
  231. config = {}
  232. Setting.select('name, preferences').where(frontend: true).each do |setting|
  233. next if setting.preferences[:authentication] == true && !current_user
  234. value = Setting.get(setting.name)
  235. next if !current_user && (value == false || value.nil?)
  236. config[setting.name] = value
  237. end
  238. # NB: Explicitly include SAML display name config
  239. # This is needed because the setting is not frontend related,
  240. # but we still to display one of the options
  241. # https://github.com/zammad/zammad/issues/4263
  242. config['auth_saml_display_name'] = Setting.get('auth_saml_credentials')[:display_name]
  243. config['auth_openid_connect_display_name'] = Setting.get('auth_openid_connect_credentials')[:display_name]
  244. # Include the flag for JSON column type support (currently only on PostgreSQL backend).
  245. config['column_type_json_supported'] =
  246. ActiveRecord::Base.connection_db_config.configuration_hash[:adapter] == 'postgresql'
  247. # Announce searchable models to the front end.
  248. config['models_searchable'] = Models.searchable.map(&:to_s)
  249. # remember if we can switch back to user
  250. if session[:switched_from_user_id]
  251. config['switch_back_to_possible'] = true
  252. end
  253. # remember session_id for websocket logon
  254. if current_user
  255. config['session_id'] = session.id.public_id
  256. end
  257. config['core_workflow_config'] = CoreWorkflow.config
  258. config['icons_url'] = icons_url
  259. config
  260. end
  261. def saml_session?
  262. (session['saml_uid'] || session['saml_session_index']) && OmniAuth::Strategies::SamlDatabase.setup.fetch('idp_slo_service_url', nil)
  263. end
  264. def saml_destroy
  265. options = OmniAuth::Strategies::SamlDatabase.setup
  266. settings = OneLogin::RubySaml::Settings.new(options)
  267. logout_request = OneLogin::RubySaml::Logoutrequest.new
  268. # Since we created a new SAML request, save the transaction_id
  269. # to compare it with the response we get back
  270. session['saml_transaction_id'] = logout_request.uuid
  271. settings.name_identifier_value = session['saml_uid']
  272. settings.sessionindex = session['saml_session_index']
  273. url = logout_request.create(settings)
  274. render json: { url: url }
  275. rescue => e
  276. Rails.logger.error "SAML SLO failed: #{e.message}"
  277. end
  278. end