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