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