sessions_controller.rb 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. # Copyright (C) 2012-2023 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 = request.env['omniauth.origin']&.include?('/mobile') ? '/mobile' : '/#'
  72. if !auth
  73. logger.info('AUTH IS NULL, SERVICE NOT LINKED TO ACCOUNT')
  74. # redirect to app
  75. redirect_to redirect_url
  76. return
  77. end
  78. # Create a new user or add an auth to existing user, depending on
  79. # whether there is already a user signed in.
  80. authorization = Authorization.find_from_hash(auth)
  81. if !authorization
  82. authorization = Authorization.create_from_hash(auth, current_user)
  83. end
  84. if in_maintenance_mode?(authorization.user)
  85. redirect_to redirect_url
  86. return
  87. end
  88. # set current session user
  89. current_user_set(authorization.user)
  90. # log new session
  91. authorization.user.activity_stream_log('session started', authorization.user.id, true)
  92. # remember last login date
  93. authorization.user.update_last_login
  94. # remember omnitauth login
  95. session[:authentication_type] = 'omniauth'
  96. # Set needed fingerprint parameter.
  97. if request.env['omniauth.params']['fingerprint'].present?
  98. params[:fingerprint] = request.env['omniauth.params']['fingerprint']
  99. user_device_log(authorization.user, 'session')
  100. end
  101. # redirect to app
  102. redirect_to redirect_url
  103. end
  104. def failure_omniauth
  105. raise Exceptions::UnprocessableEntity, "Message from #{params[:strategy]}: #{params[:message]}"
  106. end
  107. # "switch" to user
  108. def switch_to_user
  109. # check user
  110. if !params[:id]
  111. render(
  112. json: { message: 'no user given' },
  113. status: :not_found
  114. )
  115. return false
  116. end
  117. user = User.find(params[:id])
  118. if !user
  119. render(
  120. json: {},
  121. status: :not_found
  122. )
  123. return false
  124. end
  125. # remember original user
  126. session[:switched_from_user_id] ||= current_user.id
  127. # log new session
  128. user.activity_stream_log('switch to', current_user.id, true)
  129. # set session user
  130. current_user_set(user)
  131. render(
  132. json: {
  133. success: true,
  134. location: '',
  135. },
  136. )
  137. end
  138. # "switch" back to user
  139. def switch_back_to_user
  140. # check if it's a switch back
  141. raise Exceptions::Forbidden if !session[:switched_from_user_id]
  142. user = User.lookup(id: session[:switched_from_user_id])
  143. if !user
  144. render(
  145. json: {},
  146. status: :not_found
  147. )
  148. return false
  149. end
  150. # remember current user
  151. current_session_user = current_user
  152. # remove switched_from_user_id
  153. session[:switched_from_user_id] = nil
  154. # set old session user again
  155. current_user_set(user)
  156. # log end session
  157. current_session_user.activity_stream_log('ended switch to', user.id, true)
  158. render(
  159. json: {
  160. success: true,
  161. location: '',
  162. },
  163. )
  164. end
  165. def available
  166. render json: {
  167. app_version: AppVersion.get
  168. }
  169. end
  170. def list
  171. assets = {}
  172. sessions_clean = []
  173. SessionHelper.list.each do |session|
  174. next if session.data['user_id'].blank?
  175. sessions_clean.push session
  176. next if session.data['user_id']
  177. user = User.lookup(id: session.data['user_id'])
  178. next if !user
  179. assets = user.assets(assets)
  180. end
  181. render json: {
  182. sessions: sessions_clean,
  183. assets: assets,
  184. }
  185. end
  186. def delete
  187. SessionHelper.destroy(params[:id])
  188. render json: {}
  189. end
  190. def two_factor_authentication_method_initiate_authentication
  191. %i[username password method].each do |param|
  192. raise Exceptions::UnprocessableEntity, "The required parameter '#{param}' is missing." if params[param].blank?
  193. end
  194. auth = Auth.new(params[:username], params[:password], only_verify_password: true)
  195. begin
  196. auth.valid!
  197. rescue Auth::Error::AuthenticationFailed
  198. raise Exceptions::UnprocessableEntity, __('The username or password is incorrect.')
  199. end
  200. two_factor_method = auth.user.auth_two_factor.authentication_method_object(params[:method])
  201. raise Exceptions::UnprocessableEntity, __('The two-factor authentication method is not enabled.') if !two_factor_method&.enabled? || !two_factor_method&.available?
  202. render json: two_factor_method.initiate_authentication, status: :ok
  203. end
  204. private
  205. def authenticate_with_password
  206. auth = Auth.new(params[:username], params[:password],
  207. two_factor_method: params[:two_factor_method], two_factor_payload: params[:two_factor_payload])
  208. auth.valid!
  209. session.delete(:switched_from_user_id)
  210. authentication_check_prerequesits(auth.user, 'session')
  211. end
  212. def initiate_session_for(user, type = 'password')
  213. request.env['rack.session.options'][:expire_after] = 1.year if params[:remember_me]
  214. # Mark the session as "persistent". Non-persistent sessions (e.g. sessions generated by curl API call) are
  215. # deleted periodically in SessionHelper.cleanup_expired.
  216. session[:persistent] = true
  217. session[:authentication_type] = type
  218. user.activity_stream_log('session started', user.id, true)
  219. end
  220. def config_frontend
  221. # config
  222. config = {}
  223. Setting.select('name, preferences').where(frontend: true).each do |setting|
  224. next if setting.preferences[:authentication] == true && !current_user
  225. value = Setting.get(setting.name)
  226. next if !current_user && (value == false || value.nil?)
  227. config[setting.name] = value
  228. end
  229. Setting::Processed.process_frontend_settings! config
  230. # NB: Explicitly include SAML display name config
  231. # This is needed because the setting is not frontend related,
  232. # but we still to display one of the options
  233. # https://github.com/zammad/zammad/issues/4263
  234. config['auth_saml_display_name'] = Setting.get('auth_saml_credentials')[:display_name]
  235. # Announce searchable models to the front end.
  236. config['models_searchable'] = Models.searchable.map(&:to_s)
  237. # remember if we can switch back to user
  238. if session[:switched_from_user_id]
  239. config['switch_back_to_possible'] = true
  240. end
  241. # remember session_id for websocket logon
  242. if current_user
  243. config['session_id'] = session.id.public_id
  244. end
  245. config
  246. end
  247. def saml_destroy
  248. options = OmniAuth::Strategies::SamlDatabase.setup
  249. settings = OneLogin::RubySaml::Settings.new(options)
  250. logout_request = OneLogin::RubySaml::Logoutrequest.new
  251. # Since we created a new SAML request, save the transaction_id
  252. # to compare it with the response we get back
  253. session['saml_transaction_id'] = logout_request.uuid
  254. settings.name_identifier_value = session['saml_uid']
  255. settings.sessionindex = session['saml_session_index']
  256. url = logout_request.create(settings)
  257. render json: { url: url }
  258. end
  259. end