]> git.openstreetmap.org Git - rails.git/blob - app/controllers/users_controller.rb
Added root elements and dict support for preferences response
[rails.git] / app / controllers / users_controller.rb
1 class UsersController < ApplicationController
2   include SessionMethods
3
4   layout "site"
5
6   skip_before_action :verify_authenticity_token, :only => [:auth_success]
7   before_action :disable_terms_redirect, :only => [:terms, :save]
8   before_action :authorize_web
9   before_action :set_locale
10   before_action :check_database_readable
11
12   authorize_resource
13
14   before_action :require_self, :only => [:account]
15   before_action :check_database_writable, :only => [:new, :account, :confirm, :confirm_email, :lost_password, :reset_password, :go_public]
16   before_action :require_cookies, :only => [:new, :confirm]
17   before_action :lookup_user_by_name, :only => [:set_status, :destroy]
18   before_action :allow_thirdparty_images, :only => [:show, :account]
19
20   def terms
21     @legale = params[:legale] || OSM.ip_to_country(request.remote_ip) || Settings.default_legale
22     @text = OSM.legal_text_for_country(@legale)
23
24     if request.xhr?
25       render :partial => "terms"
26     else
27       @title = t "users.terms.title"
28
29       if current_user&.terms_agreed?
30         # Already agreed to terms, so just show settings
31         redirect_to :action => :account, :display_name => current_user.display_name
32       elsif current_user.nil? && session[:new_user].nil?
33         redirect_to :action => :login, :referer => request.fullpath
34       end
35     end
36   end
37
38   def save
39     @title = t "users.new.title"
40
41     if params[:decline] || !(params[:read_tou] && params[:read_ct])
42       if current_user
43         current_user.terms_seen = true
44
45         flash[:notice] = t("users.new.terms declined", :url => t("users.new.terms declined url")).html_safe if current_user.save
46
47         if params[:referer]
48           redirect_to safe_referer(params[:referer])
49         else
50           redirect_to :action => :account, :display_name => current_user.display_name
51         end
52       elsif params[:decline]
53         redirect_to t("users.terms.declined")
54       else
55         redirect_to :action => :terms
56       end
57     elsif current_user
58       unless current_user.terms_agreed?
59         current_user.consider_pd = params[:user][:consider_pd]
60         current_user.tou_agreed = Time.now.getutc
61         current_user.terms_agreed = Time.now.getutc
62         current_user.terms_seen = true
63
64         flash[:notice] = t "users.new.terms accepted" if current_user.save
65       end
66
67       if params[:referer]
68         redirect_to safe_referer(params[:referer])
69       else
70         redirect_to :action => :account, :display_name => current_user.display_name
71       end
72     else
73       self.current_user = session.delete(:new_user)
74
75       if check_signup_allowed(current_user.email)
76         current_user.data_public = true
77         current_user.description = "" if current_user.description.nil?
78         current_user.creation_ip = request.remote_ip
79         current_user.languages = http_accept_language.user_preferred_languages
80         current_user.terms_agreed = Time.now.getutc
81         current_user.tou_agreed = Time.now.getutc
82         current_user.terms_seen = true
83
84         if current_user.auth_uid.blank?
85           current_user.auth_provider = nil
86           current_user.auth_uid = nil
87         end
88
89         if current_user.save
90           flash[:piwik_goal] = PIWIK["goals"]["signup"] if defined?(PIWIK)
91
92           referer = welcome_path
93
94           begin
95             uri = URI(session[:referer])
96             %r{map=(.*)/(.*)/(.*)}.match(uri.fragment) do |m|
97               editor = Rack::Utils.parse_query(uri.query).slice("editor")
98               referer = welcome_path({ "zoom" => m[1],
99                                        "lat" => m[2],
100                                        "lon" => m[3] }.merge(editor))
101             end
102           rescue StandardError
103             # Use default
104           end
105
106           if current_user.status == "active"
107             session[:referer] = referer
108             successful_login(current_user)
109           else
110             session[:token] = current_user.tokens.create.token
111             UserMailer.signup_confirm(current_user, current_user.tokens.create(:referer => referer)).deliver_later
112             redirect_to :action => "confirm", :display_name => current_user.display_name
113           end
114         else
115           render :action => "new", :referer => params[:referer]
116         end
117       end
118     end
119   end
120
121   def account
122     @tokens = current_user.oauth_tokens.authorized
123
124     append_content_security_policy_directives(
125       :form_action => %w[accounts.google.com *.facebook.com login.live.com github.com meta.wikimedia.org]
126     )
127
128     if request.post?
129       if params[:user][:auth_provider].blank? ||
130          (params[:user][:auth_provider] == current_user.auth_provider &&
131           params[:user][:auth_uid] == current_user.auth_uid)
132         update_user(current_user, params)
133         redirect_to user_account_url(current_user) if current_user.errors.count.zero?
134       else
135         session[:new_user_settings] = params
136         redirect_to auth_url(params[:user][:auth_provider], params[:user][:auth_uid]), :status => :temporary_redirect
137       end
138     elsif errors = session.delete(:user_errors)
139       errors.each do |attribute, error|
140         current_user.errors.add(attribute, error)
141       end
142     end
143     @title = t "users.account.title"
144   end
145
146   def go_public
147     current_user.data_public = true
148     current_user.save
149     flash[:notice] = t "users.go_public.flash success"
150     redirect_to :action => "account", :display_name => current_user.display_name
151   end
152
153   def lost_password
154     @title = t "users.lost_password.title"
155
156     if request.post?
157       user = User.visible.find_by(:email => params[:email])
158
159       if user.nil?
160         users = User.visible.where("LOWER(email) = LOWER(?)", params[:email])
161
162         user = users.first if users.count == 1
163       end
164
165       if user
166         token = user.tokens.create
167         UserMailer.lost_password(user, token).deliver_later
168         flash[:notice] = t "users.lost_password.notice email on way"
169         redirect_to login_path
170       else
171         flash.now[:error] = t "users.lost_password.notice email cannot find"
172       end
173     end
174   end
175
176   def reset_password
177     @title = t "users.reset_password.title"
178
179     if params[:token]
180       token = UserToken.find_by(:token => params[:token])
181
182       if token
183         self.current_user = token.user
184
185         if params[:user]
186           current_user.pass_crypt = params[:user][:pass_crypt]
187           current_user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
188           current_user.status = "active" if current_user.status == "pending"
189           current_user.email_valid = true
190
191           if current_user.save
192             token.destroy
193             session[:fingerprint] = current_user.fingerprint
194             flash[:notice] = t "users.reset_password.flash changed"
195             successful_login(current_user)
196           end
197         end
198       else
199         flash[:error] = t "users.reset_password.flash token bad"
200         redirect_to :action => "lost_password"
201       end
202     else
203       head :bad_request
204     end
205   end
206
207   def new
208     @title = t "users.new.title"
209     @referer = if params[:referer]
210                  safe_referer(params[:referer])
211                else
212                  session[:referer]
213                end
214
215     append_content_security_policy_directives(
216       :form_action => %w[accounts.google.com *.facebook.com login.live.com github.com meta.wikimedia.org]
217     )
218
219     if current_user
220       # The user is logged in already, so don't show them the signup
221       # page, instead send them to the home page
222       if @referer
223         redirect_to @referer
224       else
225         redirect_to :controller => "site", :action => "index"
226       end
227     elsif params.key?(:auth_provider) && params.key?(:auth_uid)
228       self.current_user = User.new(:email => params[:email],
229                                    :email_confirmation => params[:email],
230                                    :display_name => params[:nickname],
231                                    :auth_provider => params[:auth_provider],
232                                    :auth_uid => params[:auth_uid])
233
234       flash.now[:notice] = render_to_string :partial => "auth_association"
235     else
236       check_signup_allowed
237
238       self.current_user = User.new
239     end
240   end
241
242   def create
243     self.current_user = User.new(user_params)
244
245     if check_signup_allowed(current_user.email)
246       session[:referer] = safe_referer(params[:referer]) if params[:referer]
247
248       Rails.logger.info "create: #{session[:referer]}"
249
250       current_user.status = "pending"
251
252       if current_user.auth_provider.present? && current_user.pass_crypt.empty?
253         # We are creating an account with external authentication and
254         # no password was specified so create a random one
255         current_user.pass_crypt = SecureRandom.base64(16)
256         current_user.pass_crypt_confirmation = current_user.pass_crypt
257       end
258
259       if current_user.invalid?
260         # Something is wrong with a new user, so rerender the form
261         render :action => "new"
262       elsif current_user.auth_provider.present?
263         # Verify external authenticator before moving on
264         session[:new_user] = current_user
265         redirect_to auth_url(current_user.auth_provider, current_user.auth_uid), :status => :temporary_redirect
266       else
267         # Save the user record
268         session[:new_user] = current_user
269         redirect_to :action => :terms
270       end
271     end
272   end
273
274   def confirm
275     if request.post?
276       token = UserToken.find_by(:token => params[:confirm_string])
277       if token&.user&.active?
278         flash[:error] = t("users.confirm.already active")
279         redirect_to login_path
280       elsif !token || token.expired?
281         flash[:error] = t("users.confirm.unknown token")
282         redirect_to :action => "confirm"
283       elsif !token.user.visible?
284         render_unknown_user token.user.display_name
285       else
286         user = token.user
287         user.status = "active"
288         user.email_valid = true
289         flash[:notice] = gravatar_status_message(user) if gravatar_enable(user)
290         user.save!
291         referer = safe_referer(token.referer) if token.referer
292         token.destroy
293
294         if session[:token]
295           token = UserToken.find_by(:token => session[:token])
296           session.delete(:token)
297         else
298           token = nil
299         end
300
301         if token.nil? || token.user != user
302           flash[:notice] = t("users.confirm.success")
303           redirect_to login_path(:referer => referer)
304         else
305           token.destroy
306
307           session[:user] = user.id
308           session[:fingerprint] = user.fingerprint
309
310           redirect_to referer || welcome_path
311         end
312       end
313     else
314       user = User.visible.find_by(:display_name => params[:display_name])
315
316       redirect_to root_path if user.nil? || user.active?
317     end
318   end
319
320   def confirm_resend
321     user = User.visible.find_by(:display_name => params[:display_name])
322     token = UserToken.find_by(:token => session[:token])
323
324     if user.nil? || token.nil? || token.user != user
325       flash[:error] = t "users.confirm_resend.failure", :name => params[:display_name]
326     else
327       UserMailer.signup_confirm(user, user.tokens.create).deliver_later
328       flash[:notice] = t "users.confirm_resend.success_html", :email => user.email, :sender => Settings.support_email
329     end
330
331     redirect_to login_path
332   end
333
334   def confirm_email
335     if request.post?
336       token = UserToken.find_by(:token => params[:confirm_string])
337       if token&.user&.new_email?
338         self.current_user = token.user
339         current_user.email = current_user.new_email
340         current_user.new_email = nil
341         current_user.email_valid = true
342         gravatar_enabled = gravatar_enable(current_user)
343         if current_user.save
344           flash[:notice] = if gravatar_enabled
345                              "#{t('users.confirm_email.success')} #{gravatar_status_message(current_user)}"
346                            else
347                              t("users.confirm_email.success")
348                            end
349         else
350           flash[:errors] = current_user.errors
351         end
352         current_user.tokens.delete_all
353         session[:user] = current_user.id
354         session[:fingerprint] = current_user.fingerprint
355         redirect_to :action => "account", :display_name => current_user.display_name
356       elsif token
357         flash[:error] = t "users.confirm_email.failure"
358         redirect_to :action => "account", :display_name => token.user.display_name
359       else
360         flash[:error] = t "users.confirm_email.unknown_token"
361       end
362     end
363   end
364
365   def show
366     @user = User.find_by(:display_name => params[:display_name])
367
368     if @user &&
369        (@user.visible? || current_user&.administrator?)
370       @title = @user.display_name
371     else
372       render_unknown_user params[:display_name]
373     end
374   end
375
376   ##
377   # sets a user's status
378   def set_status
379     @user.status = params[:status]
380     @user.save
381     redirect_to user_path(:display_name => params[:display_name])
382   end
383
384   ##
385   # delete a user, marking them as deleted and removing personal data
386   def destroy
387     @user.delete
388     redirect_to user_path(:display_name => params[:display_name])
389   end
390
391   ##
392   # display a list of users matching specified criteria
393   def index
394     if request.post?
395       ids = params[:user].keys.collect(&:to_i)
396
397       User.where(:id => ids).update_all(:status => "confirmed") if params[:confirm]
398       User.where(:id => ids).update_all(:status => "deleted") if params[:hide]
399
400       redirect_to url_for(:status => params[:status], :ip => params[:ip], :page => params[:page])
401     else
402       @params = params.permit(:status, :ip)
403
404       conditions = {}
405       conditions[:status] = @params[:status] if @params[:status]
406       conditions[:creation_ip] = @params[:ip] if @params[:ip]
407
408       @user_pages, @users = paginate(:users,
409                                      :conditions => conditions,
410                                      :order => :id,
411                                      :per_page => 50)
412     end
413   end
414
415   ##
416   # omniauth success callback
417   def auth_success
418     auth_info = request.env["omniauth.auth"]
419
420     provider = auth_info[:provider]
421     uid = auth_info[:uid]
422     name = auth_info[:info][:name]
423     email = auth_info[:info][:email]
424
425     case provider
426     when "openid"
427       email_verified = uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
428                        uid.match(%r{https://me.yahoo.com/(.*)})
429     when "google", "facebook"
430       email_verified = true
431     else
432       email_verified = false
433     end
434
435     if settings = session.delete(:new_user_settings)
436       current_user.auth_provider = provider
437       current_user.auth_uid = uid
438
439       update_user(current_user, settings)
440
441       flash.discard
442
443       session[:user_errors] = current_user.errors.as_json
444
445       redirect_to :action => "account", :display_name => current_user.display_name
446     elsif session[:new_user]
447       session[:new_user].auth_provider = provider
448       session[:new_user].auth_uid = uid
449
450       session[:new_user].status = "active" if email_verified && email == session[:new_user].email
451
452       redirect_to :action => "terms"
453     else
454       user = User.find_by(:auth_provider => provider, :auth_uid => uid)
455
456       if user.nil? && provider == "google"
457         openid_url = auth_info[:extra][:id_info]["openid_id"]
458         user = User.find_by(:auth_provider => "openid", :auth_uid => openid_url) if openid_url
459         user&.update(:auth_provider => provider, :auth_uid => uid)
460       end
461
462       if user
463         case user.status
464         when "pending"
465           unconfirmed_login(user)
466         when "active", "confirmed"
467           successful_login(user, request.env["omniauth.params"]["referer"])
468         when "suspended"
469           failed_login t("users.login.account is suspended", :webmaster => "mailto:#{Settings.support_email}").html_safe
470         else
471           failed_login t("users.login.auth failure")
472         end
473       else
474         redirect_to :action => "new", :nickname => name, :email => email,
475                     :auth_provider => provider, :auth_uid => uid
476       end
477     end
478   end
479
480   ##
481   # omniauth failure callback
482   def auth_failure
483     flash[:error] = t("users.auth_failure.#{params[:message]}")
484     redirect_to params[:origin] || login_url
485   end
486
487   private
488
489   ##
490   #
491   def unconfirmed_login(user)
492     session[:token] = user.tokens.create.token
493
494     redirect_to :action => "confirm", :display_name => user.display_name
495
496     session.delete(:remember_me)
497     session.delete(:referer)
498   end
499
500   ##
501   # update a user's details
502   def update_user(user, params)
503     user.display_name = params[:user][:display_name]
504     user.new_email = params[:user][:new_email]
505
506     unless params[:user][:pass_crypt].empty? && params[:user][:pass_crypt_confirmation].empty?
507       user.pass_crypt = params[:user][:pass_crypt]
508       user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
509     end
510
511     if params[:user][:description] != user.description
512       user.description = params[:user][:description]
513       user.description_format = "markdown"
514     end
515
516     user.languages = params[:user][:languages].split(",")
517
518     case params[:avatar_action]
519     when "new"
520       user.avatar.attach(params[:user][:avatar])
521       user.image_use_gravatar = false
522     when "delete"
523       user.avatar.purge_later
524       user.image_use_gravatar = false
525     when "gravatar"
526       user.avatar.purge_later
527       user.image_use_gravatar = true
528     end
529
530     user.home_lat = params[:user][:home_lat]
531     user.home_lon = params[:user][:home_lon]
532
533     user.preferred_editor = if params[:user][:preferred_editor] == "default"
534                               nil
535                             else
536                               params[:user][:preferred_editor]
537                             end
538
539     if params[:user][:auth_provider].nil? || params[:user][:auth_provider].blank?
540       user.auth_provider = nil
541       user.auth_uid = nil
542     end
543
544     if user.save
545       session[:fingerprint] = user.fingerprint
546
547       set_locale(:reset => true)
548
549       if user.new_email.blank? || user.new_email == user.email
550         flash[:notice] = t "users.account.flash update success"
551       else
552         user.email = user.new_email
553
554         if user.valid?
555           flash[:notice] = t "users.account.flash update success confirm needed"
556
557           begin
558             UserMailer.email_confirm(user, user.tokens.create).deliver_later
559           rescue StandardError
560             # Ignore errors sending email
561           end
562         else
563           current_user.errors.add(:new_email, current_user.errors[:email])
564           current_user.errors.add(:email, [])
565         end
566
567         user.restore_email!
568       end
569     end
570   end
571
572   ##
573   # require that the user in the URL is the logged in user
574   def require_self
575     head :forbidden if params[:display_name] != current_user.display_name
576   end
577
578   ##
579   # ensure that there is a "user" instance variable
580   def lookup_user_by_name
581     @user = User.find_by(:display_name => params[:display_name])
582   rescue ActiveRecord::RecordNotFound
583     redirect_to :action => "view", :display_name => params[:display_name] unless @user
584   end
585
586   ##
587   # return permitted user parameters
588   def user_params
589     params.require(:user).permit(:email, :email_confirmation, :display_name,
590                                  :auth_provider, :auth_uid,
591                                  :pass_crypt, :pass_crypt_confirmation)
592   end
593
594   ##
595   # check signup acls
596   def check_signup_allowed(email = nil)
597     domain = if email.nil?
598                nil
599              else
600                email.split("@").last
601              end
602
603     mx_servers = if domain.nil?
604                    nil
605                  else
606                    domain_mx_servers(domain)
607                  end
608
609     if blocked = Acl.no_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
610       logger.info "Blocked signup from #{request.remote_ip} for #{email}"
611
612       render :action => "blocked"
613     end
614
615     !blocked
616   end
617
618   ##
619   # get list of MX servers for a domains
620   def domain_mx_servers(domain)
621     Resolv::DNS.open do |dns|
622       dns.getresources(domain, Resolv::DNS::Resource::IN::MX).collect(&:exchange).collect(&:to_s)
623     end
624   end
625
626   ##
627   # check if this user has a gravatar and set the user pref is true
628   def gravatar_enable(user)
629     # code from example https://en.gravatar.com/site/implement/images/ruby/
630     return false if user.avatar.attached?
631
632     begin
633       hash = Digest::MD5.hexdigest(user.email.downcase)
634       url = "https://www.gravatar.com/avatar/#{hash}?d=404" # without d=404 we will always get an image back
635       response = OSM.http_client.get(URI.parse(url))
636       available = response.success?
637     rescue StandardError
638       available = false
639     end
640
641     oldsetting = user.image_use_gravatar
642     user.image_use_gravatar = available
643     oldsetting != user.image_use_gravatar
644   end
645
646   ##
647   # display a message about th current status of the gravatar setting
648   def gravatar_status_message(user)
649     if user.image_use_gravatar
650       t "users.account.gravatar.enabled"
651     else
652       t "users.account.gravatar.disabled"
653     end
654   end
655 end