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