sessions_controller.rb 10 KB

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