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