]> git.openstreetmap.org Git - rails.git/blob - app/controllers/users_controller.rb
Merge remote-tracking branch 'upstream/pull/4486'
[rails.git] / app / controllers / users_controller.rb
1 class UsersController < ApplicationController
2   include EmailMethods
3   include SessionMethods
4   include UserMethods
5
6   layout "site"
7
8   skip_before_action :verify_authenticity_token, :only => [:auth_success]
9   before_action :disable_terms_redirect, :only => [:terms, :save]
10   before_action :authorize_web
11   before_action :set_locale
12   before_action :check_database_readable
13
14   authorize_resource
15
16   before_action :check_database_writable, :only => [:new, :go_public]
17   before_action :require_cookies, :only => [:new]
18   before_action :lookup_user_by_name, :only => [:set_status, :destroy]
19   before_action :allow_thirdparty_images, :only => [:show]
20
21   ##
22   # display a list of users matching specified criteria
23   def index
24     if request.post?
25       ids = params[:user].keys.collect(&:to_i)
26
27       User.where(:id => ids).update_all(:status => "confirmed") if params[:confirm]
28       User.where(:id => ids).update_all(:status => "deleted") if params[:hide]
29
30       redirect_to url_for(:status => params[:status], :ip => params[:ip], :page => params[:page])
31     else
32       @params = params.permit(:status, :ip)
33
34       conditions = {}
35       conditions[:status] = @params[:status] if @params[:status]
36       conditions[:creation_ip] = @params[:ip] if @params[:ip]
37
38       @user_pages, @users = paginate(:users,
39                                      :conditions => conditions,
40                                      :order => :id,
41                                      :per_page => 50)
42     end
43   end
44
45   def show
46     @user = User.find_by(:display_name => params[:display_name])
47
48     if @user &&
49        (@user.visible? || current_user&.administrator?)
50       @title = @user.display_name
51     else
52       render_unknown_user params[:display_name]
53     end
54   end
55
56   def new
57     @title = t ".title"
58     @referer = if params[:referer]
59                  safe_referer(params[:referer])
60                else
61                  session[:referer]
62                end
63
64     append_content_security_policy_directives(
65       :form_action => %w[accounts.google.com *.facebook.com login.live.com github.com meta.wikimedia.org]
66     )
67
68     if current_user
69       # The user is logged in already, so don't show them the signup
70       # page, instead send them to the home page
71       redirect_to @referer || { :controller => "site", :action => "index" }
72     elsif params.key?(:auth_provider) && params.key?(:auth_uid)
73       self.current_user = User.new(:email => params[:email],
74                                    :email_confirmation => params[:email],
75                                    :display_name => params[:nickname],
76                                    :auth_provider => params[:auth_provider],
77                                    :auth_uid => params[:auth_uid])
78
79       flash.now[:notice] = render_to_string :partial => "auth_association"
80     else
81       check_signup_allowed
82
83       self.current_user = User.new
84     end
85   end
86
87   def create
88     self.current_user = User.new(user_params)
89
90     if check_signup_allowed(current_user.email)
91       session[:referer] = safe_referer(params[:referer]) if params[:referer]
92
93       Rails.logger.info "create: #{session[:referer]}"
94
95       if current_user.auth_provider.present? && current_user.pass_crypt.empty?
96         # We are creating an account with external authentication and
97         # no password was specified so create a random one
98         current_user.pass_crypt = SecureRandom.base64(16)
99         current_user.pass_crypt_confirmation = current_user.pass_crypt
100       end
101
102       if current_user.invalid?
103         # Something is wrong with a new user, so rerender the form
104         render :action => "new"
105       elsif current_user.auth_provider.present?
106         # Verify external authenticator before moving on
107         session[:new_user] = current_user.slice("email", "display_name", "pass_crypt", "pass_crypt_confirmation")
108         redirect_to auth_url(current_user.auth_provider, current_user.auth_uid), :status => :temporary_redirect
109       else
110         # Save the user record
111         session[:new_user] = current_user.slice("email", "display_name", "pass_crypt", "pass_crypt_confirmation")
112         redirect_to :action => :terms
113       end
114     end
115   end
116
117   ##
118   # destroy a user, marking them as deleted and removing personal data
119   def destroy
120     @user.soft_destroy!
121     redirect_to user_path(:display_name => params[:display_name])
122   end
123
124   def terms
125     @legale = params[:legale] || OSM.ip_to_country(request.remote_ip) || Settings.default_legale
126     @text = OSM.legal_text_for_country(@legale)
127
128     if request.xhr?
129       render :partial => "terms"
130     else
131       @title = t ".title"
132
133       if current_user&.terms_agreed?
134         # Already agreed to terms, so just show settings
135         redirect_to edit_account_path
136       elsif current_user.nil? && session[:new_user].nil?
137         redirect_to login_path(:referer => request.fullpath)
138       end
139     end
140   end
141
142   def save
143     @title = t "users.new.title"
144
145     if params[:decline] || !(params[:read_tou] && params[:read_ct])
146       if current_user
147         current_user.terms_seen = true
148
149         flash[:notice] = { :partial => "users/terms_declined_flash" } if current_user.save
150
151         referer = safe_referer(params[:referer]) if params[:referer]
152
153         redirect_to referer || edit_account_path
154       elsif params[:decline]
155         redirect_to t("users.terms.declined"), :allow_other_host => true
156       else
157         redirect_to :action => :terms
158       end
159     elsif current_user
160       unless current_user.terms_agreed?
161         current_user.consider_pd = params[:user][:consider_pd]
162         current_user.tou_agreed = Time.now.utc
163         current_user.terms_agreed = Time.now.utc
164         current_user.terms_seen = true
165
166         flash[:notice] = t "users.new.terms accepted" if current_user.save
167       end
168
169       referer = safe_referer(params[:referer]) if params[:referer]
170
171       redirect_to referer || edit_account_path
172     else
173       new_user = session.delete(:new_user)
174       verified_email = new_user.delete("verified_email")
175
176       self.current_user = User.new(new_user)
177
178       if check_signup_allowed(current_user.email)
179         current_user.data_public = true
180         current_user.description = "" if current_user.description.nil?
181         current_user.creation_ip = request.remote_ip
182         current_user.languages = http_accept_language.user_preferred_languages
183         current_user.terms_agreed = Time.now.utc
184         current_user.tou_agreed = Time.now.utc
185         current_user.terms_seen = true
186
187         if current_user.auth_uid.blank?
188           current_user.auth_provider = nil
189           current_user.auth_uid = nil
190         elsif current_user.email == verified_email
191           current_user.activate
192         end
193
194         if current_user.save
195           SIGNUP_IP_LIMITER&.update(request.remote_ip)
196           SIGNUP_EMAIL_LIMITER&.update(canonical_email(current_user.email))
197
198           flash[:matomo_goal] = Settings.matomo["goals"]["signup"] if defined?(Settings.matomo)
199
200           referer = welcome_path(welcome_options)
201
202           if current_user.status == "active"
203             session[:referer] = referer
204             successful_login(current_user)
205           else
206             session[:token] = current_user.tokens.create.token
207             UserMailer.signup_confirm(current_user, current_user.tokens.create(:referer => referer)).deliver_later
208             redirect_to :controller => :confirmations, :action => :confirm, :display_name => current_user.display_name
209           end
210         else
211           render :action => "new", :referer => params[:referer]
212         end
213       end
214     end
215   end
216
217   def go_public
218     current_user.data_public = true
219     current_user.save
220     flash[:notice] = t ".flash success"
221     redirect_to edit_account_path
222   end
223
224   ##
225   # sets a user's status
226   def set_status
227     @user.activate! if params[:event] == "activate"
228     @user.confirm! if params[:event] == "confirm"
229     @user.unconfirm! if params[:event] == "unconfirm"
230     @user.hide! if params[:event] == "hide"
231     @user.unhide! if params[:event] == "unhide"
232     @user.unsuspend! if params[:event] == "unsuspend"
233     redirect_to user_path(:display_name => params[:display_name])
234   end
235
236   ##
237   # omniauth success callback
238   def auth_success
239     auth_info = request.env["omniauth.auth"]
240
241     provider = auth_info[:provider]
242     uid = auth_info[:uid]
243     name = auth_info[:info][:name]
244     email = auth_info[:info][:email]
245
246     email_verified = case provider
247                      when "openid"
248                        uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
249                        uid.match(%r{https://me.yahoo.com/(.*)})
250                      when "google", "facebook", "microsoft"
251                        true
252                      else
253                        false
254                      end
255
256     if settings = session.delete(:new_user_settings)
257       current_user.auth_provider = provider
258       current_user.auth_uid = uid
259
260       update_user(current_user, settings)
261
262       flash.discard
263
264       session[:user_errors] = current_user.errors.as_json
265
266       redirect_to edit_account_path
267     elsif session[:new_user]
268       session[:new_user]["auth_provider"] = provider
269       session[:new_user]["auth_uid"] = uid
270       session[:new_user]["verified_email"] = email if email_verified
271
272       redirect_to :action => "terms"
273     else
274       user = User.find_by(:auth_provider => provider, :auth_uid => uid)
275
276       if user.nil? && provider == "google"
277         openid_url = auth_info[:extra][:id_info]["openid_id"]
278         user = User.find_by(:auth_provider => "openid", :auth_uid => openid_url) if openid_url
279         user&.update(:auth_provider => provider, :auth_uid => uid)
280       end
281
282       if user
283         case user.status
284         when "pending"
285           unconfirmed_login(user)
286         when "active", "confirmed"
287           successful_login(user, request.env["omniauth.params"]["referer"])
288         when "suspended"
289           failed_login({ :partial => "sessions/suspended_flash" })
290         else
291           failed_login t("sessions.new.auth failure")
292         end
293       else
294         redirect_to :action => "new", :nickname => name, :email => email,
295                     :auth_provider => provider, :auth_uid => uid
296       end
297     end
298   end
299
300   ##
301   # omniauth failure callback
302   def auth_failure
303     flash[:error] = t(params[:message], :scope => "users.auth_failure", :default => t(".unknown_error"))
304
305     origin = safe_referer(params[:origin]) if params[:origin]
306
307     redirect_to origin || login_url
308   end
309
310   private
311
312   def welcome_options
313     uri = URI(session[:referer]) if session[:referer].present?
314
315     return { "oauth_return_url" => uri&.to_s } if uri&.path == oauth_authorization_path
316
317     begin
318       %r{map=(.*)/(.*)/(.*)}.match(uri.fragment) do |m|
319         editor = Rack::Utils.parse_query(uri.query).slice("editor")
320         return { "zoom" => m[1], "lat" => m[2], "lon" => m[3] }.merge(editor)
321       end
322     rescue StandardError
323       # Use default
324     end
325   end
326
327   ##
328   # ensure that there is a "user" instance variable
329   def lookup_user_by_name
330     @user = User.find_by(:display_name => params[:display_name])
331   rescue ActiveRecord::RecordNotFound
332     redirect_to :action => "view", :display_name => params[:display_name] unless @user
333   end
334
335   ##
336   # return permitted user parameters
337   def user_params
338     params.require(:user).permit(:email, :email_confirmation, :display_name,
339                                  :auth_provider, :auth_uid,
340                                  :pass_crypt, :pass_crypt_confirmation)
341   end
342
343   ##
344   # check signup acls
345   def check_signup_allowed(email = nil)
346     domain = if email.nil?
347                nil
348              else
349                email.split("@").last
350              end
351
352     mx_servers = if domain.nil?
353                    nil
354                  else
355                    domain_mx_servers(domain)
356                  end
357
358     return true if Acl.allow_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
359
360     blocked = Acl.no_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
361
362     blocked ||= SIGNUP_IP_LIMITER && !SIGNUP_IP_LIMITER.allow?(request.remote_ip)
363
364     blocked ||= email && SIGNUP_EMAIL_LIMITER && !SIGNUP_EMAIL_LIMITER.allow?(canonical_email(email))
365
366     if blocked
367       logger.info "Blocked signup from #{request.remote_ip} for #{email}"
368
369       render :action => "blocked"
370     end
371
372     !blocked
373   end
374 end