application_controller.rb 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. require 'exceptions'
  3. class ApplicationController < ActionController::Base
  4. include ErrorHandling
  5. # http_basic_authenticate_with :name => "test", :password => "ttt"
  6. helper_method :current_user,
  7. :authentication_check,
  8. :config_frontend,
  9. :http_log_config,
  10. :model_create_render,
  11. :model_update_render,
  12. :model_restory_render,
  13. :mode_show_rendeder,
  14. :model_index_render
  15. skip_before_action :verify_authenticity_token
  16. before_action :transaction_begin, :set_user, :session_update, :user_device_check, :cors_preflight_check
  17. after_action :transaction_end, :http_log, :set_access_control_headers
  18. # For all responses in this controller, return the CORS access control headers.
  19. def set_access_control_headers
  20. headers['Access-Control-Allow-Origin'] = '*'
  21. headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
  22. headers['Access-Control-Max-Age'] = '1728000'
  23. headers['Access-Control-Allow-Headers'] = 'Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Accept-Language'
  24. headers['Access-Control-Allow-Credentials'] = 'true'
  25. end
  26. # If this is a preflight OPTIONS request, then short-circuit the
  27. # request, return only the necessary headers and return an empty
  28. # text/plain.
  29. def cors_preflight_check
  30. return if request.method != 'OPTIONS'
  31. headers['Access-Control-Allow-Origin'] = '*'
  32. headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
  33. headers['Access-Control-Allow-Headers'] = 'Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Accept-Language'
  34. headers['Access-Control-Max-Age'] = '1728000'
  35. headers['Access-Control-Allow-Credentials'] = 'true'
  36. render text: '', content_type: 'text/plain'
  37. false
  38. end
  39. def http_log_config(config)
  40. @http_log_support = config
  41. end
  42. private
  43. def transaction_begin
  44. ApplicationHandleInfo.current = 'application_server'
  45. PushMessages.init
  46. end
  47. def transaction_end
  48. Observer::Transaction.commit
  49. PushMessages.finish
  50. ActiveSupport::Dependencies::Reference.clear!
  51. end
  52. # Finds the User with the ID stored in the session with the key
  53. # :current_user_id This is a common way to handle user login in
  54. # a Rails application; logging in sets the session value and
  55. # logging out removes it.
  56. def current_user
  57. return @_current_user if @_current_user
  58. return if !session[:user_id]
  59. @_current_user = User.lookup(id: session[:user_id])
  60. end
  61. def current_user_set(user)
  62. session[:user_id] = user.id
  63. @_current_user = user
  64. set_user
  65. end
  66. # Sets the current user into a named Thread location so that it can be accessed
  67. # by models and observers
  68. def set_user
  69. if !current_user
  70. UserInfo.current_user_id = 1
  71. return
  72. end
  73. UserInfo.current_user_id = current_user.id
  74. end
  75. # update session updated_at
  76. def session_update
  77. #sleep 0.6
  78. session[:ping] = Time.zone.now.iso8601
  79. # check if remote ip need to be updated
  80. if !session[:remote_ip] || session[:remote_ip] != request.remote_ip
  81. session[:remote_ip] = request.remote_ip
  82. session[:geo] = Service::GeoIp.location(request.remote_ip)
  83. end
  84. # fill user agent
  85. return if session[:user_agent]
  86. session[:user_agent] = request.env['HTTP_USER_AGENT']
  87. end
  88. # log http access
  89. def http_log
  90. return if !@http_log_support
  91. # request
  92. request_data = {
  93. content: '',
  94. content_type: request.headers['Content-Type'],
  95. content_encoding: request.headers['Content-Encoding'],
  96. source: request.headers['User-Agent'] || request.headers['Server'],
  97. }
  98. request.headers.each { |key, value|
  99. next if key[0, 5] != 'HTTP_'
  100. request_data[:content] += if key == 'HTTP_COOKIE'
  101. "#{key}: xxxxx\n"
  102. else
  103. "#{key}: #{value}\n"
  104. end
  105. }
  106. body = request.body.read
  107. if body
  108. request_data[:content] += "\n" + body
  109. end
  110. request_data[:content] = request_data[:content].slice(0, 8000)
  111. # response
  112. response_data = {
  113. code: response.status = response.code,
  114. content: '',
  115. content_type: nil,
  116. content_encoding: nil,
  117. source: nil,
  118. }
  119. response.headers.each { |key, value|
  120. response_data[:content] += "#{key}: #{value}\n"
  121. }
  122. body = response.body
  123. if body
  124. response_data[:content] += "\n" + body
  125. end
  126. response_data[:content] = response_data[:content].slice(0, 8000)
  127. record = {
  128. direction: 'in',
  129. facility: @http_log_support[:facility],
  130. url: url_for(only_path: false, overwrite_params: {}),
  131. status: response.status,
  132. ip: request.remote_ip,
  133. request: request_data,
  134. response: response_data,
  135. method: request.method,
  136. }
  137. HttpLog.create(record)
  138. end
  139. def user_device_check
  140. return false if !user_device_log(current_user, 'session')
  141. true
  142. end
  143. def user_device_log(user, type)
  144. switched_from_user_id = ENV['SWITCHED_FROM_USER_ID'] || session[:switched_from_user_id]
  145. return true if params[:controller] == 'init' # do no device logging on static inital page
  146. return true if switched_from_user_id
  147. return true if !user
  148. return true if !user.permissions?('user_preferences.device')
  149. time_to_check = true
  150. user_device_updated_at = session[:user_device_updated_at]
  151. if ENV['USER_DEVICE_UPDATED_AT']
  152. user_device_updated_at = Time.zone.parse(ENV['USER_DEVICE_UPDATED_AT'])
  153. end
  154. if user_device_updated_at
  155. # check if entry exists / only if write action
  156. diff = Time.zone.now - 10.minutes
  157. method = request.method
  158. if method == 'GET' || method == 'OPTIONS' || method == 'HEAD'
  159. diff = Time.zone.now - 30.minutes
  160. end
  161. # only update if needed
  162. if user_device_updated_at > diff
  163. time_to_check = false
  164. end
  165. end
  166. # if ip has not changed and ttl in still valid
  167. remote_ip = ENV['TEST_REMOTE_IP'] || request.remote_ip
  168. return true if time_to_check == false && session[:user_device_remote_ip] == remote_ip
  169. session[:user_device_remote_ip] = remote_ip
  170. # for sessions we need the fingperprint
  171. if type == 'session'
  172. if !session[:user_device_updated_at] && !params[:fingerprint] && !session[:user_device_fingerprint]
  173. raise Exceptions::UnprocessableEntity, 'Need fingerprint param!'
  174. end
  175. if params[:fingerprint]
  176. session[:user_device_fingerprint] = params[:fingerprint]
  177. end
  178. end
  179. session[:user_device_updated_at] = Time.zone.now
  180. # add device if needed
  181. http_user_agent = ENV['HTTP_USER_AGENT'] || request.env['HTTP_USER_AGENT']
  182. Delayed::Job.enqueue(
  183. Observer::UserDeviceLogJob.new(
  184. http_user_agent,
  185. remote_ip,
  186. user.id,
  187. session[:user_device_fingerprint],
  188. type,
  189. )
  190. )
  191. end
  192. def authentication_check_only(auth_param)
  193. #logger.debug 'authentication_check'
  194. #logger.debug params.inspect
  195. #logger.debug session.inspect
  196. #logger.debug cookies.inspect
  197. # already logged in, early exit
  198. if session.id && session[:user_id]
  199. logger.debug 'session based auth check'
  200. user = User.lookup(id: session[:user_id])
  201. return authentication_check_prerequesits(user, 'session', auth_param) if user
  202. end
  203. # check sso based authentication
  204. sso_user = User.sso(params)
  205. if sso_user
  206. if authentication_check_prerequesits(sso_user, 'session', auth_param)
  207. session[:persistent] = true
  208. return sso_user
  209. end
  210. end
  211. # check http basic based authentication
  212. authenticate_with_http_basic do |username, password|
  213. request.session_options[:skip] = true # do not send a session cookie
  214. logger.debug "http basic auth check '#{username}'"
  215. if Setting.get('api_password_access') == false
  216. raise Exceptions::NotAuthorized, 'API password access disabled!'
  217. end
  218. user = User.authenticate(username, password)
  219. return authentication_check_prerequesits(user, 'basic_auth', auth_param) if user
  220. end
  221. # check http token based authentication
  222. authenticate_with_http_token do |token_string, _options|
  223. logger.debug "http token auth check '#{token_string}'"
  224. request.session_options[:skip] = true # do not send a session cookie
  225. if Setting.get('api_token_access') == false
  226. raise Exceptions::NotAuthorized, 'API token access disabled!'
  227. end
  228. user = Token.check(
  229. action: 'api',
  230. name: token_string,
  231. inactive_user: true,
  232. )
  233. if user && auth_param[:permission]
  234. user = Token.check(
  235. action: 'api',
  236. name: token_string,
  237. permission: auth_param[:permission],
  238. inactive_user: true,
  239. )
  240. raise Exceptions::NotAuthorized, 'Not authorized (token)!' if !user
  241. end
  242. if user
  243. token = Token.find_by(name: token_string)
  244. token.last_used_at = Time.zone.now
  245. token.save!
  246. if token.expires_at &&
  247. Time.zone.today >= token.expires_at
  248. raise Exceptions::NotAuthorized, 'Not authorized (token expired)!'
  249. end
  250. end
  251. @_token_auth = token_string # remember for permission_check
  252. return authentication_check_prerequesits(user, 'token_auth', auth_param) if user
  253. end
  254. # check oauth2 token based authentication
  255. token = Doorkeeper::OAuth::Token.from_bearer_authorization(request)
  256. if token
  257. request.session_options[:skip] = true # do not send a session cookie
  258. logger.debug "oauth2 token auth check '#{token}'"
  259. access_token = Doorkeeper::AccessToken.by_token(token)
  260. if !access_token
  261. raise Exceptions::NotAuthorized, 'Invalid token!'
  262. end
  263. # check expire
  264. if access_token.expires_in && (access_token.created_at + access_token.expires_in) < Time.zone.now
  265. raise Exceptions::NotAuthorized, 'OAuth2 token is expired!'
  266. end
  267. # if access_token.scopes.empty?
  268. # raise Exceptions::NotAuthorized, 'OAuth2 scope missing for token!'
  269. # end
  270. user = User.find(access_token.resource_owner_id)
  271. return authentication_check_prerequesits(user, 'token_auth', auth_param) if user
  272. end
  273. false
  274. end
  275. def authentication_check_prerequesits(user, auth_type, auth_param)
  276. if check_maintenance_only(user)
  277. raise Exceptions::NotAuthorized, 'Maintenance mode enabled!'
  278. end
  279. if user.active == false
  280. raise Exceptions::NotAuthorized, 'User is inactive!'
  281. end
  282. # check scopes / permission check
  283. if auth_param[:permission] && !user.permissions?(auth_param[:permission])
  284. raise Exceptions::NotAuthorized, 'Not authorized (user)!'
  285. end
  286. current_user_set(user)
  287. user_device_log(user, auth_type)
  288. logger.debug "#{auth_type} for '#{user.login}'"
  289. true
  290. end
  291. def authentication_check(auth_param = {})
  292. user = authentication_check_only(auth_param)
  293. # check if basic_auth fallback is possible
  294. if auth_param[:basic_auth_promt] && !user
  295. return request_http_basic_authentication
  296. end
  297. # return auth not ok
  298. if !user
  299. raise Exceptions::NotAuthorized, 'authentication failed'
  300. end
  301. # return auth ok
  302. true
  303. end
  304. def ticket_permission(ticket)
  305. return true if ticket.permission(current_user: current_user)
  306. raise Exceptions::NotAuthorized
  307. end
  308. def article_permission(article)
  309. ticket = Ticket.lookup(id: article.ticket_id)
  310. return true if ticket.permission(current_user: current_user)
  311. raise Exceptions::NotAuthorized
  312. end
  313. def article_create(ticket, params)
  314. # create article if given
  315. form_id = params[:form_id]
  316. params.delete(:form_id)
  317. # check min. params
  318. raise Exceptions::UnprocessableEntity, 'Need at least article: { body: "some text" }' if !params[:body]
  319. # fill default values
  320. if params[:type_id].empty? && params[:type].empty?
  321. params[:type_id] = Ticket::Article::Type.lookup(name: 'note').id
  322. end
  323. if params[:sender_id].empty? && params[:sender].empty?
  324. sender = 'Customer'
  325. if current_user.permissions?('ticket.agent')
  326. sender = 'Agent'
  327. end
  328. params[:sender_id] = Ticket::Article::Sender.lookup(name: sender).id
  329. end
  330. # remember time accounting
  331. time_unit = params[:time_unit]
  332. clean_params = Ticket::Article.association_name_to_id_convert(params)
  333. clean_params = Ticket::Article.param_cleanup(clean_params, true)
  334. # overwrite params
  335. if !current_user.permissions?('ticket.agent')
  336. clean_params[:sender_id] = Ticket::Article::Sender.lookup(name: 'Customer').id
  337. clean_params.delete(:sender)
  338. type = Ticket::Article::Type.lookup(id: clean_params[:type_id])
  339. if type.name !~ /^(note|web)$/
  340. clean_params[:type_id] = Ticket::Article::Type.lookup(name: 'note').id
  341. end
  342. clean_params.delete(:type)
  343. clean_params[:internal] = false
  344. end
  345. article = Ticket::Article.new(clean_params)
  346. article.ticket_id = ticket.id
  347. # store dataurl images to store
  348. if form_id && article.body && article.content_type =~ %r{text/html}i
  349. article.body.gsub!( %r{(<img\s.+?src=")(data:image/(jpeg|png);base64,.+?)">}i ) { |_item|
  350. file_attributes = StaticAssets.data_url_attributes($2)
  351. cid = "#{ticket.id}.#{form_id}.#{rand(999_999)}@#{Setting.get('fqdn')}"
  352. headers_store = {
  353. 'Content-Type' => file_attributes[:mime_type],
  354. 'Mime-Type' => file_attributes[:mime_type],
  355. 'Content-ID' => cid,
  356. 'Content-Disposition' => 'inline',
  357. }
  358. store = Store.add(
  359. object: 'UploadCache',
  360. o_id: form_id,
  361. data: file_attributes[:content],
  362. filename: cid,
  363. preferences: headers_store
  364. )
  365. "#{$1}cid:#{cid}\">"
  366. }
  367. end
  368. # find attachments in upload cache
  369. if form_id
  370. article.attachments = Store.list(
  371. object: 'UploadCache',
  372. o_id: form_id,
  373. )
  374. end
  375. article.save!
  376. # account time
  377. if time_unit.present?
  378. Ticket::TimeAccounting.create!(
  379. ticket_id: article.ticket_id,
  380. ticket_article_id: article.id,
  381. time_unit: time_unit
  382. )
  383. end
  384. # remove attachments from upload cache
  385. return article if !form_id
  386. Store.remove(
  387. object: 'UploadCache',
  388. o_id: form_id,
  389. )
  390. article
  391. end
  392. def permission_check(key)
  393. if @_token_auth
  394. user = Token.check(
  395. action: 'api',
  396. name: @_token_auth,
  397. permission: key,
  398. )
  399. return false if user
  400. raise Exceptions::NotAuthorized, 'Not authorized (token)!'
  401. end
  402. return false if current_user && current_user.permissions?(key)
  403. raise Exceptions::NotAuthorized, 'Not authorized (user)!'
  404. end
  405. def valid_session_with_user
  406. return true if current_user
  407. raise Exceptions::UnprocessableEntity, 'No session user!'
  408. end
  409. def response_access_deny
  410. raise Exceptions::NotAuthorized
  411. end
  412. def config_frontend
  413. # config
  414. config = {}
  415. Setting.select('name, preferences').where(frontend: true).each { |setting|
  416. next if setting.preferences[:authentication] == true && !current_user
  417. value = Setting.get(setting.name)
  418. next if !current_user && (value == false || value.nil?)
  419. config[setting.name] = value
  420. }
  421. # remember if we can to swich back to user
  422. if session[:switched_from_user_id]
  423. config['switch_back_to_possible'] = true
  424. end
  425. # remember session_id for websocket logon
  426. if current_user
  427. config['session_id'] = session.id
  428. end
  429. config
  430. end
  431. # model helper
  432. def model_create_render(object, params)
  433. clean_params = object.association_name_to_id_convert(params)
  434. clean_params = object.param_cleanup(clean_params, true)
  435. # create object
  436. generic_object = object.new(clean_params)
  437. # save object
  438. generic_object.save!
  439. # set relations
  440. generic_object.associations_from_param(params)
  441. if params[:expand]
  442. render json: generic_object.attributes_with_association_names, status: :created
  443. return
  444. end
  445. model_create_render_item(generic_object)
  446. end
  447. def model_create_render_item(generic_object)
  448. render json: generic_object.attributes_with_association_ids, status: :created
  449. end
  450. def model_update_render(object, params)
  451. # find object
  452. generic_object = object.find(params[:id])
  453. clean_params = object.association_name_to_id_convert(params)
  454. clean_params = object.param_cleanup(clean_params, true)
  455. generic_object.with_lock do
  456. # set attributes
  457. generic_object.update_attributes!(clean_params)
  458. # set relations
  459. generic_object.associations_from_param(params)
  460. end
  461. if params[:expand]
  462. render json: generic_object.attributes_with_association_names, status: :ok
  463. return
  464. end
  465. model_update_render_item(generic_object)
  466. end
  467. def model_update_render_item(generic_object)
  468. render json: generic_object.attributes_with_association_ids, status: :ok
  469. end
  470. def model_destroy_render(object, params)
  471. generic_object = object.find(params[:id])
  472. generic_object.destroy!
  473. model_destroy_render_item()
  474. end
  475. def model_destroy_render_item ()
  476. render json: {}, status: :ok
  477. end
  478. def model_show_render(object, params)
  479. if params[:expand]
  480. generic_object = object.find(params[:id])
  481. render json: generic_object.attributes_with_association_names, status: :ok
  482. return
  483. end
  484. if params[:full]
  485. generic_object_full = object.full(params[:id])
  486. render json: generic_object_full, status: :ok
  487. return
  488. end
  489. generic_object = object.find(params[:id])
  490. model_show_render_item(generic_object)
  491. end
  492. def model_show_render_item(generic_object)
  493. render json: generic_object.attributes_with_association_ids, status: :ok
  494. end
  495. def model_index_render(object, params)
  496. offset = 0
  497. per_page = 500
  498. if params[:page] && params[:per_page]
  499. offset = (params[:page].to_i - 1) * params[:per_page].to_i
  500. limit = params[:per_page].to_i
  501. end
  502. if per_page > 500
  503. per_page = 500
  504. end
  505. generic_objects = if offset.positive?
  506. object.limit(params[:per_page]).order(id: 'ASC').offset(offset).limit(limit)
  507. else
  508. object.all.order(id: 'ASC').offset(offset).limit(limit)
  509. end
  510. if params[:expand]
  511. list = []
  512. generic_objects.each { |generic_object|
  513. list.push generic_object.attributes_with_association_names
  514. }
  515. render json: list, status: :ok
  516. return
  517. end
  518. if params[:full]
  519. assets = {}
  520. item_ids = []
  521. generic_objects.each { |item|
  522. item_ids.push item.id
  523. assets = item.assets(assets)
  524. }
  525. render json: {
  526. record_ids: item_ids,
  527. assets: assets,
  528. }, status: :ok
  529. return
  530. end
  531. generic_objects_with_associations = []
  532. generic_objects.each { |item|
  533. generic_objects_with_associations.push item.attributes_with_association_ids
  534. }
  535. model_index_render_result(generic_objects_with_associations)
  536. end
  537. def model_index_render_result(generic_objects)
  538. render json: generic_objects, status: :ok
  539. end
  540. def model_references_check(object, params)
  541. generic_object = object.find(params[:id])
  542. result = Models.references(object, generic_object.id)
  543. return false if result.empty?
  544. raise Exceptions::UnprocessableEntity, 'Can\'t delete, object has references.'
  545. rescue => e
  546. raise Exceptions::UnprocessableEntity, e
  547. end
  548. # check maintenance mode
  549. def check_maintenance_only(user)
  550. return false if Setting.get('maintenance_mode') != true
  551. return false if user.permissions?('admin.maintenance')
  552. Rails.logger.info "Maintenance mode enabled, denied login for user #{user.login}, it's no admin user."
  553. true
  554. end
  555. def check_maintenance(user)
  556. return false if !check_maintenance_only(user)
  557. raise Exceptions::NotAuthorized, 'Maintenance mode enabled!'
  558. end
  559. end