]> git.openstreetmap.org Git - rails.git/blob - app/controllers/users_controller.rb
Add support for Active Storage attachments
[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, :make_friend, :remove_friend]
14   before_action :require_cookies, :only => [:new, :login, :confirm]
15   before_action :lookup_user_by_name, :only => [:set_status, :delete]
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 params[:session] == session.id
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   def make_friend
387     @new_friend = User.find_by(:display_name => params[:display_name])
388
389     if @new_friend
390       if request.post?
391         friendship = Friendship.new
392         friendship.befriender = current_user
393         friendship.befriendee = @new_friend
394         if current_user.is_friends_with?(@new_friend)
395           flash[:warning] = t "users.make_friend.already_a_friend", :name => @new_friend.display_name
396         elsif friendship.save
397           flash[:notice] = t "users.make_friend.success", :name => @new_friend.display_name
398           Notifier.friend_notification(friendship).deliver_later
399         else
400           friendship.add_error(t("users.make_friend.failed", :name => @new_friend.display_name))
401         end
402
403         if params[:referer]
404           redirect_to params[:referer]
405         else
406           redirect_to :action => "show"
407         end
408       end
409     else
410       render_unknown_user params[:display_name]
411     end
412   end
413
414   def remove_friend
415     @friend = User.find_by(:display_name => params[:display_name])
416
417     if @friend
418       if request.post?
419         if current_user.is_friends_with?(@friend)
420           Friendship.where(:befriender => current_user, :befriendee => @friend).delete_all
421           flash[:notice] = t "users.remove_friend.success", :name => @friend.display_name
422         else
423           flash[:error] = t "users.remove_friend.not_a_friend", :name => @friend.display_name
424         end
425
426         if params[:referer]
427           redirect_to params[:referer]
428         else
429           redirect_to :action => "show"
430         end
431       end
432     else
433       render_unknown_user params[:display_name]
434     end
435   end
436
437   ##
438   # sets a user's status
439   def set_status
440     @user.status = params[:status]
441     @user.save
442     redirect_to user_path(:display_name => params[:display_name])
443   end
444
445   ##
446   # delete a user, marking them as deleted and removing personal data
447   def delete
448     @user.delete
449     redirect_to user_path(:display_name => params[:display_name])
450   end
451
452   ##
453   # display a list of users matching specified criteria
454   def index
455     if request.post?
456       ids = params[:user].keys.collect(&:to_i)
457
458       User.where(:id => ids).update_all(:status => "confirmed") if params[:confirm]
459       User.where(:id => ids).update_all(:status => "deleted") if params[:hide]
460
461       redirect_to url_for(:status => params[:status], :ip => params[:ip], :page => params[:page])
462     else
463       @params = params.permit(:status, :ip)
464
465       conditions = {}
466       conditions[:status] = @params[:status] if @params[:status]
467       conditions[:creation_ip] = @params[:ip] if @params[:ip]
468
469       @user_pages, @users = paginate(:users,
470                                      :conditions => conditions,
471                                      :order => :id,
472                                      :per_page => 50)
473     end
474   end
475
476   ##
477   # omniauth success callback
478   def auth_success
479     auth_info = request.env["omniauth.auth"]
480
481     provider = auth_info[:provider]
482     uid = auth_info[:uid]
483     name = auth_info[:info][:name]
484     email = auth_info[:info][:email]
485
486     case provider
487     when "openid"
488       email_verified = uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
489                        uid.match(%r{https://me.yahoo.com/(.*)})
490     when "google", "facebook"
491       email_verified = true
492     else
493       email_verified = false
494     end
495
496     if settings = session.delete(:new_user_settings)
497       current_user.auth_provider = provider
498       current_user.auth_uid = uid
499
500       update_user(current_user, settings)
501
502       session[:user_errors] = current_user.errors.as_json
503
504       redirect_to :action => "account", :display_name => current_user.display_name
505     elsif session[:new_user]
506       session[:new_user].auth_provider = provider
507       session[:new_user].auth_uid = uid
508
509       session[:new_user].status = "active" if email_verified && email == session[:new_user].email
510
511       redirect_to :action => "terms"
512     else
513       user = User.find_by(:auth_provider => provider, :auth_uid => uid)
514
515       if user.nil? && provider == "google"
516         openid_url = auth_info[:extra][:id_info]["openid_id"]
517         user = User.find_by(:auth_provider => "openid", :auth_uid => openid_url) if openid_url
518         user&.update(:auth_provider => provider, :auth_uid => uid)
519       end
520
521       if user
522         case user.status
523         when "pending" then
524           unconfirmed_login(user)
525         when "active", "confirmed" then
526           successful_login(user, request.env["omniauth.params"]["referer"])
527         when "suspended" then
528           failed_login t("users.login.account is suspended", :webmaster => "mailto:#{Settings.support_email}").html_safe
529         else
530           failed_login t("users.login.auth failure")
531         end
532       else
533         redirect_to :action => "new", :nickname => name, :email => email,
534                     :auth_provider => provider, :auth_uid => uid
535       end
536     end
537   end
538
539   ##
540   # omniauth failure callback
541   def auth_failure
542     flash[:error] = t("users.auth_failure." + params[:message])
543     redirect_to params[:origin] || login_url
544   end
545
546   private
547
548   ##
549   # handle password authentication
550   def password_authentication(username, password)
551     if user = User.authenticate(:username => username, :password => password)
552       successful_login(user)
553     elsif user = User.authenticate(:username => username, :password => password, :pending => true)
554       unconfirmed_login(user)
555     elsif User.authenticate(:username => username, :password => password, :suspended => true)
556       failed_login t("users.login.account is suspended", :webmaster => "mailto:#{Settings.support_email}").html_safe, username
557     else
558       failed_login t("users.login.auth failure"), username
559     end
560   end
561
562   ##
563   # return the URL to use for authentication
564   def auth_url(provider, uid, referer = nil)
565     params = { :provider => provider }
566
567     params[:openid_url] = openid_expand_url(uid) if provider == "openid"
568
569     if referer.nil?
570       params[:origin] = request.path
571     else
572       params[:origin] = request.path + "?referer=" + CGI.escape(referer)
573       params[:referer] = referer
574     end
575
576     auth_path(params)
577   end
578
579   ##
580   # special case some common OpenID providers by applying heuristics to
581   # try and come up with the correct URL based on what the user entered
582   def openid_expand_url(openid_url)
583     if openid_url.nil?
584       nil
585     elsif openid_url.match(%r{(.*)gmail.com(/?)$}) || openid_url.match(%r{(.*)googlemail.com(/?)$})
586       # Special case gmail.com as it is potentially a popular OpenID
587       # provider and, unlike yahoo.com, where it works automatically, Google
588       # have hidden their OpenID endpoint somewhere obscure this making it
589       # somewhat less user friendly.
590       "https://www.google.com/accounts/o8/id"
591     else
592       openid_url
593     end
594   end
595
596   ##
597   # process a successful login
598   def successful_login(user, referer = nil)
599     session[:user] = user.id
600     session_expires_after 28.days if session[:remember_me]
601
602     target = referer || session[:referer] || url_for(:controller => :site, :action => :index)
603
604     # The user is logged in, so decide where to send them:
605     #
606     # - If they haven't seen the contributor terms, send them there.
607     # - If they have a block on them, show them that.
608     # - If they were referred to the login, send them back there.
609     # - Otherwise, send them to the home page.
610     if !user.terms_seen
611       redirect_to :action => :terms, :referer => target
612     elsif user.blocked_on_view
613       redirect_to user.blocked_on_view, :referer => target
614     else
615       redirect_to target
616     end
617
618     session.delete(:remember_me)
619     session.delete(:referer)
620   end
621
622   ##
623   # process a failed login
624   def failed_login(message, username = nil)
625     flash[:error] = message
626
627     redirect_to :action => "login", :referer => session[:referer],
628                 :username => username, :remember_me => session[:remember_me]
629
630     session.delete(:remember_me)
631     session.delete(:referer)
632   end
633
634   ##
635   #
636   def unconfirmed_login(user)
637     session[:token] = user.tokens.create.token
638
639     redirect_to :action => "confirm", :display_name => user.display_name
640
641     session.delete(:remember_me)
642     session.delete(:referer)
643   end
644
645   ##
646   # update a user's details
647   def update_user(user, params)
648     user.display_name = params[:user][:display_name]
649     user.new_email = params[:user][:new_email]
650
651     unless params[:user][:pass_crypt].empty? && params[:user][:pass_crypt_confirmation].empty?
652       user.pass_crypt = params[:user][:pass_crypt]
653       user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
654     end
655
656     if params[:user][:description] != user.description
657       user.description = params[:user][:description]
658       user.description_format = "markdown"
659     end
660
661     user.languages = params[:user][:languages].split(",")
662
663     case params[:image_action]
664     when "new" then
665       user.image = params[:user][:image]
666       user.image_use_gravatar = false
667     when "delete" then
668       user.image = nil
669       user.image_use_gravatar = false
670     when "gravatar" then
671       user.image = nil
672       user.image_use_gravatar = true
673     end
674
675     user.home_lat = params[:user][:home_lat]
676     user.home_lon = params[:user][:home_lon]
677
678     user.preferred_editor = if params[:user][:preferred_editor] == "default"
679                               nil
680                             else
681                               params[:user][:preferred_editor]
682                             end
683
684     if params[:user][:auth_provider].nil? || params[:user][:auth_provider].blank?
685       user.auth_provider = nil
686       user.auth_uid = nil
687     end
688
689     if user.save
690       set_locale(true)
691
692       if user.new_email.blank? || user.new_email == user.email
693         flash.now[:notice] = t "users.account.flash update success"
694       else
695         user.email = user.new_email
696
697         if user.valid?
698           flash.now[:notice] = t "users.account.flash update success confirm needed"
699
700           begin
701             Notifier.email_confirm(user, user.tokens.create).deliver_later
702           rescue StandardError
703             # Ignore errors sending email
704           end
705         else
706           current_user.errors.add(:new_email, current_user.errors[:email])
707           current_user.errors.add(:email, [])
708         end
709
710         user.restore_email!
711       end
712     end
713   end
714
715   ##
716   # require that the user in the URL is the logged in user
717   def require_self
718     head :forbidden if params[:display_name] != current_user.display_name
719   end
720
721   ##
722   # ensure that there is a "user" instance variable
723   def lookup_user_by_name
724     @user = User.find_by(:display_name => params[:display_name])
725   rescue ActiveRecord::RecordNotFound
726     redirect_to :action => "view", :display_name => params[:display_name] unless @user
727   end
728
729   ##
730   #
731   def disable_terms_redirect
732     # this is necessary otherwise going to the user terms page, when
733     # having not agreed already would cause an infinite redirect loop.
734     # it's .now so that this doesn't propagate to other pages.
735     flash.now[:skip_terms] = true
736   end
737
738   ##
739   # return permitted user parameters
740   def user_params
741     params.require(:user).permit(:email, :email_confirmation, :display_name,
742                                  :auth_provider, :auth_uid,
743                                  :pass_crypt, :pass_crypt_confirmation)
744   end
745
746   ##
747   # check signup acls
748   def check_signup_allowed(email = nil)
749     domain = if email.nil?
750                nil
751              else
752                email.split("@").last
753              end
754
755     mx_servers = if domain.nil?
756                    nil
757                  else
758                    domain_mx_servers(domain)
759                  end
760
761     if blocked = Acl.no_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
762       logger.info "Blocked signup from #{request.remote_ip} for #{email}"
763
764       render :action => "blocked"
765     end
766
767     !blocked
768   end
769
770   ##
771   # get list of MX servers for a domains
772   def domain_mx_servers(domain)
773     Resolv::DNS.open do |dns|
774       dns.getresources(domain, Resolv::DNS::Resource::IN::MX).collect(&:exchange).collect(&:to_s)
775     end
776   end
777
778   ##
779   # check if this user has a gravatar and set the user pref is true
780   def gravatar_enable(user)
781     # code from example https://en.gravatar.com/site/implement/images/ruby/
782     return false if user.image.present?
783
784     hash = Digest::MD5.hexdigest(user.email.downcase)
785     url = "https://www.gravatar.com/avatar/#{hash}?d=404" # without d=404 we will always get an image back
786     response = OSM.http_client.get(URI.parse(url))
787     oldsetting = user.image_use_gravatar
788     user.image_use_gravatar = response.success?
789     oldsetting != user.image_use_gravatar
790   end
791
792   ##
793   # display a message about th current status of the gravatar setting
794   def gravatar_status_message(user)
795     if user.image_use_gravatar
796       t "users.account.gravatar.enabled"
797     else
798       t "users.account.gravatar.disabled"
799     end
800   end
801 end