]> git.openstreetmap.org Git - rails.git/blob - app/controllers/users_controller.rb
Merge remote-tracking branch 'upstream/pull/3166'
[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, :go_public]
16   before_action :require_cookies, :only => [:new]
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 :controller => :confirmations, :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 new
154     @title = t "users.new.title"
155     @referer = if params[:referer]
156                  safe_referer(params[:referer])
157                else
158                  session[:referer]
159                end
160
161     append_content_security_policy_directives(
162       :form_action => %w[accounts.google.com *.facebook.com login.live.com github.com meta.wikimedia.org]
163     )
164
165     if current_user
166       # The user is logged in already, so don't show them the signup
167       # page, instead send them to the home page
168       if @referer
169         redirect_to @referer
170       else
171         redirect_to :controller => "site", :action => "index"
172       end
173     elsif params.key?(:auth_provider) && params.key?(:auth_uid)
174       self.current_user = User.new(:email => params[:email],
175                                    :email_confirmation => params[:email],
176                                    :display_name => params[:nickname],
177                                    :auth_provider => params[:auth_provider],
178                                    :auth_uid => params[:auth_uid])
179
180       flash.now[:notice] = render_to_string :partial => "auth_association"
181     else
182       check_signup_allowed
183
184       self.current_user = User.new
185     end
186   end
187
188   def create
189     self.current_user = User.new(user_params)
190
191     if check_signup_allowed(current_user.email)
192       session[:referer] = safe_referer(params[:referer]) if params[:referer]
193
194       Rails.logger.info "create: #{session[:referer]}"
195
196       current_user.status = "pending"
197
198       if current_user.auth_provider.present? && current_user.pass_crypt.empty?
199         # We are creating an account with external authentication and
200         # no password was specified so create a random one
201         current_user.pass_crypt = SecureRandom.base64(16)
202         current_user.pass_crypt_confirmation = current_user.pass_crypt
203       end
204
205       if current_user.invalid?
206         # Something is wrong with a new user, so rerender the form
207         render :action => "new"
208       elsif current_user.auth_provider.present?
209         # Verify external authenticator before moving on
210         session[:new_user] = current_user
211         redirect_to auth_url(current_user.auth_provider, current_user.auth_uid), :status => :temporary_redirect
212       else
213         # Save the user record
214         session[:new_user] = current_user
215         redirect_to :action => :terms
216       end
217     end
218   end
219
220   def show
221     @user = User.find_by(:display_name => params[:display_name])
222
223     if @user &&
224        (@user.visible? || current_user&.administrator?)
225       @title = @user.display_name
226     else
227       render_unknown_user params[:display_name]
228     end
229   end
230
231   ##
232   # sets a user's status
233   def set_status
234     @user.status = params[:status]
235     @user.save
236     redirect_to user_path(:display_name => params[:display_name])
237   end
238
239   ##
240   # delete a user, marking them as deleted and removing personal data
241   def destroy
242     @user.delete
243     redirect_to user_path(:display_name => params[:display_name])
244   end
245
246   ##
247   # display a list of users matching specified criteria
248   def index
249     if request.post?
250       ids = params[:user].keys.collect(&:to_i)
251
252       User.where(:id => ids).update_all(:status => "confirmed") if params[:confirm]
253       User.where(:id => ids).update_all(:status => "deleted") if params[:hide]
254
255       redirect_to url_for(:status => params[:status], :ip => params[:ip], :page => params[:page])
256     else
257       @params = params.permit(:status, :ip)
258
259       conditions = {}
260       conditions[:status] = @params[:status] if @params[:status]
261       conditions[:creation_ip] = @params[:ip] if @params[:ip]
262
263       @user_pages, @users = paginate(:users,
264                                      :conditions => conditions,
265                                      :order => :id,
266                                      :per_page => 50)
267     end
268   end
269
270   ##
271   # omniauth success callback
272   def auth_success
273     auth_info = request.env["omniauth.auth"]
274
275     provider = auth_info[:provider]
276     uid = auth_info[:uid]
277     name = auth_info[:info][:name]
278     email = auth_info[:info][:email]
279
280     case provider
281     when "openid"
282       email_verified = uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
283                        uid.match(%r{https://me.yahoo.com/(.*)})
284     when "google", "facebook"
285       email_verified = true
286     else
287       email_verified = false
288     end
289
290     if settings = session.delete(:new_user_settings)
291       current_user.auth_provider = provider
292       current_user.auth_uid = uid
293
294       update_user(current_user, settings)
295
296       flash.discard
297
298       session[:user_errors] = current_user.errors.as_json
299
300       redirect_to :action => "account", :display_name => current_user.display_name
301     elsif session[:new_user]
302       session[:new_user].auth_provider = provider
303       session[:new_user].auth_uid = uid
304
305       session[:new_user].status = "active" if email_verified && email == session[:new_user].email
306
307       redirect_to :action => "terms"
308     else
309       user = User.find_by(:auth_provider => provider, :auth_uid => uid)
310
311       if user.nil? && provider == "google"
312         openid_url = auth_info[:extra][:id_info]["openid_id"]
313         user = User.find_by(:auth_provider => "openid", :auth_uid => openid_url) if openid_url
314         user&.update(:auth_provider => provider, :auth_uid => uid)
315       end
316
317       if user
318         case user.status
319         when "pending"
320           unconfirmed_login(user)
321         when "active", "confirmed"
322           successful_login(user, request.env["omniauth.params"]["referer"])
323         when "suspended"
324           failed_login t("users.login.account is suspended", :webmaster => "mailto:#{Settings.support_email}").html_safe
325         else
326           failed_login t("users.login.auth failure")
327         end
328       else
329         redirect_to :action => "new", :nickname => name, :email => email,
330                     :auth_provider => provider, :auth_uid => uid
331       end
332     end
333   end
334
335   ##
336   # omniauth failure callback
337   def auth_failure
338     flash[:error] = t("users.auth_failure.#{params[:message]}")
339     redirect_to params[:origin] || login_url
340   end
341
342   private
343
344   ##
345   #
346   def unconfirmed_login(user)
347     session[:token] = user.tokens.create.token
348
349     redirect_to :action => "confirm", :display_name => user.display_name
350
351     session.delete(:remember_me)
352     session.delete(:referer)
353   end
354
355   ##
356   # update a user's details
357   def update_user(user, params)
358     user.display_name = params[:user][:display_name]
359     user.new_email = params[:user][:new_email]
360
361     unless params[:user][:pass_crypt].empty? && params[:user][:pass_crypt_confirmation].empty?
362       user.pass_crypt = params[:user][:pass_crypt]
363       user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
364     end
365
366     if params[:user][:description] != user.description
367       user.description = params[:user][:description]
368       user.description_format = "markdown"
369     end
370
371     user.languages = params[:user][:languages].split(",")
372
373     case params[:avatar_action]
374     when "new"
375       user.avatar.attach(params[:user][:avatar])
376       user.image_use_gravatar = false
377     when "delete"
378       user.avatar.purge_later
379       user.image_use_gravatar = false
380     when "gravatar"
381       user.avatar.purge_later
382       user.image_use_gravatar = true
383     end
384
385     user.home_lat = params[:user][:home_lat]
386     user.home_lon = params[:user][:home_lon]
387
388     user.preferred_editor = if params[:user][:preferred_editor] == "default"
389                               nil
390                             else
391                               params[:user][:preferred_editor]
392                             end
393
394     if params[:user][:auth_provider].nil? || params[:user][:auth_provider].blank?
395       user.auth_provider = nil
396       user.auth_uid = nil
397     end
398
399     if user.save
400       session[:fingerprint] = user.fingerprint
401
402       set_locale(:reset => true)
403
404       if user.new_email.blank? || user.new_email == user.email
405         flash[:notice] = t "users.account.flash update success"
406       else
407         user.email = user.new_email
408
409         if user.valid?
410           flash[:notice] = t "users.account.flash update success confirm needed"
411
412           begin
413             UserMailer.email_confirm(user, user.tokens.create).deliver_later
414           rescue StandardError
415             # Ignore errors sending email
416           end
417         else
418           current_user.errors.add(:new_email, current_user.errors[:email])
419           current_user.errors.add(:email, [])
420         end
421
422         user.restore_email!
423       end
424     end
425   end
426
427   ##
428   # require that the user in the URL is the logged in user
429   def require_self
430     head :forbidden if params[:display_name] != current_user.display_name
431   end
432
433   ##
434   # ensure that there is a "user" instance variable
435   def lookup_user_by_name
436     @user = User.find_by(:display_name => params[:display_name])
437   rescue ActiveRecord::RecordNotFound
438     redirect_to :action => "view", :display_name => params[:display_name] unless @user
439   end
440
441   ##
442   # return permitted user parameters
443   def user_params
444     params.require(:user).permit(:email, :email_confirmation, :display_name,
445                                  :auth_provider, :auth_uid,
446                                  :pass_crypt, :pass_crypt_confirmation)
447   end
448
449   ##
450   # check signup acls
451   def check_signup_allowed(email = nil)
452     domain = if email.nil?
453                nil
454              else
455                email.split("@").last
456              end
457
458     mx_servers = if domain.nil?
459                    nil
460                  else
461                    domain_mx_servers(domain)
462                  end
463
464     if blocked = Acl.no_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
465       logger.info "Blocked signup from #{request.remote_ip} for #{email}"
466
467       render :action => "blocked"
468     end
469
470     !blocked
471   end
472
473   ##
474   # get list of MX servers for a domains
475   def domain_mx_servers(domain)
476     Resolv::DNS.open do |dns|
477       dns.getresources(domain, Resolv::DNS::Resource::IN::MX).collect(&:exchange).collect(&:to_s)
478     end
479   end
480 end