sessions_controller.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. end
  110. def failure_omniauth
  111. raise Exceptions::UnprocessableEntity, "Message from #{params[:strategy]}: #{params[:message]}"
  112. end
  113. # "switch" to user
  114. def switch_to_user
  115. # check user
  116. if !params[:id]
  117. render(
  118. json: { message: 'no user given' },
  119. status: :not_found
  120. )
  121. return false
  122. end
  123. user = User.find(params[:id])
  124. if !user
  125. render(
  126. json: {},
  127. status: :not_found
  128. )
  129. return false
  130. end
  131. # remember original user
  132. session[:switched_from_user_id] ||= current_user.id
  133. # log new session
  134. user.activity_stream_log('switch to', current_user.id, true)
  135. # set session user
  136. current_user_set(user)
  137. render(
  138. json: {
  139. success: true,
  140. location: '',
  141. },
  142. )
  143. end
  144. # "switch" back to user
  145. def switch_back_to_user
  146. # check if it's a switch back
  147. raise Exceptions::Forbidden if !session[:switched_from_user_id]
  148. user = User.lookup(id: session[:switched_from_user_id])
  149. if !user
  150. render(
  151. json: {},
  152. status: :not_found
  153. )
  154. return false
  155. end
  156. # remember current user
  157. current_session_user = current_user
  158. # remove switched_from_user_id
  159. session[:switched_from_user_id] = nil
  160. # set old session user again
  161. current_user_set(user)
  162. # log end session
  163. current_session_user.activity_stream_log('ended switch to', user.id, true)
  164. render(
  165. json: {
  166. success: true,
  167. location: '',
  168. },
  169. )
  170. end
  171. def available
  172. render json: {
  173. app_version: AppVersion.get
  174. }
  175. end
  176. def list
  177. assets = {}
  178. sessions_clean = []
  179. SessionHelper.list.each do |session|
  180. next if session.data['user_id'].blank?
  181. sessions_clean.push session
  182. user = User.lookup(id: session.data['user_id'])
  183. next if !user
  184. assets = user.assets(assets)
  185. end
  186. render json: {
  187. sessions: sessions_clean,
  188. assets: assets,
  189. }
  190. end
  191. def delete
  192. SessionHelper.destroy(params[:id])
  193. render json: {}
  194. end
  195. def two_factor_authentication_method_initiate_authentication
  196. %i[username password method].each do |param|
  197. raise Exceptions::UnprocessableEntity, "The required parameter '#{param}' is missing." if params[param].blank?
  198. end
  199. auth = Auth.new(params[:username], params[:password], only_verify_password: true)
  200. begin
  201. auth.valid!
  202. rescue Auth::Error::AuthenticationFailed
  203. raise Exceptions::UnprocessableEntity, __('The username or password is incorrect.')
  204. end
  205. two_factor_method = auth.user.auth_two_factor.authentication_method_object(params[:method])
  206. raise Exceptions::UnprocessableEntity, __('The two-factor authentication method is not enabled.') if !two_factor_method&.enabled? || !two_factor_method&.available?
  207. render json: two_factor_method.initiate_authentication, status: :ok
  208. end
  209. private
  210. def authenticate_with_password
  211. auth = Auth.new(params[:username], params[:password],
  212. two_factor_method: params[:two_factor_method], two_factor_payload: params[:two_factor_payload])
  213. auth.valid!
  214. session.delete(:switched_from_user_id)
  215. authentication_check_prerequesits(auth.user, 'session')
  216. end
  217. def initiate_session_for(user, type = 'password')
  218. request.env['rack.session.options'][:expire_after] = 1.year if params[:remember_me]
  219. # Mark the session as "persistent". Non-persistent sessions (e.g. sessions generated by curl API call) are
  220. # deleted periodically in SessionHelper.cleanup_expired.
  221. session[:persistent] = true
  222. session[:authentication_type] = type
  223. user.activity_stream_log('session started', user.id, true)
  224. end
  225. def config_frontend
  226. # config
  227. config = {}
  228. Setting.select('name, preferences').where(frontend: true).each do |setting|
  229. next if setting.preferences[:authentication] == true && !current_user
  230. value = Setting.get(setting.name)
  231. next if !current_user && (value == false || value.nil?)
  232. config[setting.name] = value
  233. end
  234. # NB: Explicitly include SAML display name config
  235. # This is needed because the setting is not frontend related,
  236. # but we still to display one of the options
  237. # https://github.com/zammad/zammad/issues/4263
  238. config['auth_saml_display_name'] = Setting.get('auth_saml_credentials')[:display_name]
  239. # Include the flag for JSON column type support (currently only on PostgreSQL backend).
  240. config['column_type_json_supported'] =
  241. ActiveRecord::Base.connection_db_config.configuration_hash[:adapter] == 'postgresql'
  242. # Announce searchable models to the front end.
  243. config['models_searchable'] = Models.searchable.map(&:to_s)
  244. # remember if we can switch back to user
  245. if session[:switched_from_user_id]
  246. config['switch_back_to_possible'] = true
  247. end
  248. # remember session_id for websocket logon
  249. if current_user
  250. config['session_id'] = session.id.public_id
  251. end
  252. config['core_workflow_config'] = CoreWorkflow.config
  253. config
  254. end
  255. def saml_destroy
  256. options = OmniAuth::Strategies::SamlDatabase.setup
  257. settings = OneLogin::RubySaml::Settings.new(options)
  258. logout_request = OneLogin::RubySaml::Logoutrequest.new
  259. # Since we created a new SAML request, save the transaction_id
  260. # to compare it with the response we get back
  261. session['saml_transaction_id'] = logout_request.uuid
  262. settings.name_identifier_value = session['saml_uid']
  263. settings.sessionindex = session['saml_session_index']
  264. url = logout_request.create(settings)
  265. render json: { url: url }
  266. end
  267. end