sessions_controller.rb 7.1 KB

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