##// END OF EJS Templates
Added support for HTTP Basic access to the API. (#3920)...
Eric Davis -
r3105:e07e9d8bfed4
parent child
Show More
@@ -0,0 +1,78
1 require "#{File.dirname(__FILE__)}/../test_helper"
2
3 class HttpBasicLoginTest < ActionController::IntegrationTest
4 fixtures :all
5
6 def setup
7 Setting.login_required = '1'
8 end
9
10 def teardown
11 Setting.login_required = '0'
12 end
13
14 # Using the NewsController because it's a simple API.
15 context "get /news" do
16
17 context "in :xml format" do
18 context "with a valid HTTP authentication" do
19 setup do
20 @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password')
21 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password')
22 get "/news.xml", nil, :authorization => @authorization
23 end
24
25 should_respond_with :success
26 should_respond_with_content_type :xml
27 should "login as the user" do
28 assert_equal @user, User.current
29 end
30 end
31
32 context "with an invalid HTTP authentication" do
33 setup do
34 @user = User.generate_with_protected!
35 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'wrong_password')
36 get "/news.xml", nil, :authorization => @authorization
37 end
38
39 should_respond_with :unauthorized
40 should_respond_with_content_type :xml
41 should "not login as the user" do
42 assert_equal User.anonymous, User.current
43 end
44 end
45 end
46
47 context "in :json format" do
48 context "with a valid HTTP authentication" do
49 setup do
50 @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password')
51 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password')
52 get "/news.json", nil, :authorization => @authorization
53 end
54
55 should_respond_with :success
56 should_respond_with_content_type :json
57 should "login as the user" do
58 assert_equal @user, User.current
59 end
60 end
61
62 context "with an invalid HTTP authentication" do
63 setup do
64 @user = User.generate_with_protected!
65 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'wrong_password')
66 get "/news.json", nil, :authorization => @authorization
67 end
68
69 should_respond_with :unauthorized
70 should_respond_with_content_type :json
71 should "not login as the user" do
72 assert_equal User.anonymous, User.current
73 end
74 end
75 end
76
77 end
78 end
@@ -0,0 +1,82
1 require "#{File.dirname(__FILE__)}/../test_helper"
2
3 class HttpBasicLoginWithApiTokenTest < ActionController::IntegrationTest
4 fixtures :all
5
6 def setup
7 Setting.login_required = '1'
8 end
9
10 def teardown
11 Setting.login_required = '0'
12 end
13
14 # Using the NewsController because it's a simple API.
15 context "get /news" do
16
17 context "in :xml format" do
18 context "with a valid HTTP authentication using the API token" do
19 setup do
20 @user = User.generate_with_protected!
21 @token = Token.generate!(:user => @user, :action => 'api')
22 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X')
23 get "/news.xml", nil, :authorization => @authorization
24 end
25
26 should_respond_with :success
27 should_respond_with_content_type :xml
28 should "login as the user" do
29 assert_equal @user, User.current
30 end
31 end
32
33 context "with an invalid HTTP authentication" do
34 setup do
35 @user = User.generate_with_protected!
36 @token = Token.generate!(:user => @user, :action => 'feeds')
37 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X')
38 get "/news.xml", nil, :authorization => @authorization
39 end
40
41 should_respond_with :unauthorized
42 should_respond_with_content_type :xml
43 should "not login as the user" do
44 assert_equal User.anonymous, User.current
45 end
46 end
47 end
48
49 context "in :json format" do
50 context "with a valid HTTP authentication" do
51 setup do
52 @user = User.generate_with_protected!
53 @token = Token.generate!(:user => @user, :action => 'api')
54 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'DoesNotMatter')
55 get "/news.json", nil, :authorization => @authorization
56 end
57
58 should_respond_with :success
59 should_respond_with_content_type :json
60 should "login as the user" do
61 assert_equal @user, User.current
62 end
63 end
64
65 context "with an invalid HTTP authentication" do
66 setup do
67 @user = User.generate_with_protected!
68 @token = Token.generate!(:user => @user, :action => 'feeds')
69 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'DoesNotMatter')
70 get "/news.json", nil, :authorization => @authorization
71 end
72
73 should_respond_with :unauthorized
74 should_respond_with_content_type :json
75 should "not login as the user" do
76 assert_equal User.anonymous, User.current
77 end
78 end
79 end
80
81 end
82 end
@@ -1,284 +1,293
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])
73 elsif ['xml', 'json'].include?(params[:format]) && accept_key_auth_actions.include?(params[:action])
74 if params[:key].present?
75 # Use API key
74 76 User.find_by_api_key(params[:key])
77 else
78 # HTTP Basic, either username/password or API key/random
79 authenticate_with_http_basic do |username, password|
80 User.try_to_login(username, password) || User.find_by_api_key(username)
81 end
82 end
75 83 end
76 84 end
77 85
78 86 # Sets the logged in user
79 87 def logged_user=(user)
80 88 reset_session
81 89 if user && user.is_a?(User)
82 90 User.current = user
83 91 session[:user_id] = user.id
84 92 else
85 93 User.current = User.anonymous
86 94 end
87 95 end
88 96
89 97 # check if login is globally required to access the application
90 98 def check_if_login_required
91 99 # no check needed if user is already logged in
92 100 return true if User.current.logged?
93 101 require_login if Setting.login_required?
94 102 end
95 103
96 104 def set_localization
97 105 lang = nil
98 106 if User.current.logged?
99 107 lang = find_language(User.current.language)
100 108 end
101 109 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
102 110 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first.downcase
103 111 if !accept_lang.blank?
104 112 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
105 113 end
106 114 end
107 115 lang ||= Setting.default_language
108 116 set_language_if_valid(lang)
109 117 end
110 118
111 119 def require_login
112 120 if !User.current.logged?
113 121 # Extract only the basic url parameters on non-GET requests
114 122 if request.get?
115 123 url = url_for(params)
116 124 else
117 125 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
118 126 end
119 127 respond_to do |format|
120 128 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
129 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
121 130 format.xml { head :unauthorized }
122 131 format.json { head :unauthorized }
123 132 end
124 133 return false
125 134 end
126 135 true
127 136 end
128 137
129 138 def require_admin
130 139 return unless require_login
131 140 if !User.current.admin?
132 141 render_403
133 142 return false
134 143 end
135 144 true
136 145 end
137 146
138 147 def deny_access
139 148 User.current.logged? ? render_403 : require_login
140 149 end
141 150
142 151 # Authorize the user for the requested action
143 152 def authorize(ctrl = params[:controller], action = params[:action], global = false)
144 153 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project, :global => global)
145 154 allowed ? true : deny_access
146 155 end
147 156
148 157 # Authorize the user for the requested action outside a project
149 158 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
150 159 authorize(ctrl, action, global)
151 160 end
152 161
153 162 # make sure that the user is a member of the project (or admin) if project is private
154 163 # used as a before_filter for actions that do not require any particular permission on the project
155 164 def check_project_privacy
156 165 if @project && @project.active?
157 166 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
158 167 true
159 168 else
160 169 User.current.logged? ? render_403 : require_login
161 170 end
162 171 else
163 172 @project = nil
164 173 render_404
165 174 false
166 175 end
167 176 end
168 177
169 178 def redirect_back_or_default(default)
170 179 back_url = CGI.unescape(params[:back_url].to_s)
171 180 if !back_url.blank?
172 181 begin
173 182 uri = URI.parse(back_url)
174 183 # do not redirect user to another host or to the login or register page
175 184 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
176 185 redirect_to(back_url)
177 186 return
178 187 end
179 188 rescue URI::InvalidURIError
180 189 # redirect to default
181 190 end
182 191 end
183 192 redirect_to default
184 193 end
185 194
186 195 def render_403
187 196 @project = nil
188 197 render :template => "common/403", :layout => (request.xhr? ? false : 'base'), :status => 403
189 198 return false
190 199 end
191 200
192 201 def render_404
193 202 render :template => "common/404", :layout => !request.xhr?, :status => 404
194 203 return false
195 204 end
196 205
197 206 def render_error(msg)
198 207 flash.now[:error] = msg
199 208 render :text => '', :layout => !request.xhr?, :status => 500
200 209 end
201 210
202 211 def invalid_authenticity_token
203 212 render_error "Invalid form authenticity token."
204 213 end
205 214
206 215 def render_feed(items, options={})
207 216 @items = items || []
208 217 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
209 218 @items = @items.slice(0, Setting.feeds_limit.to_i)
210 219 @title = options[:title] || Setting.app_title
211 220 render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml'
212 221 end
213 222
214 223 def self.accept_key_auth(*actions)
215 224 actions = actions.flatten.map(&:to_s)
216 225 write_inheritable_attribute('accept_key_auth_actions', actions)
217 226 end
218 227
219 228 def accept_key_auth_actions
220 229 self.class.read_inheritable_attribute('accept_key_auth_actions') || []
221 230 end
222 231
223 232 # TODO: move to model
224 233 def attach_files(obj, attachments)
225 234 attached = []
226 235 unsaved = []
227 236 if attachments && attachments.is_a?(Hash)
228 237 attachments.each_value do |attachment|
229 238 file = attachment['file']
230 239 next unless file && file.size > 0
231 240 a = Attachment.create(:container => obj,
232 241 :file => file,
233 242 :description => attachment['description'].to_s.strip,
234 243 :author => User.current)
235 244 a.new_record? ? (unsaved << a) : (attached << a)
236 245 end
237 246 if unsaved.any?
238 247 flash[:warning] = l(:warning_attachments_not_saved, unsaved.size)
239 248 end
240 249 end
241 250 attached
242 251 end
243 252
244 253 # Returns the number of objects that should be displayed
245 254 # on the paginated list
246 255 def per_page_option
247 256 per_page = nil
248 257 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
249 258 per_page = params[:per_page].to_s.to_i
250 259 session[:per_page] = per_page
251 260 elsif session[:per_page]
252 261 per_page = session[:per_page]
253 262 else
254 263 per_page = Setting.per_page_options_array.first || 25
255 264 end
256 265 per_page
257 266 end
258 267
259 268 # qvalues http header parser
260 269 # code taken from webrick
261 270 def parse_qvalues(value)
262 271 tmp = []
263 272 if value
264 273 parts = value.split(/,\s*/)
265 274 parts.each {|part|
266 275 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
267 276 val = m[1]
268 277 q = (m[2] or 1).to_f
269 278 tmp.push([val, q])
270 279 end
271 280 }
272 281 tmp = tmp.sort_by{|val, q| -q}
273 282 tmp.collect!{|val, q| val}
274 283 end
275 284 return tmp
276 285 rescue
277 286 nil
278 287 end
279 288
280 289 # Returns a string that can be used as filename value in Content-Disposition header
281 290 def filename_for_content_disposition(name)
282 291 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
283 292 end
284 293 end
@@ -1,73 +1,78
1 1 require "#{File.dirname(__FILE__)}/../test_helper"
2 2
3 3 class ApiTokenLoginTest < ActionController::IntegrationTest
4 4 fixtures :all
5 5
6 def setup
7 Setting.login_required = '1'
8 end
9
10 def teardown
11 Setting.login_required = '0'
12 end
13
6 14 # Using the NewsController because it's a simple API.
7 context "get /news.xml" do
15 context "get /news" do
8 16
9 17 context "in :xml format" do
10 18 context "with a valid api token" do
11 19 setup do
12 20 @user = User.generate_with_protected!
13 21 @token = Token.generate!(:user => @user, :action => 'api')
14 22 get "/news.xml?key=#{@token.value}"
15 23 end
16 24
17 25 should_respond_with :success
18 26 should_respond_with_content_type :xml
19 27 should "login as the user" do
20 28 assert_equal @user, User.current
21 29 end
22 30 end
23 31
24 context "with an invalid api token (on a protected site)" do
32 context "with an invalid api token" do
25 33 setup do
26 Setting.login_required = '1'
27 34 @user = User.generate_with_protected!
28 35 @token = Token.generate!(:user => @user, :action => 'feeds')
29 36 get "/news.xml?key=#{@token.value}"
30 37 end
31 38
32 39 should_respond_with :unauthorized
33 40 should_respond_with_content_type :xml
34 41 should "not login as the user" do
35 42 assert_equal User.anonymous, User.current
36 43 end
37 44 end
38 45 end
39 46
40 47 context "in :json format" do
41 48 context "with a valid api token" do
42 49 setup do
43 50 @user = User.generate_with_protected!
44 51 @token = Token.generate!(:user => @user, :action => 'api')
45 52 get "/news.json?key=#{@token.value}"
46 53 end
47 54
48 55 should_respond_with :success
49 56 should_respond_with_content_type :json
50 57 should "login as the user" do
51 58 assert_equal @user, User.current
52 59 end
53 60 end
54 61
55 context "with an invalid api token (on a protected site)" do
62 context "with an invalid api token" do
56 63 setup do
57 Setting.login_required = '1'
58 64 @user = User.generate_with_protected!
59 65 @token = Token.generate!(:user => @user, :action => 'feeds')
60 66 get "/news.json?key=#{@token.value}"
61 67 end
62 68
63 69 should_respond_with :unauthorized
64 70 should_respond_with_content_type :json
65 71 should "not login as the user" do
66 72 assert_equal User.anonymous, User.current
67 73 end
68 74 end
69 75 end
70 76
71 77 end
72
73 78 end
General Comments 0
You need to be logged in to leave comments. Login now