sessions_controller.rb 8.1 KB

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