You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

application_controller.rb 29 kB

13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
13 years ago
13 years ago
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
12 years ago
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
13 years ago
13 years ago
​
​
​
​
​
​
12 years ago
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
13 years ago
​
12 years ago
12 years ago
13 years ago
​
​
​
​
​
​
​
​
​
​
12 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
13 years ago
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
13 years ago
​
​
​
13 years ago
​
13 years ago
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
12 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2013 Jean-Philippe Lang
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. require 'uri'
  18. require 'cgi'
  19. class Unauthorized < Exception; end
  20. class ApplicationController < ActionController::Base
  21. include Redmine::I18n
  22. include Redmine::Pagination
  23. include RoutesHelper
  24. helper :routes
  25. #added by william
  26. helper :watchers
  27. class_attribute :accept_api_auth_actions
  28. class_attribute :accept_rss_auth_actions
  29. class_attribute :model_object
  30. layout 'base'
  31. protect_from_forgery
  32. def handle_unverified_request
  33. super
  34. raise(ActionController::InvalidAuthenticityToken)
  35. # cookies.delete(autologin_cookie_name)
  36. end
  37. before_filter :find_first_page
  38. before_filter :find_web_footer
  39. before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
  40. before_filter :user_agent
  41. rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
  42. rescue_from ::Unauthorized, :with => :deny_access
  43. rescue_from ::ActionView::MissingTemplate, :with => :missing_template
  44. include Redmine::Search::Controller
  45. include Redmine::MenuManager::MenuController
  46. helper Redmine::MenuManager::MenuHelper
  47. def user_agent
  48. logger.info "HTTP_USER_AGENT #{request.env["HTTP_USER_AGENT"]}"
  49. end
  50. def session_expiration
  51. if session[:user_id]
  52. if session_expired? && !try_to_autologin
  53. reset_session
  54. flash[:error] = l(:error_session_expired)
  55. redirect_to signin_url
  56. else
  57. session[:atime] = Time.now.utc.to_i
  58. end
  59. end
  60. end
  61. def session_expired?
  62. if Setting.session_lifetime?
  63. unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
  64. return true
  65. end
  66. end
  67. if Setting.session_timeout?
  68. unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
  69. return true
  70. end
  71. end
  72. false
  73. end
  74. def start_user_session(user)
  75. session[:user_id] = user.id
  76. session[:ctime] = Time.now.utc.to_i
  77. session[:atime] = Time.now.utc.to_i
  78. end
  79. def user_setup
  80. # Check the settings cache for each request
  81. Setting.check_cache
  82. # Find the current user
  83. User.current = find_current_user
  84. #logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
  85. end
  86. # Returns the current user or nil if no user is logged in
  87. # and starts a session if needed
  88. def current_user
  89. find_current_user
  90. end
  91. def find_current_user
  92. user = nil
  93. unless api_request?
  94. if session[:user_id]
  95. # existing session
  96. user = (User.active.find(session[:user_id]) rescue nil)
  97. elsif autologin_user = try_to_autologin
  98. user = autologin_user
  99. elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
  100. # RSS key authentication does not start a session
  101. user = User.find_by_rss_key(params[:key])
  102. end
  103. end
  104. if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
  105. if (key = api_key_from_request)
  106. # Use API key
  107. user = User.find_by_api_key(key)
  108. else
  109. # HTTP Basic, either username/password or API key/random
  110. authenticate_with_http_basic do |username, password|
  111. user = User.try_to_login(username, password)[0] || User.find_by_api_key(username)
  112. end
  113. end
  114. # Switch user if requested by an admin user
  115. if user && user.admin? && (username = api_switch_user_from_request)
  116. su = User.find_by_login(username)
  117. if su && su.active?
  118. logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
  119. user = su
  120. else
  121. render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
  122. end
  123. end
  124. end
  125. user
  126. end
  127. def autologin_cookie_name
  128. Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
  129. end
  130. def try_to_autologin
  131. if cookies[autologin_cookie_name] && Setting.autologin?
  132. # auto-login feature starts a new session
  133. user = User.try_to_autologin(cookies[autologin_cookie_name])
  134. if user
  135. reset_session
  136. start_user_session(user)
  137. end
  138. user
  139. end
  140. end
  141. def try_to_autologin1
  142. user = User.try_to_autologin(params[:token])
  143. if user
  144. logout_user if User.current.id != user.id
  145. start_user_session(user)
  146. end
  147. user
  148. end
  149. # Sets the logged in user
  150. def logged_user=(user)
  151. reset_session
  152. if user && user.is_a?(User)
  153. User.current = user
  154. start_user_session(user)
  155. else
  156. User.current = User.anonymous
  157. end
  158. end
  159. def logged_user_by_apptoken
  160. #从手机端传来apptoken则将当前登陆用户变为对应的用户
  161. if params[:apptoken]
  162. token = ApiKey.where(access_token: params[:apptoken]).first
  163. if token.expired?
  164. return
  165. end
  166. if token && !token.expired?
  167. @current_user = User.find(token.user_id)
  168. end
  169. unless @current_user.nil?
  170. self.logged_user = @current_user
  171. if @current_user
  172. @current_user.update_column(:last_login_on, Time.now)
  173. end
  174. end
  175. end
  176. end
  177. # Logs out current user
  178. def logout_user
  179. if User.current.logged?
  180. if Redmine::Configuration['cookie_domain'].present?
  181. cookies.delete(autologin_cookie_name, domain: Redmine::Configuration['cookie_domain'])
  182. else
  183. cookies.delete autologin_cookie_name
  184. end
  185. # Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
  186. self.logged_user = nil
  187. end
  188. end
  189. # check if login is globally required to access the application
  190. def check_if_login_required
  191. # no check needed if user is already logged in
  192. return true if User.current.logged?
  193. require_login if Setting.login_required?
  194. end
  195. def set_localization
  196. lang = nil
  197. if User.current.logged?
  198. lang = find_language(User.current.language)
  199. end
  200. if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
  201. accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
  202. if !accept_lang.blank?
  203. accept_lang = accept_lang.downcase
  204. lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
  205. end
  206. end
  207. lang ||= Setting.default_language
  208. set_language_if_valid(lang)
  209. end
  210. def require_login
  211. if !User.current.logged?
  212. # Extract only the basic url parameters on non-GET requests
  213. if request.get?
  214. url = url_for(params)
  215. else
  216. url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
  217. end
  218. respond_to do |format|
  219. format.html { redirect_to signin_url }
  220. format.atom { redirect_to signin_url }
  221. format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
  222. format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
  223. format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
  224. end
  225. return false
  226. end
  227. true
  228. end
  229. def require_admin
  230. return unless require_login
  231. if !User.current.admin?
  232. render_403
  233. return false
  234. end
  235. true
  236. end
  237. def deny_access
  238. User.current.logged? ? render_403 : require_login
  239. end
  240. # Authorize the user for the requested action
  241. def authorize(ctrl = params[:controller], action = params[:action], global = false)
  242. #modify by NWB
  243. allowed = authorize_allowed(params[:controller], params[:action],global)
  244. if allowed
  245. true
  246. else
  247. if @project && @project.archived?
  248. render_403 :message => :notice_not_authorized_archived_project
  249. else
  250. deny_access
  251. end
  252. end
  253. end
  254. def authorize1(ctrl = params[:controller], action = params[:action],token = params[:token], global = false)
  255. if(!User.current.logged? && !token.nil?)
  256. User.current =try_to_autologin1
  257. end
  258. allowed = authorize_allowed(params[:controller], params[:action],global)
  259. if allowed
  260. true
  261. else
  262. if @project && @project.archived?
  263. render_403 :message => :notice_not_authorized_archived_project
  264. else
  265. deny_access
  266. end
  267. end
  268. end
  269. def auth_login1(token = params[:token])
  270. if(!User.current.logged? && !token.nil?)
  271. User.current =try_to_autologin1
  272. end
  273. end
  274. def authorize_allowed(ctrl = params[:controller], action = params[:action], global = false)
  275. #modify by NWB
  276. if @project
  277. allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
  278. elsif @course
  279. allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @course || @courses, :global => global)
  280. else
  281. # allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
  282. allowed = true
  283. end
  284. allowed
  285. end
  286. def authorize_attachment_download(ctrl = params[:controller], action = params[:action], global = false)
  287. case @attachment.container_type
  288. when "Memo"
  289. allowed = User.current.allowed_to?(:memos_attachments_download,nil,:global => true)
  290. when "Message"
  291. if @project
  292. allowed = User.current.allowed_to?(:projects_attachments_download,@project,:global => false)
  293. elsif @course
  294. allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false)
  295. end
  296. when "contest"
  297. return true
  298. when "Course"
  299. allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false)
  300. else
  301. return true
  302. end
  303. if allowed
  304. true
  305. else
  306. if @project && @project.archived?
  307. render_403 :message => :notice_not_authorized_archived_project
  308. else
  309. deny_access
  310. end
  311. end
  312. end
  313. def authorize_attachment_download1(ctrl = params[:controller], action = params[:action],token = params[:token], global = false)
  314. if(!User.current.logged? && !token.nil?)
  315. User.current = try_to_autologin1
  316. end
  317. case @attachment.container_type
  318. when "Memo"
  319. allowed = User.current.allowed_to?(:memos_attachments_download,nil,:global => true)
  320. when "Message"
  321. if @project
  322. allowed = User.current.allowed_to?(:projects_attachments_download,@project,:global => false)
  323. elsif @course
  324. allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false)
  325. end
  326. when "contest"
  327. return true
  328. when "Course"
  329. allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false)
  330. else
  331. return true
  332. end
  333. if allowed
  334. true
  335. else
  336. if @project && @project.archived?
  337. render_403 :message => :notice_not_authorized_archived_project
  338. else
  339. deny_access
  340. end
  341. end
  342. end
  343. def authorize_course(ctrl = params[:controller], action = params[:action], global = false)
  344. allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @course || @course, :global => global)
  345. if allowed
  346. true
  347. else
  348. if params[:action] == 'show'
  349. #更新申请结果反馈消息的状态
  350. messages = CourseMessage.where("course_message_type =? and course_id =? and user_id =? and viewed =?", 'CourseRequestDealResult', @course.id, User.current.id, false)
  351. messages.update_all(:viewed => true)
  352. end
  353. if @course && @course.archived?
  354. render_403 :message => :notice_not_authorized_archived_project
  355. else
  356. deny_access
  357. end
  358. end
  359. end
  360. def authorize_course_global(ctrl = params[:controller], action = params[:action], global = true)
  361. authorize_course(ctrl, action, global)
  362. end
  363. # Authorize the user for the requested action outside a project
  364. def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
  365. authorize(ctrl, action, global)
  366. end
  367. # Find project of id params[:id]
  368. def find_project
  369. @project = Project.find(params[:id])
  370. rescue ActiveRecord::RecordNotFound
  371. render_404
  372. end
  373. # Find project of id params[:project_id]
  374. def find_project_by_project_id
  375. if params[:project_id]
  376. @project = Project.find(params[:project_id])
  377. elsif params[:course_id]
  378. @course = Course.find(params[:course_id])
  379. elsif params[:org_subfield_id]
  380. @org_subfield = OrgSubfield.find(params[:org_subfield_id])
  381. end
  382. rescue ActiveRecord::RecordNotFound
  383. render_404
  384. end
  385. def find_contest_by_contest_id
  386. @contest = Contest.find(params[:contest_id])
  387. rescue ActiveRecord::RecordNotFound
  388. render_404
  389. end
  390. #���course_id��project
  391. def find_project_by_course_id
  392. @bid = Bid.find params[:course_id]
  393. @project = @bid.courses[0]
  394. rescue ActiveRecord::RecordNotFound
  395. render_404
  396. end
  397. # Find a project based on params[:project_id]
  398. # TODO: some subclasses override this, see about merging their logic
  399. def find_optional_project
  400. @project = Project.find(params[:project_id]) unless params[:project_id].blank?
  401. allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
  402. allowed ? true : deny_access
  403. rescue ActiveRecord::RecordNotFound
  404. render_404
  405. end
  406. def find_optional_contest
  407. @contest = Contest.find(params[:contest_id]) unless params[:contest_id].blank?
  408. allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @contest, :global => true)
  409. allowed ? true : deny_access
  410. rescue ActiveRecord::RecordNotFound
  411. render_404
  412. end
  413. # Finds and sets @project based on @object.project
  414. def find_project_from_association
  415. render_404 unless @object.present?
  416. @project = @object.project
  417. if @project == nil && @object.has_attribute?('course_id')
  418. @course = @object.course
  419. end
  420. end
  421. def find_contest_from_association
  422. render_404 unless @object.present?
  423. @contest =@object.contest
  424. end
  425. def find_model_object
  426. model = self.class.model_object
  427. if model
  428. @object = model.find(params[:id])
  429. self.instance_variable_set('@' + controller_name.singularize, @object) if @object
  430. end
  431. rescue ActiveRecord::RecordNotFound
  432. render_404
  433. end
  434. #added by nwb
  435. #��ȡ�γ�
  436. def find_course
  437. @course= Course.find(params[:id])
  438. rescue ActiveRecord::RecordNotFound
  439. render_404
  440. end
  441. # def find_model_object_contest
  442. # model = self.class.model_object
  443. # if model
  444. # @object = model.find(params[:id])
  445. # self.instance_variable_set('@' + controller_name.singularize, @object) if @object
  446. # end
  447. # rescue ActiveRecord::RecordNotFound
  448. # render_404
  449. # end
  450. def self.model_object(model)
  451. self.model_object = model
  452. end
  453. # Find the issue whose id is the :id parameter
  454. # Raises a Unauthorized exception if the issue is not visible
  455. def find_issue
  456. # Issue.visible.find(...) can not be used to redirect user to the login form
  457. # if the issue actually exists but requires authentication
  458. @issue = Issue.find(params[:id])
  459. raise Unauthorized unless @issue.visible?
  460. @project = @issue.project
  461. rescue ActiveRecord::RecordNotFound
  462. render_404
  463. end
  464. # Find issues with a single :id param or :ids array param
  465. # Raises a Unauthorized exception if one of the issues is not visible
  466. def find_issues
  467. @issues = Issue.find_all_by_id(params[:id] || params[:ids])
  468. raise ActiveRecord::RecordNotFound if @issues.empty?
  469. raise Unauthorized unless @issues.all?(&:visible?)
  470. @projects = @issues.collect(&:project).compact.uniq
  471. @project = @projects.first if @projects.size == 1
  472. rescue ActiveRecord::RecordNotFound
  473. render_404
  474. end
  475. def find_attachments
  476. if (attachments = params[:attachments]).present?
  477. att = attachments.values.collect do |attachment|
  478. Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
  479. end
  480. att.compact!
  481. end
  482. @attachments = att || []
  483. end
  484. # make sure that the user is a member of the project (or admin) if project is private
  485. # used as a before_filter for actions that do not require any particular permission on the project
  486. def check_project_privacy
  487. if @project && !@project.archived?
  488. if @project.visible?
  489. true
  490. else
  491. deny_access
  492. end
  493. else
  494. @project = nil
  495. render_404
  496. false
  497. end
  498. end
  499. def back_url
  500. url = params[:back_url]
  501. if url.nil? && referer = request.env['HTTP_REFERER']
  502. url = CGI.unescape(referer.to_s)
  503. end
  504. url
  505. end
  506. def redirect_back_or_default(default, options={})
  507. back_url = '' #params[:back_url].to_s
  508. if back_url.present?
  509. begin
  510. uri = URI.parse(back_url)
  511. # do not redirect user to another host or to the login or register page
  512. if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
  513. back_url = back_url.gsub(%r{\/users\/(\d+)},"/users/"+default.id.to_s) if default.is_a?(:User)
  514. redirect_to(back_url)
  515. return
  516. end
  517. rescue URI::InvalidURIError
  518. logger.warn("Could not redirect to invalid URL #{back_url}")
  519. # redirect to default
  520. end
  521. elsif options[:referer]
  522. redirect_to_referer_or default
  523. return
  524. end
  525. redirect_to default
  526. false
  527. end
  528. # Redirects to the request referer if present, redirects to args or call block otherwise.
  529. def redirect_to_referer_or(*args, &block)
  530. redirect_to :back
  531. rescue ::ActionController::RedirectBackError
  532. if args.any?
  533. redirect_to *args
  534. elsif block_given?
  535. block.call
  536. else
  537. raise "#redirect_to_referer_or takes arguments or a block"
  538. end
  539. end
  540. def render_403(options={})
  541. @project = nil
  542. render_error({:message => :notice_not_authorized, :status => 403}.merge(options),'common/403')
  543. #render :template => 'common/403'
  544. return false
  545. end
  546. def render_404(options={})
  547. render_error({:message => :notice_file_not_found, :status => 404}.merge(options),'common/404')
  548. #render :template => 'common/404'
  549. return false
  550. end
  551. # Renders an error response
  552. def render_error(arg,template = 'common/error')
  553. arg = {:message => arg} unless arg.is_a?(Hash)
  554. @message = arg[:message]
  555. @lay = arg[:layout]
  556. @message = l(@message) if @message.is_a?(Symbol)
  557. @status = arg[:status] || 500
  558. respond_to do |format|
  559. format.html {
  560. if @lay
  561. render :template => template, :layout => @lay,:status => @status
  562. else
  563. render :template => template, :layout => use_layout, :status => @status
  564. end
  565. }
  566. format.any { head @status }
  567. end
  568. end
  569. # Handler for ActionView::MissingTemplate exception
  570. def missing_template
  571. logger.warn "Missing template, responding with 404"
  572. @project = nil
  573. render_404
  574. end
  575. # Filter for actions that provide an API response
  576. # but have no HTML representation for non admin users
  577. def require_admin_or_api_request
  578. return true if api_request?
  579. if User.current.admin?
  580. true
  581. elsif User.current.logged?
  582. render_error(:status => 406)
  583. else
  584. deny_access
  585. end
  586. end
  587. # Picks which layout to use based on the request
  588. #
  589. # @return [boolean, string] name of the layout to use or false for no layout
  590. def use_layout
  591. request.xhr? ? false : 'users_base'
  592. end
  593. def invalid_authenticity_token
  594. if api_request?
  595. logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
  596. end
  597. #render_error "Invalid form authenticity token."
  598. redirect_to signin_path(:login=>true)
  599. end
  600. def render_feed(items, options={})
  601. @items = items || []
  602. @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
  603. @items = @items.slice(0, Setting.feeds_limit.to_i)
  604. @title = options[:title] || Setting.app_title
  605. render :template => "common/feed", :formats => [:atom], :layout => false,
  606. :content_type => 'application/atom+xml'
  607. end
  608. def self.accept_rss_auth(*actions)
  609. if actions.any?
  610. self.accept_rss_auth_actions = actions
  611. else
  612. self.accept_rss_auth_actions || []
  613. end
  614. end
  615. def accept_rss_auth?(action=action_name)
  616. self.class.accept_rss_auth.include?(action.to_sym)
  617. end
  618. def self.accept_api_auth(*actions)
  619. if actions.any?
  620. self.accept_api_auth_actions = actions
  621. else
  622. self.accept_api_auth_actions || []
  623. end
  624. end
  625. def accept_api_auth?(action=action_name)
  626. self.class.accept_api_auth.include?(action.to_sym)
  627. end
  628. # Returns the number of objects that should be displayed
  629. # on the paginated list
  630. def per_page_option
  631. per_page = nil
  632. if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
  633. per_page = params[:per_page].to_s.to_i
  634. session[:per_page] = per_page
  635. elsif session[:per_page]
  636. per_page = session[:per_page]
  637. else
  638. per_page = Setting.per_page_options_array.first || 25
  639. end
  640. per_page
  641. end
  642. # Returns offset and limit used to retrieve objects
  643. # for an API response based on offset, limit and page parameters
  644. def api_offset_and_limit(options=params)
  645. if options[:offset].present?
  646. offset = options[:offset].to_i
  647. if offset < 0
  648. offset = 0
  649. end
  650. end
  651. limit = options[:limit].to_i
  652. if limit < 1
  653. limit = 25
  654. elsif limit > 100
  655. limit = 100
  656. end
  657. if offset.nil? && options[:page].present?
  658. offset = (options[:page].to_i - 1) * limit
  659. offset = 0 if offset < 0
  660. offset ||= 0
  661. end
  662. [offset, limit]
  663. end
  664. # qvalues http header parser
  665. # code taken from webrick
  666. def parse_qvalues(value)
  667. tmp = []
  668. if value
  669. parts = value.split(/,\s*/)
  670. parts.each {|part|
  671. if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
  672. val = m[1]
  673. q = (m[2] or 1).to_f
  674. tmp.push([val, q])
  675. end
  676. }
  677. tmp = tmp.sort_by{|val, q| -q}
  678. tmp.collect!{|val, q| val}
  679. end
  680. return tmp
  681. rescue
  682. nil
  683. end
  684. # Returns a string that can be used as filename value in Content-Disposition header
  685. def filename_for_content_disposition(name)
  686. request.env['HTTP_USER_AGENT'] =~ %r{MSIE|Trident} ? ERB::Util.url_encode(name) : name
  687. end
  688. def api_request?
  689. return false if params[:controller] == 'at'
  690. %w(xml json).include? params[:format]
  691. end
  692. # Returns the API key present in the request
  693. def api_key_from_request
  694. if params[:key].present?
  695. params[:key].to_s
  696. elsif request.headers["X-Redmine-API-Key"].present?
  697. request.headers["X-Redmine-API-Key"].to_s
  698. end
  699. end
  700. # Returns the API 'switch user' value if present
  701. def api_switch_user_from_request
  702. request.headers["X-Redmine-Switch-User"].to_s.presence
  703. end
  704. # Renders a warning flash if obj has unsaved attachments
  705. def render_attachment_warning_if_needed(obj)
  706. flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
  707. end
  708. # Sets the `flash` notice or error based the number of issues that did not save
  709. #
  710. # @param [Array, Issue] issues all of the saved and unsaved Issues
  711. # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
  712. def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
  713. if unsaved_issue_ids.empty?
  714. flash[:notice] = l(:notice_successful_update) unless issues.empty?
  715. else
  716. flash[:error] = l(:notice_failed_to_save_issues,
  717. :count => unsaved_issue_ids.size,
  718. :total => issues.size,
  719. :ids => '#' + unsaved_issue_ids.join(', #'))
  720. end
  721. end
  722. # Rescues an invalid query statement. Just in case...
  723. def query_statement_invalid(exception)
  724. logger.error "Query::StatementInvalid: #{exception.message}" if logger
  725. session.delete(:query)
  726. sort_clear if respond_to?(:sort_clear)
  727. render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
  728. end
  729. # Renders a 200 response for successfull updates or deletions via the API
  730. def render_api_ok
  731. render_api_head :ok
  732. end
  733. # Renders a head API response
  734. def render_api_head(status)
  735. # #head would return a response body with one space
  736. render :text => '', :status => status, :layout => nil
  737. end
  738. # Renders API response on validation failure
  739. def render_validation_errors(objects)
  740. if objects.is_a?(Array)
  741. @error_messages = objects.map {|object| object.errors.full_messages}.flatten
  742. else
  743. @error_messages = objects.errors.full_messages
  744. end
  745. render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
  746. end
  747. # Overrides #_include_layout? so that #render with no arguments
  748. # doesn't use the layout for api requests
  749. def _include_layout?(*args)
  750. api_request? ? false : super
  751. end
  752. ## Please added code in html.
  753. # <div class="pagination"><%= pagination_links_full @obj_pages, @obj_count, :per_page_links => false %></div>
  754. def paginateHelper obj, pre_size=20
  755. @obj_count = obj.count
  756. @obj_pages = Paginator.new @obj_count, pre_size, params['page']
  757. if obj.kind_of? ActiveRecord::Base or obj.kind_of? ActiveRecord::Relation
  758. obj.limit(@obj_pages.per_page).offset(@obj_pages.offset)
  759. elsif obj.kind_of? Array
  760. obj[@obj_pages.offset, @obj_pages.per_page]
  761. else
  762. logger.error "[ApplicationController] Error : application_controller#paginateHelper ===> unknow category: #{obj.class}"
  763. raise RuntimeError, 'unknow type, Please input you type into this helper.'
  764. end
  765. end
  766. def paginateHelper_for_members obj, pre_size=10
  767. @obj_count = StudentsForCourse.find_by_sql("select count(id) as mem_count from students_for_courses where course_id = #{@course.id}")[0][:mem_count].to_s.to_i
  768. @obj_pages = Paginator.new @obj_count, pre_size, params['page']
  769. if obj.kind_of? ActiveRecord::Base or obj.kind_of? ActiveRecord::Relation
  770. obj.limit(@obj_pages.per_page).offset(0)
  771. elsif obj.kind_of? Array
  772. obj[0, @obj_pages.per_page]
  773. else
  774. logger.error "[ApplicationController] Error : application_controller#paginateHelper ===> unknow category: #{obj.class}"
  775. raise RuntimeError, 'unknow type, Please input you type into this helper.'
  776. end
  777. end
  778. #查找首页相关信息
  779. def find_first_page
  780. @first_page = FirstPage.find_by_page_type('project')
  781. if @first_page.nil?
  782. @first_page = FirstPage.new
  783. @first_page.page_type = 'project'
  784. @first_page.description = ""
  785. @first_page.save()
  786. end
  787. @show_course = @first_page.show_course
  788. @show_contest = @first_page.show_contest
  789. end
  790. def find_web_footer
  791. @organizer = WebFooterOranizer.first
  792. @companies = WebFooterCompany.all
  793. end
  794. def password_authentication
  795. user, last_login_on = User.try_to_login(params[:user_name], params[:password])
  796. successful_authentication(user, last_login_on)
  797. end
  798. def successful_authentication(user, last_login_on)
  799. logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
  800. # Valid user
  801. self.logged_user = user
  802. # generate a key and set cookie if autologin
  803. if params[:autologin] && Setting.autologin?
  804. set_autologin_cookie(user)
  805. end
  806. call_hook(:controller_account_success_authentication_after, {:user => user })
  807. end
  808. end

软件技术创新是当今国家整体创新能力的重要基础和发展引擎。近年来,大众参与的软件创新与创业活动已经成为网络时代软件开发和应用的新形态,正在快速改变着全球软件创新模式和软件产业格局。 ...