sessions_controller.rb 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class SessionsController < ApplicationController
  3. prepend_before_action -> { authentication_check && 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]
  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)
  11. rescue Exceptions::NotAuthorized => e
  12. render json: {
  13. error: e.message,
  14. config: config_frontend,
  15. models: SessionHelper.models,
  16. collections: {
  17. Locale.to_app_model => Locale.where(active: true),
  18. PublicLink.to_app_model => PublicLink.all,
  19. }
  20. }
  21. end
  22. # "Create" a login, aka "log the user in"
  23. def create
  24. user = authenticate_with_password
  25. initiate_session_for(user)
  26. # return new session data
  27. render status: :created,
  28. json: SessionHelper.json_hash(user).merge(config: config_frontend)
  29. end
  30. def create_sso
  31. raise Exceptions::Forbidden, 'SSO authentication disabled!' if !Setting.get('auth_sso')
  32. user = begin
  33. login = request.env['REMOTE_USER'] ||
  34. request.env['HTTP_REMOTE_USER'] ||
  35. request.headers['X-Forwarded-User']
  36. User.lookup(login: login&.downcase)
  37. end
  38. raise Exceptions::NotAuthorized, __("Neither an SSO environment variable 'REMOTE_USER' nor a 'X-Forwarded-User' header could be found.") if login.blank?
  39. raise Exceptions::NotAuthorized, "User '#{login}' could not be found." if user.blank?
  40. session.delete(:switched_from_user_id)
  41. authentication_check_prerequesits(user, 'SSO', {})
  42. initiate_session_for(user)
  43. redirect_to '/#'
  44. end
  45. # "Delete" a login, aka "log the user out"
  46. def destroy
  47. if %w[test development].include?(Rails.env) && ENV['FAKE_SELENIUM_LOGIN_USER_ID'].present?
  48. ENV['FAKE_SELENIUM_LOGIN_USER_ID'] = nil # rubocop:disable Rails/EnvironmentVariableAccess
  49. ENV['FAKE_SELENIUM_LOGIN_PENDING'] = nil # rubocop:disable Rails/EnvironmentVariableAccess
  50. end
  51. if (session['saml_uid'] || session['saml_session_index']) && SamlDatabase.setup.fetch('idp_slo_service_url', nil)
  52. begin
  53. return saml_destroy
  54. rescue => e
  55. Rails.logger.error "SAML SLO failed: #{e.message}"
  56. end
  57. end
  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. if !auth
  70. logger.info('AUTH IS NULL, SERVICE NOT LINKED TO ACCOUNT')
  71. # redirect to app
  72. redirect_to '/'
  73. end
  74. # Create a new user or add an auth to existing user, depending on
  75. # whether there is already a user signed in.
  76. authorization = Authorization.find_from_hash(auth)
  77. if !authorization
  78. authorization = Authorization.create_from_hash(auth, current_user)
  79. end
  80. if in_maintenance_mode?(authorization.user)
  81. redirect_to '/#'
  82. return
  83. end
  84. # set current session user
  85. current_user_set(authorization.user)
  86. # log new session
  87. authorization.user.activity_stream_log('session started', authorization.user.id, true)
  88. # remember last login date
  89. authorization.user.update_last_login
  90. # redirect to app
  91. redirect_to '/'
  92. end
  93. def failure_omniauth
  94. raise Exceptions::UnprocessableEntity, "Message from #{params[:strategy]}: #{params[:message]}"
  95. end
  96. # "switch" to user
  97. def switch_to_user
  98. # check user
  99. if !params[:id]
  100. render(
  101. json: { message: 'no user given' },
  102. status: :not_found
  103. )
  104. return false
  105. end
  106. user = User.find(params[:id])
  107. if !user
  108. render(
  109. json: {},
  110. status: :not_found
  111. )
  112. return false
  113. end
  114. # remember original user
  115. session[:switched_from_user_id] ||= current_user.id
  116. # log new session
  117. user.activity_stream_log('switch to', current_user.id, true)
  118. # set session user
  119. current_user_set(user)
  120. render(
  121. json: {
  122. success: true,
  123. location: '',
  124. },
  125. )
  126. end
  127. # "switch" back to user
  128. def switch_back_to_user
  129. # check if it's a switch back
  130. raise Exceptions::Forbidden if !session[:switched_from_user_id]
  131. user = User.lookup(id: session[:switched_from_user_id])
  132. if !user
  133. render(
  134. json: {},
  135. status: :not_found
  136. )
  137. return false
  138. end
  139. # remember current user
  140. current_session_user = current_user
  141. # remove switched_from_user_id
  142. session[:switched_from_user_id] = nil
  143. # set old session user again
  144. current_user_set(user)
  145. # log end session
  146. current_session_user.activity_stream_log('ended switch to', user.id, true)
  147. render(
  148. json: {
  149. success: true,
  150. location: '',
  151. },
  152. )
  153. end
  154. def available
  155. render json: {
  156. app_version: AppVersion.get
  157. }
  158. end
  159. def list
  160. assets = {}
  161. sessions_clean = []
  162. SessionHelper.list.each do |session|
  163. next if session.data['user_id'].blank?
  164. sessions_clean.push session
  165. next if session.data['user_id']
  166. user = User.lookup(id: session.data['user_id'])
  167. next if !user
  168. assets = user.assets(assets)
  169. end
  170. render json: {
  171. sessions: sessions_clean,
  172. assets: assets,
  173. }
  174. end
  175. def delete
  176. SessionHelper.destroy(params[:id])
  177. render json: {}
  178. end
  179. private
  180. def authenticate_with_password
  181. auth = Auth.new(params[:username], params[:password])
  182. raise_unified_login_error if !auth.valid?
  183. session.delete(:switched_from_user_id)
  184. authentication_check_prerequesits(auth.user, 'session', {})
  185. end
  186. def initiate_session_for(user)
  187. request.env['rack.session.options'][:expire_after] = 1.year if params[:remember_me]
  188. # Mark the session as "persistent". Non-persistent sessions (e.g. sessions generated by curl API call) are
  189. # deleted periodically in SessionHelper.cleanup_expired.
  190. session[:persistent] = true
  191. user.activity_stream_log('session started', user.id, true)
  192. end
  193. def config_frontend
  194. # config
  195. config = {}
  196. Setting.select('name, preferences').where(frontend: true).each do |setting|
  197. next if setting.preferences[:authentication] == true && !current_user
  198. value = Setting.get(setting.name)
  199. next if !current_user && (value == false || value.nil?)
  200. config[setting.name] = value
  201. end
  202. Setting::Processed.process_frontend_settings! config
  203. # NB: Explicitly include SAML display name config
  204. # This is needed because the setting is not frontend related,
  205. # but we still to display one of the options
  206. # https://github.com/zammad/zammad/issues/4263
  207. config['auth_saml_display_name'] = Setting.get('auth_saml_credentials')[:display_name]
  208. # remember if we can switch back to user
  209. if session[:switched_from_user_id]
  210. config['switch_back_to_possible'] = true
  211. end
  212. # remember session_id for websocket logon
  213. if current_user
  214. config['session_id'] = session.id.public_id
  215. end
  216. config
  217. end
  218. def saml_destroy
  219. options = SamlDatabase.setup
  220. settings = OneLogin::RubySaml::Settings.new(options)
  221. logout_request = OneLogin::RubySaml::Logoutrequest.new
  222. # Since we created a new SAML request, save the transaction_id
  223. # to compare it with the response we get back
  224. session['saml_transaction_id'] = logout_request.uuid
  225. settings.name_identifier_value = session['saml_uid']
  226. settings.sessionindex = session['saml_session_index']
  227. url = logout_request.create(settings)
  228. render json: { url: url }
  229. end
  230. end