sessions_controller.rb 11 KB

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