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