]> git.openstreetmap.org Git - rails.git/blob - app/controllers/user_controller.rb
merge 19889:20181 of rails_port into the openID branch
[rails.git] / app / controllers / user_controller.rb
1 class UserController < ApplicationController
2   layout 'site', :except => :api_details
3
4   before_filter :authorize, :only => [:api_details, :api_gpx_files]
5   before_filter :authorize_web, :except => [:api_details, :api_gpx_files]
6   before_filter :set_locale, :except => [:api_details, :api_gpx_files]
7   before_filter :require_user, :only => [:account, :go_public, :make_friend, :remove_friend]
8   before_filter :check_database_readable, :except => [:api_details, :api_gpx_files]
9   before_filter :check_database_writable, :only => [:login, :new, :account, :go_public, :make_friend, :remove_friend]
10   before_filter :check_api_readable, :only => [:api_details, :api_gpx_files]
11   before_filter :require_allow_read_prefs, :only => [:api_details]
12   before_filter :require_allow_read_gpx, :only => [:api_gpx_files]
13   before_filter :require_cookies, :only => [:login, :confirm]
14   before_filter :require_administrator, :only => [:activate, :deactivate, :hide, :unhide, :delete]
15   before_filter :lookup_this_user, :only => [:activate, :deactivate, :hide, :unhide, :delete]
16
17   filter_parameter_logging :password, :pass_crypt, :pass_crypt_confirmation
18
19   cache_sweeper :user_sweeper, :only => [:account, :hide, :unhide, :delete]
20
21   def save
22     @title = t 'user.new.title'
23
24     if Acl.find_by_address(request.remote_ip, :conditions => {:k => "no_account_creation"})
25       render :action => 'new'
26     else
27           #The redirect from the OpenID provider reenters here again 
28       #and we need to pass the parameters through to the  
29       #open_id_authentication function a second time 
30       if params[:open_id_complete] 
31         openid_verify('', true) 
32         #We have set the user.openid_url to nil beforehand. If it hasn't 
33         #been set to a new valid openid_url, it means the openid couldn't be validated 
34         if @user.nil? or @user.openid_url.nil? 
35           render :action => 'new' 
36           return 
37         end   
38       else
39       @user = User.new(params[:user])
40
41       @user.visible = true
42       @user.data_public = true
43       @user.description = "" if @user.description.nil?
44       @user.creation_ip = request.remote_ip
45       @user.languages = request.user_preferred_languages
46         #Set the openid_url to nil as for one it is used 
47         #to check if the openid could be validated and secondly 
48         #to not get dupplicate conflicts for an empty openid  
49         @user.openid_url = nil
50
51 if (!params[:user][:openid_url].nil? and params[:user][:openid_url].length > 0)
52                   if @user.pass_crypt.length == 0 
53             #if the password is empty, but we have a openid 
54             #then generate a random passowrd to disable 
55             #loging in via password 
56             @user.pass_crypt = ActiveSupport::SecureRandom.base64(16) 
57             @user.pass_crypt_confirmation = @user.pass_crypt 
58           end
59                   #Validate all of the other fields before
60                   #redirecting to the openid provider
61                   if !@user.valid?
62                         render :action => 'new'
63                   else            
64                         #TODO: Is it a problem to store the user variable with respect to password safty in the session variables?
65                         #Store the user variable in the session for it to be accessible when redirecting back from the openid provider
66                         session[:new_usr] = @user
67                         begin
68                           @norm_openid_url = OpenIdAuthentication.normalize_identifier(params[:user][:openid_url])
69                         rescue
70                           flash.now[:error] = t 'user.login.openid invalid'
71                           render :action => 'new'
72                           return
73                         end
74                         #Verify that the openid provided is valid and that the user is the owner of the id
75                         openid_verify(@norm_openid_url, true)
76                         #openid_verify can return in two ways:
77                         #Either it returns with a redirect to the openid provider who then freshly
78                         #redirects back to this url if the openid is valid, or if the openid is not plausible
79                         #and no provider for it could be found it just returns
80                         #we want to just let the redirect through
81                         if response.headers["Location"].nil?
82                           render :action => 'new'
83                         end
84                   end
85                   #At this point there was either an error and the page has been rendered,
86                   #or there is a redirect to the openid provider and the rest of the method
87                   #gets executed whenn this method gets reentered after redirecting back
88                   #from the openid provider
89                   return
90                 end
91           end
92
93       if @user.save
94         flash[:notice] = t 'user.new.flash create success message'
95         Notifier.deliver_signup_confirm(@user, @user.tokens.create(:referer => params[:referer]))
96         redirect_to :action => 'login'
97       else
98         render :action => 'new'
99       end
100     end
101   end
102
103   def account
104     @title = t 'user.account.title'
105     @tokens = @user.oauth_tokens.find :all, :conditions => 'oauth_tokens.invalidated_at is null and oauth_tokens.authorized_at is not null'
106
107         #The redirect from the OpenID provider reenters here again
108     #and we need to pass the parameters through to the 
109     #open_id_authentication function
110     if params[:open_id_complete]
111       openid_verify('', false)
112           @user.save
113       return
114     end
115
116     if params[:user] and params[:user][:display_name] and params[:user][:description]
117       @user.display_name = params[:user][:display_name]
118       @user.new_email = params[:user][:new_email]
119
120       if params[:user][:pass_crypt].length > 0 or params[:user][:pass_crypt_confirmation].length > 0
121         @user.pass_crypt = params[:user][:pass_crypt]
122         @user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
123       end
124
125       @user.description = params[:user][:description]
126       @user.languages = params[:user][:languages].split(",")
127
128       case params[:image_action]
129         when "new" then @user.image = params[:user][:image]
130         when "delete" then @user.image = nil
131       end
132
133       @user.home_lat = params[:user][:home_lat]
134       @user.home_lon = params[:user][:home_lon]
135
136       if @user.save
137         set_locale
138
139         if @user.new_email.nil? or @user.new_email.empty?
140           flash.now[:notice] = t 'user.account.flash update success'
141         else
142           flash.now[:notice] = t 'user.account.flash update success confirm needed'
143
144           begin
145             Notifier.deliver_email_confirm(@user, @user.tokens.create)
146           rescue
147             # Ignore errors sending email
148           end
149         end
150       end
151
152           if (params[:user][:openid_url].length > 0)
153                 begin
154                   @norm_openid_url = OpenIdAuthentication.normalize_identifier(params[:user][:openid_url])
155                   if (@norm_openid_url != @user.openid_url)
156                         #If the OpenID has changed, we want to check that it is a valid OpenID and one
157                         #the user has control over before saving the openID as a password equivalent for
158                         #the user.
159                         openid_verify(@norm_openid_url, false)
160                   end
161                 rescue
162                   flash.now[:error] = t 'user.login.openid invalid'
163                 end
164       end
165
166     else
167       if flash[:errors]
168         flash[:errors].each do |attr,msg|
169           attr = "new_email" if attr == "email"
170           @user.errors.add(attr,msg)
171         end
172       end
173     end
174   end
175
176   def openid_specialcase_mapping(openid_url)
177     #Special case gmail.com, as it is pontentially a popular OpenID provider and unlike
178     #yahoo.com, where it works automatically, Google have hidden their OpenID endpoint
179     #somewhere obscure making it less userfriendly.
180     if (openid_url.match(/(.*)gmail.com(\/?)$/) or openid_url.match(/(.*)googlemail.com(\/?)$/) )
181       return 'https://www.google.com/accounts/o8/id'
182     end
183
184     return nil
185   end  
186
187   def openid_verify(openid_url,account_create)
188     authenticate_with_open_id(openid_url) do |result, identity_url|
189       if result.successful?
190         #We need to use the openid url passed back from the OpenID provider
191         #rather than the one supplied by the user, as these can be different.
192         #e.g. one can simply enter yahoo.com in the login box, i.e. no user specific url
193         #only once it comes back from the OpenID provider do we know the unique address for
194         #the user.
195                 @user = session[:new_usr] unless @user #this is used for account creation when the user is not yet in the database
196         @user.openid_url = identity_url
197           elsif result.missing?
198                 mapped_id = openid_specialcase_mapping(openid_url)
199                 if mapped_id
200                   openid_verify(mapped_id, account_create)
201                 else
202                   flash.now[:error] = t 'user.login.openid missing provider'
203                 end
204           elsif result.invalid?
205                 flash.now[:error] = t 'user.login.openid invalid'
206           else
207                 flash.now[:error] = t 'user.login.auth failure'
208           end
209     end
210   end
211
212   def open_id_authentication(openid_url)
213     #TODO: only ask for nickname and email, if we don't already have a user for that openID, in which case
214     #email and nickname are already filled out. I don't know how to do that with ruby syntax though, as we
215     #don't want to duplicate the do block
216     #On the other hand it also doesn't matter too much if we ask every time, as the OpenID provider should
217     #remember these results, and shouldn't repromt the user for these data each time.
218     authenticate_with_open_id(openid_url, :return_to => request.protocol + request.host_with_port + '/login?referer=' + params[:referer], :optional => [:nickname, :email]) do |result, identity_url, registration|
219       if result.successful?
220         #We need to use the openid url passed back from the OpenID provider
221         #rather than the one supplied by the user, as these can be different.
222         #e.g. one can simply enter yahoo.com in the login box, i.e. no user specific url
223         #only once it comes back from the OpenID provider do we know the unique address for
224         #the user.
225         user = User.find_by_openid_url(identity_url)
226         if user
227           if user.visible? and user.active?
228             session[:user] = user.id
229                         session_expires_after 1.month if session[:remember]
230           else
231             user = nil
232             flash.now[:error] = t 'user.login.account not active'
233           end
234         else
235           #We don't have a user registered to this OpenID. Redirect to the create account page
236           #with username and email filled in if they have been given by the OpenID provider through
237           #the simple registration protocol
238           redirect_to :controller => 'user', :action => 'new', :nickname => registration['nickname'], :email => registration['email'], :openid => identity_url
239         end
240       else if result.missing?
241              #Try and apply some heuristics to make common cases more userfriendly
242              mapped_id = openid_specialcase_mapping(openid_url)
243              if mapped_id
244                open_id_authentication(mapped_id)
245              else
246                flash.now[:error] = t 'user.login.openid missing provider'
247              end
248            else if result.invalid?
249                   flash.now[:error] = t 'user.login.openid invalid'
250                 else
251                   flash.now[:error] = t 'user.login.auth failure'
252                 end
253            end
254       end
255     end
256   end
257
258   def go_public
259     @user.data_public = true
260     @user.save
261     flash[:notice] = t 'user.go_public.flash success'
262     redirect_to :controller => 'user', :action => 'account', :display_name => @user.display_name
263   end
264
265   def lost_password
266     @title = t 'user.lost_password.title'
267
268     if params[:user] and params[:user][:email]
269       user = User.find_by_email(params[:user][:email], :conditions => {:visible => true})
270
271       if user
272         token = user.tokens.create
273         Notifier.deliver_lost_password(user, token)
274         flash[:notice] = t 'user.lost_password.notice email on way'
275         redirect_to :action => 'login'
276       else
277         flash.now[:error] = t 'user.lost_password.notice email cannot find'
278       end
279     end
280   end
281
282   def reset_password
283     @title = t 'user.reset_password.title'
284
285     if params[:token]
286       token = UserToken.find_by_token(params[:token])
287
288       if token
289         @user = token.user
290
291         if params[:user]
292           @user.pass_crypt = params[:user][:pass_crypt]
293           @user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
294           @user.active = true
295           @user.email_valid = true
296
297           if @user.save
298             token.destroy
299             flash[:notice] = t 'user.reset_password.flash changed'
300             redirect_to :action => 'login'
301           end
302         end
303       else
304         flash[:error] = t 'user.reset_password.flash token bad'
305         redirect_to :action => 'lost_password'
306       end
307     end
308   end
309
310   def new
311     @title = t 'user.new.title'
312
313     # The user is logged in already, so don't show them the signup page, instead
314     # send them to the home page
315     redirect_to :controller => 'site', :action => 'index' if session[:user]
316
317         @nickname = params['nickname']
318     @email = params['email']
319         @openID = params['openid']
320   end
321
322   def login
323
324         #The redirect from the OpenID provider reenters here again
325     #and we need to pass the parameters through to the 
326     # open_id_authentication function
327     if params[:open_id_complete]
328       open_id_authentication('')
329     end
330
331     if params[:user] and session[:user].nil?
332           if !params[:user][:openid_url].nil? and !params[:user][:openid_url].empty?
333                 session[:remember] = params[:remember_me]
334         open_id_authentication(params[:user][:openid_url])
335       else
336                 email_or_display_name = params[:user][:email]
337                 pass = params[:user][:password]
338                 user = User.authenticate(:username => email_or_display_name, :password => pass)
339                 if user
340                   session[:user] = user.id
341                   session_expires_after 1.month if params[:remember_me]
342                 elsif User.authenticate(:username => email_or_display_name, :password => pass, :inactive => true)
343                   flash.now[:error] = t 'user.login.account not active'
344                 else
345                   flash.now[:error] = t 'user.login.auth failure'
346                 end
347           end
348     end
349
350     if session[:user]
351       # The user is logged in, if the referer param exists, redirect them to that
352       # unless they've also got a block on them, in which case redirect them to
353       # the block so they can clear it.
354       user = User.find(session[:user])
355       block = user.blocked_on_view
356       if block
357         redirect_to block, :referrer => params[:referrer]
358       elsif params[:referer]
359         redirect_to params[:referer]
360       else
361         redirect_to :controller => 'site', :action => 'index'
362       end
363       return
364     end
365
366     @title = t 'user.login.title'
367   end
368
369   def logout
370     if session[:token]
371       token = UserToken.find_by_token(session[:token])
372       if token
373         token.destroy
374       end
375       session[:token] = nil
376     end
377     session[:user] = nil
378     session_expires_automatically
379     if params[:referer]
380       redirect_to params[:referer]
381     else
382       redirect_to :controller => 'site', :action => 'index'
383     end
384   end
385
386   def confirm
387     if params[:confirm_action]
388       token = UserToken.find_by_token(params[:confirm_string])
389       if token and !token.user.active?
390         @user = token.user
391         @user.active = true
392         @user.email_valid = true
393         @user.save!
394         referer = token.referer
395         token.destroy
396         flash[:notice] = t 'user.confirm.success'
397         session[:user] = @user.id
398         unless referer.nil?
399           redirect_to referer
400         else
401           redirect_to :action => 'account', :display_name => @user.display_name
402         end
403       else
404         flash.now[:error] = t 'user.confirm.failure'
405       end
406     end
407   end
408
409   def confirm_email
410     if params[:confirm_action]
411       token = UserToken.find_by_token(params[:confirm_string])
412       if token and token.user.new_email?
413         @user = token.user
414         @user.email = @user.new_email
415         @user.new_email = nil
416         @user.active = true
417         @user.email_valid = true
418         if @user.save
419           flash[:notice] = t 'user.confirm_email.success'
420         else
421           flash[:errors] = @user.errors
422         end
423         token.destroy
424         session[:user] = @user.id
425         redirect_to :action => 'account', :display_name => @user.display_name
426       else
427         flash.now[:error] = t 'user.confirm_email.failure'
428       end
429     end
430   end
431
432   def api_gpx_files
433     doc = OSM::API.new.get_xml_doc
434     @user.traces.each do |trace|
435       doc.root << trace.to_xml_node() if trace.public? or trace.user == @user
436     end
437     render :text => doc.to_s, :content_type => "text/xml"
438   end
439
440   def view
441     @this_user = User.find_by_display_name(params[:display_name])
442
443     if @this_user and
444        (@this_user.visible? or (@user and @user.administrator?))
445       @title = @this_user.display_name
446     else
447       @title = t 'user.no_such_user.title'
448       @not_found_user = params[:display_name]
449       render :action => 'no_such_user', :status => :not_found
450     end
451   end
452
453   def make_friend
454     if params[:display_name]
455       name = params[:display_name]
456       new_friend = User.find_by_display_name(name, :conditions => {:visible => true})
457       friend = Friend.new
458       friend.user_id = @user.id
459       friend.friend_user_id = new_friend.id
460       unless @user.is_friends_with?(new_friend)
461         if friend.save
462           flash[:notice] = t 'user.make_friend.success', :name => name
463           Notifier.deliver_friend_notification(friend)
464         else
465           friend.add_error(t('user.make_friend.failed', :name => name))
466         end
467       else
468         flash[:warning] = t 'user.make_friend.already_a_friend', :name => name
469       end
470
471       redirect_to :controller => 'user', :action => 'view'
472     end
473   end
474
475   def remove_friend
476     if params[:display_name]
477       name = params[:display_name]
478       friend = User.find_by_display_name(name, :conditions => {:visible => true})
479       if @user.is_friends_with?(friend)
480         Friend.delete_all "user_id = #{@user.id} AND friend_user_id = #{friend.id}"
481         flash[:notice] = t 'user.remove_friend.success', :name => friend.display_name
482       else
483         flash[:error] = t 'user.remove_friend.not_a_friend', :name => friend.display_name
484       end
485
486       redirect_to :controller => 'user', :action => 'view'
487     end
488   end
489
490   ##
491   # activate a user, allowing them to log in
492   def activate
493     @this_user.update_attributes(:active => true)
494     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
495   end
496
497   ##
498   # deactivate a user, preventing them from logging in
499   def deactivate
500     @this_user.update_attributes(:active => false)
501     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
502   end
503
504   ##
505   # hide a user, marking them as logically deleted
506   def hide
507     @this_user.update_attributes(:visible => false)
508     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
509   end
510
511   ##
512   # unhide a user, clearing the logically deleted flag
513   def unhide
514     @this_user.update_attributes(:visible => true)
515     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
516   end
517
518   ##
519   # delete a user, marking them as deleted and removing personal data
520   def delete
521     @this_user.delete
522     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
523   end
524 private
525   ##
526   # require that the user is a administrator, or fill out a helpful error message
527   # and return them to the user page.
528   def require_administrator
529     unless @user.administrator?
530       flash[:error] = t('user.filter.not_an_administrator')
531       redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
532     end
533   end
534
535   ##
536   # ensure that there is a "this_user" instance variable
537   def lookup_this_user
538     @this_user = User.find_by_display_name(params[:display_name])
539   rescue ActiveRecord::RecordNotFound
540     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name] unless @this_user
541   end
542 end