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