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