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