##// END OF EJS Templates
Allow authenticating with an API token via XML or JSON. (#3920)...
Eric Davis -
r3104:baa1ad42560f
parent child
Show More
@@ -0,0 +1,73
1 require "#{File.dirname(__FILE__)}/../test_helper"
2
3 class ApiTokenLoginTest < ActionController::IntegrationTest
4 fixtures :all
5
6 # Using the NewsController because it's a simple API.
7 context "get /news.xml" do
8
9 context "in :xml format" do
10 context "with a valid api token" do
11 setup do
12 @user = User.generate_with_protected!
13 @token = Token.generate!(:user => @user, :action => 'api')
14 get "/news.xml?key=#{@token.value}"
15 end
16
17 should_respond_with :success
18 should_respond_with_content_type :xml
19 should "login as the user" do
20 assert_equal @user, User.current
21 end
22 end
23
24 context "with an invalid api token (on a protected site)" do
25 setup do
26 Setting.login_required = '1'
27 @user = User.generate_with_protected!
28 @token = Token.generate!(:user => @user, :action => 'feeds')
29 get "/news.xml?key=#{@token.value}"
30 end
31
32 should_respond_with :unauthorized
33 should_respond_with_content_type :xml
34 should "not login as the user" do
35 assert_equal User.anonymous, User.current
36 end
37 end
38 end
39
40 context "in :json format" do
41 context "with a valid api token" do
42 setup do
43 @user = User.generate_with_protected!
44 @token = Token.generate!(:user => @user, :action => 'api')
45 get "/news.json?key=#{@token.value}"
46 end
47
48 should_respond_with :success
49 should_respond_with_content_type :json
50 should "login as the user" do
51 assert_equal @user, User.current
52 end
53 end
54
55 context "with an invalid api token (on a protected site)" do
56 setup do
57 Setting.login_required = '1'
58 @user = User.generate_with_protected!
59 @token = Token.generate!(:user => @user, :action => 'feeds')
60 get "/news.json?key=#{@token.value}"
61 end
62
63 should_respond_with :unauthorized
64 should_respond_with_content_type :json
65 should "not login as the user" do
66 assert_equal User.anonymous, User.current
67 end
68 end
69 end
70
71 end
72
73 end
@@ -1,278 +1,284
1 1 # redMine - project management software
2 2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require 'uri'
19 19 require 'cgi'
20 20
21 21 class ApplicationController < ActionController::Base
22 22 include Redmine::I18n
23 23
24 24 layout 'base'
25 25
26 26 # Remove broken cookie after upgrade from 0.8.x (#4292)
27 27 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
28 28 # TODO: remove it when Rails is fixed
29 29 before_filter :delete_broken_cookies
30 30 def delete_broken_cookies
31 31 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
32 32 cookies.delete '_redmine_session'
33 33 redirect_to home_path
34 34 return false
35 35 end
36 36 end
37 37
38 38 before_filter :user_setup, :check_if_login_required, :set_localization
39 39 filter_parameter_logging :password
40 40 protect_from_forgery
41 41
42 42 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
43 43
44 44 include Redmine::Search::Controller
45 45 include Redmine::MenuManager::MenuController
46 46 helper Redmine::MenuManager::MenuHelper
47 47
48 48 REDMINE_SUPPORTED_SCM.each do |scm|
49 49 require_dependency "repository/#{scm.underscore}"
50 50 end
51 51
52 52 def user_setup
53 53 # Check the settings cache for each request
54 54 Setting.check_cache
55 55 # Find the current user
56 56 User.current = find_current_user
57 57 end
58 58
59 59 # Returns the current user or nil if no user is logged in
60 60 # and starts a session if needed
61 61 def find_current_user
62 62 if session[:user_id]
63 63 # existing session
64 64 (User.active.find(session[:user_id]) rescue nil)
65 65 elsif cookies[:autologin] && Setting.autologin?
66 66 # auto-login feature starts a new session
67 67 user = User.try_to_autologin(cookies[:autologin])
68 68 session[:user_id] = user.id if user
69 69 user
70 70 elsif params[:format] == 'atom' && params[:key] && accept_key_auth_actions.include?(params[:action])
71 71 # RSS key authentication does not start a session
72 72 User.find_by_rss_key(params[:key])
73 elsif ['xml', 'json'].include?(params[:format]) && params[:key] && accept_key_auth_actions.include?(params[:action])
74 User.find_by_api_key(params[:key])
73 75 end
74 76 end
75 77
76 78 # Sets the logged in user
77 79 def logged_user=(user)
78 80 reset_session
79 81 if user && user.is_a?(User)
80 82 User.current = user
81 83 session[:user_id] = user.id
82 84 else
83 85 User.current = User.anonymous
84 86 end
85 87 end
86 88
87 89 # check if login is globally required to access the application
88 90 def check_if_login_required
89 91 # no check needed if user is already logged in
90 92 return true if User.current.logged?
91 93 require_login if Setting.login_required?
92 94 end
93 95
94 96 def set_localization
95 97 lang = nil
96 98 if User.current.logged?
97 99 lang = find_language(User.current.language)
98 100 end
99 101 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
100 102 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first.downcase
101 103 if !accept_lang.blank?
102 104 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
103 105 end
104 106 end
105 107 lang ||= Setting.default_language
106 108 set_language_if_valid(lang)
107 109 end
108 110
109 111 def require_login
110 112 if !User.current.logged?
111 113 # Extract only the basic url parameters on non-GET requests
112 114 if request.get?
113 115 url = url_for(params)
114 116 else
115 117 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
116 118 end
117 redirect_to :controller => "account", :action => "login", :back_url => url
119 respond_to do |format|
120 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
121 format.xml { head :unauthorized }
122 format.json { head :unauthorized }
123 end
118 124 return false
119 125 end
120 126 true
121 127 end
122 128
123 129 def require_admin
124 130 return unless require_login
125 131 if !User.current.admin?
126 132 render_403
127 133 return false
128 134 end
129 135 true
130 136 end
131 137
132 138 def deny_access
133 139 User.current.logged? ? render_403 : require_login
134 140 end
135 141
136 142 # Authorize the user for the requested action
137 143 def authorize(ctrl = params[:controller], action = params[:action], global = false)
138 144 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project, :global => global)
139 145 allowed ? true : deny_access
140 146 end
141 147
142 148 # Authorize the user for the requested action outside a project
143 149 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
144 150 authorize(ctrl, action, global)
145 151 end
146 152
147 153 # make sure that the user is a member of the project (or admin) if project is private
148 154 # used as a before_filter for actions that do not require any particular permission on the project
149 155 def check_project_privacy
150 156 if @project && @project.active?
151 157 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
152 158 true
153 159 else
154 160 User.current.logged? ? render_403 : require_login
155 161 end
156 162 else
157 163 @project = nil
158 164 render_404
159 165 false
160 166 end
161 167 end
162 168
163 169 def redirect_back_or_default(default)
164 170 back_url = CGI.unescape(params[:back_url].to_s)
165 171 if !back_url.blank?
166 172 begin
167 173 uri = URI.parse(back_url)
168 174 # do not redirect user to another host or to the login or register page
169 175 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
170 176 redirect_to(back_url)
171 177 return
172 178 end
173 179 rescue URI::InvalidURIError
174 180 # redirect to default
175 181 end
176 182 end
177 183 redirect_to default
178 184 end
179 185
180 186 def render_403
181 187 @project = nil
182 188 render :template => "common/403", :layout => (request.xhr? ? false : 'base'), :status => 403
183 189 return false
184 190 end
185 191
186 192 def render_404
187 193 render :template => "common/404", :layout => !request.xhr?, :status => 404
188 194 return false
189 195 end
190 196
191 197 def render_error(msg)
192 198 flash.now[:error] = msg
193 199 render :text => '', :layout => !request.xhr?, :status => 500
194 200 end
195 201
196 202 def invalid_authenticity_token
197 203 render_error "Invalid form authenticity token."
198 204 end
199 205
200 206 def render_feed(items, options={})
201 207 @items = items || []
202 208 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
203 209 @items = @items.slice(0, Setting.feeds_limit.to_i)
204 210 @title = options[:title] || Setting.app_title
205 211 render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml'
206 212 end
207 213
208 214 def self.accept_key_auth(*actions)
209 215 actions = actions.flatten.map(&:to_s)
210 216 write_inheritable_attribute('accept_key_auth_actions', actions)
211 217 end
212 218
213 219 def accept_key_auth_actions
214 220 self.class.read_inheritable_attribute('accept_key_auth_actions') || []
215 221 end
216 222
217 223 # TODO: move to model
218 224 def attach_files(obj, attachments)
219 225 attached = []
220 226 unsaved = []
221 227 if attachments && attachments.is_a?(Hash)
222 228 attachments.each_value do |attachment|
223 229 file = attachment['file']
224 230 next unless file && file.size > 0
225 231 a = Attachment.create(:container => obj,
226 232 :file => file,
227 233 :description => attachment['description'].to_s.strip,
228 234 :author => User.current)
229 235 a.new_record? ? (unsaved << a) : (attached << a)
230 236 end
231 237 if unsaved.any?
232 238 flash[:warning] = l(:warning_attachments_not_saved, unsaved.size)
233 239 end
234 240 end
235 241 attached
236 242 end
237 243
238 244 # Returns the number of objects that should be displayed
239 245 # on the paginated list
240 246 def per_page_option
241 247 per_page = nil
242 248 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
243 249 per_page = params[:per_page].to_s.to_i
244 250 session[:per_page] = per_page
245 251 elsif session[:per_page]
246 252 per_page = session[:per_page]
247 253 else
248 254 per_page = Setting.per_page_options_array.first || 25
249 255 end
250 256 per_page
251 257 end
252 258
253 259 # qvalues http header parser
254 260 # code taken from webrick
255 261 def parse_qvalues(value)
256 262 tmp = []
257 263 if value
258 264 parts = value.split(/,\s*/)
259 265 parts.each {|part|
260 266 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
261 267 val = m[1]
262 268 q = (m[2] or 1).to_f
263 269 tmp.push([val, q])
264 270 end
265 271 }
266 272 tmp = tmp.sort_by{|val, q| -q}
267 273 tmp.collect!{|val, q| val}
268 274 end
269 275 return tmp
270 276 rescue
271 277 nil
272 278 end
273 279
274 280 # Returns a string that can be used as filename value in Content-Disposition header
275 281 def filename_for_content_disposition(name)
276 282 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
277 283 end
278 284 end
@@ -1,109 +1,111
1 1 # redMine - project management software
2 2 # Copyright (C) 2006 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class NewsController < ApplicationController
19 19 default_search_scope :news
20 20 before_filter :find_news, :except => [:new, :index, :preview]
21 21 before_filter :find_project, :only => [:new, :preview]
22 22 before_filter :authorize, :except => [:index, :preview]
23 23 before_filter :find_optional_project, :only => :index
24 24 accept_key_auth :index
25 25
26 26 def index
27 27 @news_pages, @newss = paginate :news,
28 28 :per_page => 10,
29 29 :conditions => Project.allowed_to_condition(User.current, :view_news, :project => @project),
30 30 :include => [:author, :project],
31 31 :order => "#{News.table_name}.created_on DESC"
32 32 respond_to do |format|
33 33 format.html { render :layout => false if request.xhr? }
34 format.xml { render :xml => @newss.to_xml }
35 format.json { render :json => @newss.to_json }
34 36 format.atom { render_feed(@newss, :title => (@project ? @project.name : Setting.app_title) + ": #{l(:label_news_plural)}") }
35 37 end
36 38 end
37 39
38 40 def show
39 41 @comments = @news.comments
40 42 @comments.reverse! if User.current.wants_comments_in_reverse_order?
41 43 end
42 44
43 45 def new
44 46 @news = News.new(:project => @project, :author => User.current)
45 47 if request.post?
46 48 @news.attributes = params[:news]
47 49 if @news.save
48 50 flash[:notice] = l(:notice_successful_create)
49 51 redirect_to :controller => 'news', :action => 'index', :project_id => @project
50 52 end
51 53 end
52 54 end
53 55
54 56 def edit
55 57 if request.post? and @news.update_attributes(params[:news])
56 58 flash[:notice] = l(:notice_successful_update)
57 59 redirect_to :action => 'show', :id => @news
58 60 end
59 61 end
60 62
61 63 def add_comment
62 64 @comment = Comment.new(params[:comment])
63 65 @comment.author = User.current
64 66 if @news.comments << @comment
65 67 flash[:notice] = l(:label_comment_added)
66 68 redirect_to :action => 'show', :id => @news
67 69 else
68 70 show
69 71 render :action => 'show'
70 72 end
71 73 end
72 74
73 75 def destroy_comment
74 76 @news.comments.find(params[:comment_id]).destroy
75 77 redirect_to :action => 'show', :id => @news
76 78 end
77 79
78 80 def destroy
79 81 @news.destroy
80 82 redirect_to :action => 'index', :project_id => @project
81 83 end
82 84
83 85 def preview
84 86 @text = (params[:news] ? params[:news][:description] : nil)
85 87 render :partial => 'common/preview'
86 88 end
87 89
88 90 private
89 91 def find_news
90 92 @news = News.find(params[:id])
91 93 @project = @news.project
92 94 rescue ActiveRecord::RecordNotFound
93 95 render_404
94 96 end
95 97
96 98 def find_project
97 99 @project = Project.find(params[:project_id])
98 100 rescue ActiveRecord::RecordNotFound
99 101 render_404
100 102 end
101 103
102 104 def find_optional_project
103 105 return true unless params[:project_id]
104 106 @project = Project.find(params[:project_id])
105 107 authorize
106 108 rescue ActiveRecord::RecordNotFound
107 109 render_404
108 110 end
109 111 end
General Comments 0
You need to be logged in to leave comments. Login now