]> git.openstreetmap.org Git - rails.git/blob - app/controllers/user_controller.rb
merge 19364:19600 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 => [:set_home, :account, :go_public, :make_friend, :remove_friend, :upload_image, :delete_image]
8   before_filter :check_database_readable, :except => [:api_details, :api_gpx_files]
9   before_filter :check_database_writable, :only => [:login, :new, :set_home, :account, :go_public, :make_friend, :remove_friend, :upload_image, :delete_image]
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           if @user.save
93                 flash[:notice] = t 'user.new.flash create success message'
94                 Notifier.deliver_signup_confirm(@user, @user.tokens.create(:referer => params[:referer]))
95                 redirect_to :action => 'login'
96           else
97                 render :action => 'new'
98           end
99     end
100   end
101
102   def account
103     @title = t 'user.account.title'
104     @tokens = @user.oauth_tokens.find :all, :conditions => 'oauth_tokens.invalidated_at is null and oauth_tokens.authorized_at is not null'
105
106     #The redirect from the OpenID provider reenters here again
107     #and we need to pass the parameters through to the 
108     #open_id_authentication function
109     if params[:open_id_complete]
110       openid_verify('', false)
111           @user.save
112       return
113     end
114
115     if params[:user] and params[:user][:display_name] and params[:user][:description]
116       if params[:user][:email] != @user.email
117         @user.new_email = params[:user][:email]
118       end
119
120       @user.display_name = params[:user][:display_name]
121
122       if params[:user][:pass_crypt].length > 0 or params[:user][:pass_crypt_confirmation].length > 0
123         @user.pass_crypt = params[:user][:pass_crypt]
124         @user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
125       end
126       if (params[:user][:openid_url].length == 0)
127         #Clearing doesn't need OpenID validation, so we can set it here.
128         @user.openid_url = nil
129       end
130
131       @user.description = params[:user][:description]
132       @user.languages = params[:user][:languages].split(",")
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 params[:user][:email] == @user.new_email
140           flash.now[:notice] = t 'user.account.flash update success confirm needed'
141           Notifier.deliver_email_confirm(@user, @user.tokens.create)
142         else
143           flash.now[:notice] = t 'user.account.flash update success'
144         end
145       end
146
147       if (params[:user][:openid_url].length > 0)
148                 begin
149                   @norm_openid_url = OpenIdAuthentication.normalize_identifier(params[:user][:openid_url])
150                   if (@norm_openid_url != @user.openid_url)
151                         #If the OpenID has changed, we want to check that it is a valid OpenID and one
152                         #the user has control over before saving the openID as a password equivalent for
153                         #the user.
154                         openid_verify(@norm_openid_url, false)
155                   end
156                 rescue
157                   flash.now[:error] = t 'user.login.openid invalid'
158                 end
159       end
160
161     end
162   end
163
164   def openid_specialcase_mapping(openid_url)
165     #Special case gmail.com, as it is pontentially a popular OpenID provider and unlike
166     #yahoo.com, where it works automatically, Google have hidden their OpenID endpoint
167     #somewhere obscure making it less userfriendly.
168     if (openid_url.match(/(.*)gmail.com(\/?)$/) or openid_url.match(/(.*)googlemail.com(\/?)$/) )
169       return 'https://www.google.com/accounts/o8/id'
170     end
171
172     return nil
173   end  
174
175   def openid_verify(openid_url,account_create)
176     authenticate_with_open_id(openid_url) do |result, identity_url|
177       if result.successful?
178         #We need to use the openid url passed back from the OpenID provider
179         #rather than the one supplied by the user, as these can be different.
180         #e.g. one can simply enter yahoo.com in the login box, i.e. no user specific url
181         #only once it comes back from the OpenID provider do we know the unique address for
182         #the user.
183                 @user = session[:new_usr] unless @user #this is used for account creation when the user is not yet in the database
184         @user.openid_url = identity_url
185           elsif result.missing?
186                 mapped_id = openid_specialcase_mapping(openid_url)
187                 if mapped_id
188                   openid_verify(mapped_id, account_create)
189                 else
190                   flash.now[:error] = t 'user.login.openid missing provider'
191                 end
192           elsif result.invalid?
193                 flash.now[:error] = t 'user.login.openid invalid'
194           else
195                 flash.now[:error] = t 'user.login.auth failure'
196           end
197     end
198   end
199
200
201   def set_home
202     if params[:user][:home_lat] and params[:user][:home_lon]
203       @user.home_lat = params[:user][:home_lat].to_f
204       @user.home_lon = params[:user][:home_lon].to_f
205       if @user.save
206         flash[:notice] = t 'user.set_home.flash success'
207         redirect_to :controller => 'user', :action => 'account'
208       end
209     end
210   end
211
212   def go_public
213     @user.data_public = true
214     @user.save
215     flash[:notice] = t 'user.go_public.flash success'
216     redirect_to :controller => 'user', :action => 'account', :display_name => @user.display_name
217   end
218
219   def lost_password
220     @title = t 'user.lost_password.title'
221
222     if params[:user] and params[:user][:email]
223       user = User.find_by_email(params[:user][:email], :conditions => {:visible => true})
224
225       if user
226         token = user.tokens.create
227         Notifier.deliver_lost_password(user, token)
228         flash.now[:notice] = t 'user.lost_password.notice email on way'
229       else
230         flash.now[:error] = t 'user.lost_password.notice email cannot find'
231       end
232     end
233   end
234
235   def reset_password
236     @title = t 'user.reset_password.title'
237
238     if params[:token]
239       token = UserToken.find_by_token(params[:token])
240
241       if token
242         @user = token.user
243
244         if params[:user]
245           @user.pass_crypt = params[:user][:pass_crypt]
246           @user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
247           @user.active = true
248           @user.email_valid = true
249
250           if @user.save
251             token.destroy
252             flash[:notice] = t 'user.reset_password.flash changed'
253             redirect_to :action => 'login'
254           end
255         end
256       else
257         flash[:error] = t 'user.reset_password.flash token bad'
258         redirect_to :action => 'lost_password'
259       end
260     end
261   end
262
263   def new
264     @title = t 'user.new.title'
265
266     # The user is logged in already, so don't show them the signup page, instead
267     # send them to the home page
268     redirect_to :controller => 'site', :action => 'index' if session[:user]
269
270     @nickname = params['nickname']
271     @email = params['email']
272         @openID = params['openid']
273   end
274
275   def login
276
277     #The redirect from the OpenID provider reenters here again
278     #and we need to pass the parameters through to the 
279     # open_id_authentication function
280     if params[:open_id_complete]
281       open_id_authentication('')
282     end
283
284     
285     if params[:user] and session[:user].nil?
286
287       if !params[:user][:openid_url].nil? and !params[:user][:openid_url].empty?
288         open_id_authentication(params[:user][:openid_url])
289       else
290         email_or_display_name = params[:user][:email]
291         pass = params[:user][:password]
292         user = User.authenticate(:username => email_or_display_name, :password => pass)
293         if user
294           session[:user] = user.id
295         elsif User.authenticate(:username => email_or_display_name, :password => pass, :inactive => true)
296           flash.now[:error] = t 'user.login.account not active'
297         else
298           flash.now[:error] = t 'user.login.auth failure'
299         end
300       end
301     end
302   
303     if session[:user]
304       # The user is logged in, if the referer param exists, redirect them to that
305       # unless they've also got a block on them, in which case redirect them to
306       # the block so they can clear it.
307       user = User.find(session[:user])
308       block = user.blocked_on_view
309       if block
310         redirect_to block, :referrer => params[:referrer]
311       elsif params[:referer]
312         redirect_to params[:referer]
313       else
314         redirect_to :controller => 'site', :action => 'index'
315       end
316       return
317     end
318
319     @title = t 'user.login.title'
320   end
321
322   def open_id_authentication(openid_url)
323     #TODO: only ask for nickname and email, if we don't already have a user for that openID, in which case
324     #email and nickname are already filled out. I don't know how to do that with ruby syntax though, as we
325     #don't want to duplicate the do block
326     #On the other hand it also doesn't matter too much if we ask every time, as the OpenID provider should
327     #remember these results, and shouldn't repromt the user for these data each time.
328     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|
329       if result.successful?
330         #We need to use the openid url passed back from the OpenID provider
331         #rather than the one supplied by the user, as these can be different.
332         #e.g. one can simply enter yahoo.com in the login box, i.e. no user specific url
333         #only once it comes back from the OpenID provider do we know the unique address for
334         #the user.
335         user = User.find_by_openid_url(identity_url)
336         if user
337           if user.visible? and user.active?
338             session[:user] = user.id
339           else
340             user = nil
341             flash.now[:error] = t 'user.login.account not active'
342           end
343         else
344           #We don't have a user registered to this OpenID. Redirect to the create account page
345           #with username and email filled in if they have been given by the OpenID provider through
346           #the simple registration protocol
347           redirect_to :controller => 'user', :action => 'new', :nickname => registration['nickname'], :email => registration['email'], :openid => identity_url
348         end
349       else if result.missing?
350              #Try and apply some heuristics to make common cases more userfriendly
351              mapped_id = openid_specialcase_mapping(openid_url)
352              if mapped_id
353                open_id_authentication(mapped_id)
354              else
355                flash.now[:error] = t 'user.login.openid missing provider'
356              end
357            else if result.invalid?
358                   flash.now[:error] = t 'user.login.openid invalid'
359                 else
360                   flash.now[:error] = t 'user.login.auth failure'
361                 end
362            end
363       end
364     end
365   end
366
367   def logout
368     if session[:token]
369       token = UserToken.find_by_token(session[:token])
370       if token
371         token.destroy
372       end
373       session[:token] = nil
374     end
375     session[:user] = nil
376     if params[:referer]
377       redirect_to params[:referer]
378     else
379       redirect_to :controller => 'site', :action => 'index'
380     end
381   end
382
383   def confirm
384     if params[:confirm_action]
385       token = UserToken.find_by_token(params[:confirm_string])
386       if token and !token.user.active?
387         @user = token.user
388         @user.active = true
389         @user.email_valid = true
390         @user.save!
391         referer = token.referer
392         token.destroy
393         flash[:notice] = t 'user.confirm.success'
394         session[:user] = @user.id
395         unless referer.nil?
396           redirect_to referer
397         else
398           redirect_to :action => 'account', :display_name => @user.display_name
399         end
400       else
401         flash.now[:error] = t 'user.confirm.failure'
402       end
403     end
404   end
405
406   def confirm_email
407     if params[:confirm_action]
408       token = UserToken.find_by_token(params[:confirm_string])
409       if token and token.user.new_email?
410         @user = token.user
411         @user.email = @user.new_email
412         @user.new_email = nil
413         @user.active = true
414         @user.email_valid = true
415         @user.save!
416         token.destroy
417         flash[:notice] = t 'user.confirm_email.success'
418         session[:user] = @user.id
419         redirect_to :action => 'account', :display_name => @user.display_name
420       else
421         flash.now[:error] = t 'user.confirm_email.failure'
422       end
423     end
424   end
425
426   def upload_image
427     @user.image = params[:user][:image]
428     @user.save!
429     redirect_to :controller => 'user', :action => 'view', :display_name => @user.display_name
430   end
431
432   def delete_image
433     @user.image = nil
434     @user.save!
435     redirect_to :controller => 'user', :action => 'view', :display_name => @user.display_name
436   end
437
438   def api_gpx_files
439     doc = OSM::API.new.get_xml_doc
440     @user.traces.each do |trace|
441       doc.root << trace.to_xml_node() if trace.public? or trace.user == @user
442     end
443     render :text => doc.to_s, :content_type => "text/xml"
444   end
445
446   def view
447     @this_user = User.find_by_display_name(params[:display_name])
448
449     if @this_user and
450        (@this_user.visible? or (@user and @user.administrator?))
451       @title = @this_user.display_name
452     else
453       @title = t 'user.no_such_user.title'
454       @not_found_user = params[:display_name]
455       render :action => 'no_such_user', :status => :not_found
456     end
457   end
458
459   def make_friend
460     if params[:display_name]
461       name = params[:display_name]
462       new_friend = User.find_by_display_name(name, :conditions => {:visible => true})
463       friend = Friend.new
464       friend.user_id = @user.id
465       friend.friend_user_id = new_friend.id
466       unless @user.is_friends_with?(new_friend)
467         if friend.save
468           flash[:notice] = t 'user.make_friend.success', :name => name
469           Notifier.deliver_friend_notification(friend)
470         else
471           friend.add_error(t('user.make_friend.failed', :name => name))
472         end
473       else
474         flash[:warning] = t 'user.make_friend.already_a_friend', :name => name
475       end
476
477       redirect_to :controller => 'user', :action => 'view'
478     end
479   end
480
481   def remove_friend
482     if params[:display_name]
483       name = params[:display_name]
484       friend = User.find_by_display_name(name, :conditions => {:visible => true})
485       if @user.is_friends_with?(friend)
486         Friend.delete_all "user_id = #{@user.id} AND friend_user_id = #{friend.id}"
487         flash[:notice] = t 'user.remove_friend.success', :name => friend.display_name
488       else
489         flash[:error] = t 'user.remove_friend.not_a_friend', :name => friend.display_name
490       end
491
492       redirect_to :controller => 'user', :action => 'view'
493     end
494   end
495
496   ##
497   # activate a user, allowing them to log in
498   def activate
499     @this_user.update_attributes(:active => true)
500     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
501   end
502
503   ##
504   # deactivate a user, preventing them from logging in
505   def deactivate
506     @this_user.update_attributes(:active => false)
507     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
508   end
509
510   ##
511   # hide a user, marking them as logically deleted
512   def hide
513     @this_user.update_attributes(:visible => false)
514     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
515   end
516
517   ##
518   # unhide a user, clearing the logically deleted flag
519   def unhide
520     @this_user.update_attributes(:visible => true)
521     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
522   end
523
524   ##
525   # delete a user, marking them as deleted and removing personal data
526   def delete
527     @this_user.delete
528     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
529   end
530 private
531   ##
532   # require that the user is a administrator, or fill out a helpful error message
533   # and return them to the user page.
534   def require_administrator
535     unless @user.administrator?
536       flash[:error] = t('user.filter.not_an_administrator')
537       redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]
538     end
539   end
540
541   ##
542   # ensure that there is a "this_user" instance variable
543   def lookup_this_user
544     @this_user = User.find_by_display_name(params[:display_name])
545   rescue ActiveRecord::RecordNotFound
546     redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name] unless @this_user
547   end
548 end