]> git.openstreetmap.org Git - rails.git/blob - app/controllers/user_controller.rb
e5515f727885e3464bb8372e8e7ce41f2b3a8f72
[rails.git] / app / controllers / user_controller.rb
1 class UserController < ApplicationController
2   layout "site", :except => [:api_details]
3
4   skip_before_action :verify_authenticity_token, :only => [:api_read, :api_details, :api_gpx_files, :auth_success]
5   before_action :disable_terms_redirect, :only => [:terms, :save, :logout, :api_details]
6   before_action :authorize, :only => [:api_details, :api_gpx_files]
7   before_action :authorize_web, :except => [:api_read, :api_details, :api_gpx_files]
8   before_action :set_locale, :except => [:api_read, :api_details, :api_gpx_files]
9   before_action :require_user, :only => [:account, :go_public, :make_friend, :remove_friend]
10   before_action :require_self, :only => [:account]
11   before_action :check_database_readable, :except => [:login, :api_read, :api_details, :api_gpx_files]
12   before_action :check_database_writable, :only => [:new, :account, :confirm, :confirm_email, :lost_password, :reset_password, :go_public, :make_friend, :remove_friend]
13   before_action :check_api_readable, :only => [:api_read, :api_details, :api_gpx_files]
14   before_action :require_allow_read_prefs, :only => [:api_details]
15   before_action :require_allow_read_gpx, :only => [:api_gpx_files]
16   before_action :require_cookies, :only => [:new, :login, :confirm]
17   before_action :require_administrator, :only => [:set_status, :delete, :list]
18   around_action :api_call_handle_error, :only => [:api_read, :api_details, :api_gpx_files]
19   before_action :lookup_user_by_id, :only => [:api_read]
20   before_action :lookup_user_by_name, :only => [:set_status, :delete]
21
22   def terms
23     @legale = params[:legale] || OSM.ip_to_country(request.remote_ip) || DEFAULT_LEGALE
24     @text = OSM.legal_text_for_country(@legale)
25
26     if request.xhr?
27       render :partial => "terms"
28     else
29       @title = t "user.terms.title"
30
31       if @user && @user.terms_agreed?
32         # Already agreed to terms, so just show settings
33         redirect_to :action => :account, :display_name => @user.display_name
34       elsif @user.nil? && session[:new_user].nil?
35         redirect_to :action => :login, :referer => request.fullpath
36       end
37     end
38   end
39
40   def save
41     @title = t "user.new.title"
42
43     if params[:decline]
44       if @user
45         @user.terms_seen = true
46
47         if @user.save
48           flash[:notice] = t("user.new.terms declined", :url => t("user.new.terms declined url")).html_safe
49         end
50
51         if params[:referer]
52           redirect_to params[:referer]
53         else
54           redirect_to :action => :account, :display_name => @user.display_name
55         end
56       else
57         redirect_to t("user.terms.declined")
58       end
59     elsif @user
60       unless @user.terms_agreed?
61         @user.consider_pd = params[:user][:consider_pd]
62         @user.terms_agreed = Time.now.getutc
63         @user.terms_seen = true
64
65         flash[:notice] = t "user.new.terms accepted" if @user.save
66       end
67
68       if params[:referer]
69         redirect_to params[:referer]
70       else
71         redirect_to :action => :account, :display_name => @user.display_name
72       end
73     else
74       @user = session.delete(:new_user)
75
76       if check_signup_allowed(@user.email)
77         @user.data_public = true
78         @user.description = "" if @user.description.nil?
79         @user.creation_ip = request.remote_ip
80         @user.languages = http_accept_language.user_preferred_languages
81         @user.terms_agreed = Time.now.getutc
82         @user.terms_seen = true
83
84         if @user.auth_uid.nil? || @user.auth_uid.empty?
85           @user.auth_provider = nil
86           @user.auth_uid = nil
87         end
88
89         if @user.save
90           flash[:piwik_goal] = PIWIK["goals"]["signup"] if defined?(PIWIK)
91
92           referer = welcome_path
93
94           begin
95             uri = URI(session[:referer])
96             %r{map=(.*)/(.*)/(.*)}.match(uri.fragment) do |m|
97               editor = Rack::Utils.parse_query(uri.query).slice("editor")
98               referer = welcome_path({ "zoom" => m[1],
99                                        "lat" => m[2],
100                                        "lon" => m[3] }.merge(editor))
101             end
102           rescue
103             # Use default
104           end
105
106           if @user.status == "active"
107             session[:referer] = referer
108             successful_login(@user)
109           else
110             session[:token] = @user.tokens.create.token
111             Notifier.signup_confirm(@user, @user.tokens.create(:referer => referer)).deliver_now
112             redirect_to :action => "confirm", :display_name => @user.display_name
113           end
114         else
115           render :action => "new", :referer => params[:referer]
116         end
117       end
118     end
119   end
120
121   def account
122     @title = t "user.account.title"
123     @tokens = @user.oauth_tokens.authorized
124
125     if params[:user] && params[:user][:display_name] && params[:user][:description]
126       if params[:user][:auth_provider].blank? ||
127          (params[:user][:auth_provider] == @user.auth_provider &&
128           params[:user][:auth_uid] == @user.auth_uid)
129         update_user(@user, params)
130       else
131         session[:new_user_settings] = params
132         redirect_to auth_url(params[:user][:auth_provider], params[:user][:auth_uid])
133       end
134     end
135   end
136
137   def go_public
138     @user.data_public = true
139     @user.save
140     flash[:notice] = t "user.go_public.flash success"
141     redirect_to :controller => "user", :action => "account", :display_name => @user.display_name
142   end
143
144   def lost_password
145     @title = t "user.lost_password.title"
146
147     if params[:user] && params[:user][:email]
148       user = User.visible.find_by_email(params[:user][:email])
149
150       if user.nil?
151         users = User.visible.where("LOWER(email) = LOWER(?)", params[:user][:email])
152
153         user = users.first if users.count == 1
154       end
155
156       if user
157         token = user.tokens.create
158         Notifier.lost_password(user, token).deliver_now
159         flash[:notice] = t "user.lost_password.notice email on way"
160         redirect_to :action => "login"
161       else
162         flash.now[:error] = t "user.lost_password.notice email cannot find"
163       end
164     end
165   end
166
167   def reset_password
168     @title = t "user.reset_password.title"
169
170     if params[:token]
171       token = UserToken.find_by_token(params[:token])
172
173       if token
174         @user = token.user
175
176         if params[:user]
177           @user.pass_crypt = params[:user][:pass_crypt]
178           @user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
179           @user.status = "active" if @user.status == "pending"
180           @user.email_valid = true
181
182           if @user.save
183             token.destroy
184             flash[:notice] = t "user.reset_password.flash changed"
185             successful_login(@user)
186           end
187         end
188       else
189         flash[:error] = t "user.reset_password.flash token bad"
190         redirect_to :action => "lost_password"
191       end
192     else
193       render :text => "", :status => :bad_request
194     end
195   end
196
197   def new
198     @title = t "user.new.title"
199     @referer = params[:referer] || session[:referer]
200
201     if @user
202       # The user is logged in already, so don't show them the signup
203       # page, instead send them to the home page
204       if @referer
205         redirect_to @referer
206       else
207         redirect_to :controller => "site", :action => "index"
208       end
209     elsif params.key?(:auth_provider) && params.key?(:auth_uid)
210       @user = User.new(:email => params[:email],
211                        :email_confirmation => params[:email],
212                        :display_name => params[:nickname],
213                        :auth_provider => params[:auth_provider],
214                        :auth_uid => params[:auth_uid])
215
216       flash.now[:notice] = render_to_string :partial => "auth_association"
217     else
218       check_signup_allowed
219     end
220   end
221
222   def create
223     @user = User.new(user_params)
224
225     if check_signup_allowed(@user.email)
226       session[:referer] = params[:referer]
227
228       @user.status = "pending"
229
230       if @user.auth_provider.present? && @user.pass_crypt.empty?
231         # We are creating an account with external authentication and
232         # no password was specified so create a random one
233         @user.pass_crypt = SecureRandom.base64(16)
234         @user.pass_crypt_confirmation = @user.pass_crypt
235       end
236
237       if @user.invalid?
238         # Something is wrong with a new user, so rerender the form
239         render :action => "new"
240       elsif @user.auth_provider.present?
241         # Verify external authenticator before moving on
242         session[:new_user] = @user
243         redirect_to auth_url(@user.auth_provider, @user.auth_uid)
244       else
245         # Save the user record
246         session[:new_user] = @user
247         redirect_to :action => :terms
248       end
249     end
250   end
251
252   def login
253     session[:referer] = params[:referer] if params[:referer]
254
255     if params[:username].present? && params[:password].present?
256       session[:remember_me] ||= params[:remember_me]
257       password_authentication(params[:username], params[:password])
258     elsif params[:openid_url].present?
259       session[:remember_me] ||= params[:remember_me_openid]
260       redirect_to auth_url("openid", params[:openid_url], params[:referer])
261     end
262   end
263
264   def logout
265     @title = t "user.logout.title"
266
267     if params[:session] == request.session_options[:id]
268       if session[:token]
269         token = UserToken.find_by_token(session[:token])
270         token.destroy if token
271         session.delete(:token)
272       end
273       session.delete(:user)
274       session_expires_automatically
275       if params[:referer]
276         redirect_to params[:referer]
277       else
278         redirect_to :controller => "site", :action => "index"
279       end
280     end
281   end
282
283   def confirm
284     if request.post?
285       token = UserToken.find_by_token(params[:confirm_string])
286       if token && token.user.active?
287         flash[:error] = t("user.confirm.already active")
288         redirect_to :action => "login"
289       elsif !token || token.expired?
290         flash[:error] = t("user.confirm.unknown token")
291         redirect_to :action => "confirm"
292       else
293         user = token.user
294         user.status = "active"
295         user.email_valid = true
296         user.save!
297         referer = token.referer
298         token.destroy
299
300         if session[:token]
301           token = UserToken.find_by_token(session[:token])
302           session.delete(:token)
303         else
304           token = nil
305         end
306
307         if token.nil? || token.user != user
308           flash[:notice] = t("user.confirm.success")
309           redirect_to :action => :login, :referer => referer
310         else
311           token.destroy
312
313           session[:user] = user.id
314
315           redirect_to referer || welcome_path
316         end
317       end
318     else
319       user = User.find_by_display_name(params[:display_name])
320
321       redirect_to root_path if user.nil? || user.active?
322     end
323   end
324
325   def confirm_resend
326     user = User.find_by_display_name(params[:display_name])
327     token = UserToken.find_by_token(session[:token])
328
329     if user.nil? || token.nil? || token.user != user
330       flash[:error] = t "user.confirm_resend.failure", :name => params[:display_name]
331     else
332       Notifier.signup_confirm(user, user.tokens.create).deliver_now
333       flash[:notice] = t("user.confirm_resend.success", :email => user.email, :sender => SUPPORT_EMAIL).html_safe
334     end
335
336     redirect_to :action => "login"
337   end
338
339   def confirm_email
340     if request.post?
341       token = UserToken.find_by_token(params[:confirm_string])
342       if token && token.user.new_email?
343         @user = token.user
344         @user.email = @user.new_email
345         @user.new_email = nil
346         @user.email_valid = true
347         if @user.save
348           flash[:notice] = t "user.confirm_email.success"
349         else
350           flash[:errors] = @user.errors
351         end
352         token.destroy
353         session[:user] = @user.id
354         redirect_to :action => "account", :display_name => @user.display_name
355       elsif token
356         flash[:error] = t "user.confirm_email.failure"
357         redirect_to :action => "account", :display_name => token.user.display_name
358       else
359         flash[:error] = t "user.confirm_email.unknown_token"
360       end
361     end
362   end
363
364   def api_read
365     if @this_user.visible?
366       render :action => :api_read, :content_type => "text/xml"
367     else
368       render :text => "", :status => :gone
369     end
370   end
371
372   def api_details
373     @this_user = @user
374     render :action => :api_read, :content_type => "text/xml"
375   end
376
377   def api_gpx_files
378     doc = OSM::API.new.get_xml_doc
379     @user.traces.reload.each do |trace|
380       doc.root << trace.to_xml_node
381     end
382     render :text => doc.to_s, :content_type => "text/xml"
383   end
384
385   def view
386     @this_user = User.find_by_display_name(params[:display_name])
387
388     if @this_user &&
389        (@this_user.visible? || (@user && @user.administrator?))
390       @title = @this_user.display_name
391     else
392       render_unknown_user params[:display_name]
393     end
394   end
395
396   def make_friend
397     @new_friend = User.find_by_display_name(params[:display_name])
398
399     if @new_friend
400       if request.post?
401         friend = Friend.new
402         friend.user_id = @user.id
403         friend.friend_user_id = @new_friend.id
404         if @user.is_friends_with?(@new_friend)
405           flash[:warning] = t "user.make_friend.already_a_friend", :name => @new_friend.display_name
406         elsif friend.save
407           flash[:notice] = t "user.make_friend.success", :name => @new_friend.display_name
408           Notifier.friend_notification(friend).deliver_now
409         else
410           friend.add_error(t("user.make_friend.failed", :name => @new_friend.display_name))
411         end
412
413         if params[:referer]
414           redirect_to params[:referer]
415         else
416           redirect_to :controller => "user", :action => "view"
417         end
418       end
419     else
420       render_unknown_user params[:display_name]
421     end
422   end
423
424   def remove_friend
425     @friend = User.find_by_display_name(params[:display_name])
426
427     if @friend
428       if request.post?
429         if @user.is_friends_with?(@friend)
430           Friend.delete_all "user_id = #{@user.id} AND friend_user_id = #{@friend.id}"
431           flash[:notice] = t "user.remove_friend.success", :name => @friend.display_name
432         else
433           flash[:error] = t "user.remove_friend.not_a_friend", :name => @friend.display_name
434         end
435
436         if params[:referer]
437           redirect_to params[:referer]
438         else
439           redirect_to :controller => "user", :action => "view"
440         end
441       end
442     else
443       render_unknown_user params[:display_name]
444     end
445   end
446
447   ##
448   # sets a user's status
449   def set_status
450     @this_user.status = params[:status]
451     @this_user.save
452     redirect_to :controller => "user", :action => "view", :display_name => params[:display_name]
453   end
454
455   ##
456   # delete a user, marking them as deleted and removing personal data
457   def delete
458     @this_user.delete
459     redirect_to :controller => "user", :action => "view", :display_name => params[:display_name]
460   end
461
462   ##
463   # display a list of users matching specified criteria
464   def list
465     if request.post?
466       ids = params[:user].keys.collect(&:to_i)
467
468       User.where(:id => ids).update_all(:status => "confirmed") if params[:confirm]
469       User.where(:id => ids).update_all(:status => "deleted") if params[:hide]
470
471       redirect_to url_for(:status => params[:status], :ip => params[:ip], :page => params[:page])
472     else
473       conditions = {}
474       conditions[:status] = params[:status] if params[:status]
475       conditions[:creation_ip] = params[:ip] if params[:ip]
476
477       @user_pages, @users = paginate(:users,
478                                      :conditions => conditions,
479                                      :order => :id,
480                                      :per_page => 50)
481     end
482   end
483
484   ##
485   # omniauth success callback
486   def auth_success
487     auth_info = env["omniauth.auth"]
488
489     provider = auth_info[:provider]
490     uid = auth_info[:uid]
491     name = auth_info[:info][:name]
492     email = auth_info[:info][:email]
493
494     case provider
495     when "openid"
496       email_verified = uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
497                        uid.match(%r{https://me.yahoo.com/(.*)})
498     when "google", "facebook"
499       email_verified = true
500     else
501       email_verified = false
502     end
503
504     user = User.find_by_auth_provider_and_auth_uid(provider, uid)
505
506     if user.nil? && provider == "google"
507       openid_url = auth_info[:extra][:id_info]["openid_id"]
508       user = User.find_by_auth_provider_and_auth_uid("openid", openid_url) if openid_url
509       user.update(:auth_provider => provider, :auth_uid => uid) if user
510     end
511
512     if user
513       case user.status
514       when "pending" then
515         unconfirmed_login(user)
516       when "active", "confirmed" then
517         successful_login(user, env["omniauth.params"]["referer"])
518       when "suspended" then
519         failed_login t("user.login.account is suspended", :webmaster => "mailto:#{SUPPORT_EMAIL}")
520       else
521         failed_login t("user.login.auth failure")
522       end
523     elsif settings = session.delete(:new_user_settings)
524       @user.auth_provider = provider
525       @user.auth_uid = uid
526
527       update_user(@user, settings)
528
529       redirect_to :action => "account", :display_name => @user.display_name
530     elsif session[:new_user]
531       session[:new_user].auth_provider = provider
532       session[:new_user].auth_uid = uid
533
534       if email_verified && email == session[:new_user].email
535         session[:new_user].status = "active"
536       end
537
538       redirect_to :action => "terms"
539     else
540       redirect_to :action => "new", :nickname => name, :email => email,
541                   :auth_provider => provider, :auth_uid => uid
542     end
543   end
544
545   ##
546   # omniauth failure callback
547   def auth_failure
548     flash[:error] = t("user.auth_failure." + params[:message])
549     redirect_to params[:origin] || login_url
550   end
551
552   private
553
554   ##
555   # handle password authentication
556   def password_authentication(username, password)
557     if user = User.authenticate(:username => username, :password => password)
558       successful_login(user)
559     elsif user = User.authenticate(:username => username, :password => password, :pending => true)
560       unconfirmed_login(user)
561     elsif User.authenticate(:username => username, :password => password, :suspended => true)
562       failed_login t("user.login.account is suspended", :webmaster => "mailto:#{SUPPORT_EMAIL}"), username
563     else
564       failed_login t("user.login.auth failure"), username
565     end
566   end
567
568   ##
569   # return the URL to use for authentication
570   def auth_url(provider, uid, referer = nil)
571     params = { :provider => provider }
572
573     params[:openid_url] = openid_expand_url(uid) if provider == "openid"
574
575     if referer.nil?
576       params[:origin] = request.path
577     else
578       params[:origin] = request.path + "?referer=" + CGI.escape(referer)
579       params[:referer] = referer
580     end
581
582     auth_path(params)
583   end
584
585   ##
586   # special case some common OpenID providers by applying heuristics to
587   # try and come up with the correct URL based on what the user entered
588   def openid_expand_url(openid_url)
589     if openid_url.nil?
590       return nil
591     elsif openid_url.match(%r{(.*)gmail.com(/?)$}) || openid_url.match(%r{(.*)googlemail.com(/?)$})
592       # Special case gmail.com as it is potentially a popular OpenID
593       # provider and, unlike yahoo.com, where it works automatically, Google
594       # have hidden their OpenID endpoint somewhere obscure this making it
595       # somewhat less user friendly.
596       return "https://www.google.com/accounts/o8/id"
597     else
598       return openid_url
599     end
600   end
601
602   ##
603   # process a successful login
604   def successful_login(user, referer = nil)
605     session[:user] = user.id
606     session_expires_after 28.days if session[:remember_me]
607
608     target = referer || session[:referer] || url_for(:controller => :site, :action => :index)
609
610     # The user is logged in, so decide where to send them:
611     #
612     # - If they haven't seen the contributor terms, send them there.
613     # - If they have a block on them, show them that.
614     # - If they were referred to the login, send them back there.
615     # - Otherwise, send them to the home page.
616     if REQUIRE_TERMS_SEEN && !user.terms_seen
617       redirect_to :controller => :user, :action => :terms, :referer => target
618     elsif user.blocked_on_view
619       redirect_to user.blocked_on_view, :referer => target
620     else
621       redirect_to target
622     end
623
624     session.delete(:remember_me)
625     session.delete(:referer)
626   end
627
628   ##
629   # process a failed login
630   def failed_login(message, username = nil)
631     flash[:error] = message
632
633     redirect_to :action => "login", :referer => session[:referer],
634                 :username => username, :remember_me => session[:remember_me]
635
636     session.delete(:remember_me)
637     session.delete(:referer)
638   end
639
640   ##
641   #
642   def unconfirmed_login(user)
643     session[:token] = user.tokens.create.token
644
645     redirect_to :action => "confirm", :display_name => user.display_name
646
647     session.delete(:remember_me)
648     session.delete(:referer)
649   end
650
651   ##
652   # update a user's details
653   def update_user(user, params)
654     user.display_name = params[:user][:display_name]
655     user.new_email = params[:user][:new_email]
656
657     unless params[:user][:pass_crypt].empty? && params[:user][:pass_crypt_confirmation].empty?
658       user.pass_crypt = params[:user][:pass_crypt]
659       user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
660     end
661
662     if params[:user][:description] != user.description
663       user.description = params[:user][:description]
664       user.description_format = "markdown"
665     end
666
667     user.languages = params[:user][:languages].split(",")
668
669     case params[:image_action]
670     when "new" then
671       user.image = params[:user][:image]
672       user.image_use_gravatar = false
673     when "delete" then
674       user.image = nil
675       user.image_use_gravatar = false
676     when "gravatar" then
677       user.image = nil
678       user.image_use_gravatar = true
679     end
680
681     user.home_lat = params[:user][:home_lat]
682     user.home_lon = params[:user][:home_lon]
683
684     user.preferred_editor = if params[:user][:preferred_editor] == "default"
685                               nil
686                             else
687                               params[:user][:preferred_editor]
688                             end
689
690     if params[:user][:auth_provider].nil? || params[:user][:auth_provider].blank?
691       user.auth_provider = nil
692       user.auth_uid = nil
693     end
694
695     if user.save
696       set_locale
697
698       if user.new_email.blank? || user.new_email == user.email
699         flash.now[:notice] = t "user.account.flash update success"
700       else
701         user.email = user.new_email
702
703         if user.valid?
704           flash.now[:notice] = t "user.account.flash update success confirm needed"
705
706           begin
707             Notifier.email_confirm(user, user.tokens.create).deliver_now
708           rescue
709             # Ignore errors sending email
710           end
711         else
712           @user.errors.set(:new_email, @user.errors.get(:email))
713           @user.errors.set(:email, [])
714         end
715
716         user.restore_email!
717       end
718     end
719   end
720
721   ##
722   # require that the user is a administrator, or fill out a helpful error message
723   # and return them to the user page.
724   def require_administrator
725     if @user && !@user.administrator?
726       flash[:error] = t("user.filter.not_an_administrator")
727
728       if params[:display_name]
729         redirect_to :controller => "user", :action => "view", :display_name => params[:display_name]
730       else
731         redirect_to :controller => "user", :action => "login", :referer => request.fullpath
732       end
733     elsif !@user
734       redirect_to :controller => "user", :action => "login", :referer => request.fullpath
735     end
736   end
737
738   ##
739   # require that the user in the URL is the logged in user
740   def require_self
741     if params[:display_name] != @user.display_name
742       render :text => "", :status => :forbidden
743     end
744   end
745
746   ##
747   # ensure that there is a "this_user" instance variable
748   def lookup_user_by_id
749     @this_user = User.find(params[:id])
750   end
751
752   ##
753   # ensure that there is a "this_user" instance variable
754   def lookup_user_by_name
755     @this_user = User.find_by_display_name(params[:display_name])
756   rescue ActiveRecord::RecordNotFound
757     redirect_to :controller => "user", :action => "view", :display_name => params[:display_name] unless @this_user
758   end
759
760   ##
761   #
762   def disable_terms_redirect
763     # this is necessary otherwise going to the user terms page, when
764     # having not agreed already would cause an infinite redirect loop.
765     # it's .now so that this doesn't propagate to other pages.
766     flash.now[:skip_terms] = true
767   end
768
769   ##
770   # return permitted user parameters
771   def user_params
772     params.require(:user).permit(:email, :email_confirmation, :display_name,
773                                  :auth_provider, :auth_uid,
774                                  :pass_crypt, :pass_crypt_confirmation)
775   end
776
777   ##
778   # check signup acls
779   def check_signup_allowed(email = nil)
780     domain = if email.nil?
781                nil
782              else
783                email.split("@").last
784              end
785
786     if blocked = Acl.no_account_creation(request.remote_ip, domain)
787       logger.info "Blocked signup from #{request.remote_ip} for #{email}"
788
789       render :action => "blocked"
790     end
791
792     !blocked
793   end
794 end