]> git.openstreetmap.org Git - rails.git/blob - app/controllers/users_controller.rb
Merge pull request #4197 from AntonKhorev/user-resources
[rails.git] / app / controllers / users_controller.rb
1 class UsersController < ApplicationController
2   include SessionMethods
3   include UserMethods
4
5   layout "site"
6
7   skip_before_action :verify_authenticity_token, :only => [:auth_success]
8   before_action :disable_terms_redirect, :only => [:terms, :save]
9   before_action :authorize_web
10   before_action :set_locale
11   before_action :check_database_readable
12
13   authorize_resource
14
15   before_action :check_database_writable, :only => [:new, :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]
19
20   ##
21   # display a list of users matching specified criteria
22   def index
23     if request.post?
24       ids = params[:user].keys.collect(&:to_i)
25
26       User.where(:id => ids).update_all(:status => "confirmed") if params[:confirm]
27       User.where(:id => ids).update_all(:status => "deleted") if params[:hide]
28
29       redirect_to url_for(:status => params[:status], :ip => params[:ip], :page => params[:page])
30     else
31       @params = params.permit(:status, :ip)
32
33       conditions = {}
34       conditions[:status] = @params[:status] if @params[:status]
35       conditions[:creation_ip] = @params[:ip] if @params[:ip]
36
37       @user_pages, @users = paginate(:users,
38                                      :conditions => conditions,
39                                      :order => :id,
40                                      :per_page => 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
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
111         redirect_to :action => :terms
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     else
172       self.current_user = session.delete(:new_user)
173
174       if check_signup_allowed(current_user.email)
175         current_user.data_public = true
176         current_user.description = "" if current_user.description.nil?
177         current_user.creation_ip = request.remote_ip
178         current_user.languages = http_accept_language.user_preferred_languages
179         current_user.terms_agreed = Time.now.utc
180         current_user.tou_agreed = Time.now.utc
181         current_user.terms_seen = true
182
183         if current_user.auth_uid.blank?
184           current_user.auth_provider = nil
185           current_user.auth_uid = nil
186         end
187
188         if current_user.save
189           SIGNUP_IP_LIMITER&.update(request.remote_ip)
190           SIGNUP_EMAIL_LIMITER&.update(canonical_email(current_user.email))
191
192           flash[:matomo_goal] = Settings.matomo["goals"]["signup"] if defined?(Settings.matomo)
193
194           referer = welcome_path
195
196           begin
197             uri = URI(session[:referer])
198             %r{map=(.*)/(.*)/(.*)}.match(uri.fragment) do |m|
199               editor = Rack::Utils.parse_query(uri.query).slice("editor")
200               referer = welcome_path({ "zoom" => m[1],
201                                        "lat" => m[2],
202                                        "lon" => m[3] }.merge(editor))
203             end
204           rescue StandardError
205             # Use default
206           end
207
208           if current_user.status == "active"
209             session[:referer] = referer
210             successful_login(current_user)
211           else
212             session[:token] = current_user.tokens.create.token
213             UserMailer.signup_confirm(current_user, current_user.tokens.create(:referer => referer)).deliver_later
214             redirect_to :controller => :confirmations, :action => :confirm, :display_name => current_user.display_name
215           end
216         else
217           render :action => "new", :referer => params[:referer]
218         end
219       end
220     end
221   end
222
223   def go_public
224     current_user.data_public = true
225     current_user.save
226     flash[:notice] = t ".flash success"
227     redirect_to edit_account_path
228   end
229
230   ##
231   # sets a user's status
232   def set_status
233     @user.activate! if params[:event] == "activate"
234     @user.confirm! if params[:event] == "confirm"
235     @user.unconfirm! if params[:event] == "unconfirm"
236     @user.hide! if params[:event] == "hide"
237     @user.unhide! if params[:event] == "unhide"
238     @user.unsuspend! if params[:event] == "unsuspend"
239     redirect_to user_path(:display_name => params[:display_name])
240   end
241
242   ##
243   # omniauth success callback
244   def auth_success
245     auth_info = request.env["omniauth.auth"]
246
247     provider = auth_info[:provider]
248     uid = auth_info[:uid]
249     name = auth_info[:info][:name]
250     email = auth_info[:info][:email]
251
252     email_verified = case provider
253                      when "openid"
254                        uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
255                        uid.match(%r{https://me.yahoo.com/(.*)})
256                      when "google", "facebook", "microsoft"
257                        true
258                      else
259                        false
260                      end
261
262     if settings = session.delete(:new_user_settings)
263       current_user.auth_provider = provider
264       current_user.auth_uid = uid
265
266       update_user(current_user, settings)
267
268       flash.discard
269
270       session[:user_errors] = current_user.errors.as_json
271
272       redirect_to edit_account_path
273     elsif session[:new_user]
274       session[:new_user].auth_provider = provider
275       session[:new_user].auth_uid = uid
276
277       session[:new_user].activate if email_verified && email == session[:new_user].email
278
279       redirect_to :action => "terms"
280     else
281       user = User.find_by(:auth_provider => provider, :auth_uid => uid)
282
283       if user.nil? && provider == "google"
284         openid_url = auth_info[:extra][:id_info]["openid_id"]
285         user = User.find_by(:auth_provider => "openid", :auth_uid => openid_url) if openid_url
286         user&.update(:auth_provider => provider, :auth_uid => uid)
287       end
288
289       if user
290         case user.status
291         when "pending"
292           unconfirmed_login(user)
293         when "active", "confirmed"
294           successful_login(user, request.env["omniauth.params"]["referer"])
295         when "suspended"
296           failed_login({ :partial => "sessions/suspended_flash" })
297         else
298           failed_login t("sessions.new.auth failure")
299         end
300       else
301         redirect_to :action => "new", :nickname => name, :email => email,
302                     :auth_provider => provider, :auth_uid => uid
303       end
304     end
305   end
306
307   ##
308   # omniauth failure callback
309   def auth_failure
310     flash[:error] = t(params[:message], :scope => "users.auth_failure", :default => t(".unknown_error"))
311
312     origin = safe_referer(params[:origin]) if params[:origin]
313
314     redirect_to origin || login_url
315   end
316
317   private
318
319   ##
320   # ensure that there is a "user" instance variable
321   def lookup_user_by_name
322     @user = User.find_by(:display_name => params[:display_name])
323   rescue ActiveRecord::RecordNotFound
324     redirect_to :action => "view", :display_name => params[:display_name] unless @user
325   end
326
327   ##
328   # return permitted user parameters
329   def user_params
330     params.require(:user).permit(:email, :email_confirmation, :display_name,
331                                  :auth_provider, :auth_uid,
332                                  :pass_crypt, :pass_crypt_confirmation)
333   end
334
335   ##
336   # check signup acls
337   def check_signup_allowed(email = nil)
338     domain = if email.nil?
339                nil
340              else
341                email.split("@").last
342              end
343
344     mx_servers = if domain.nil?
345                    nil
346                  else
347                    domain_mx_servers(domain)
348                  end
349
350     blocked = Acl.no_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
351
352     blocked ||= SIGNUP_IP_LIMITER && !SIGNUP_IP_LIMITER.allow?(request.remote_ip)
353
354     blocked ||= email && SIGNUP_EMAIL_LIMITER && !SIGNUP_EMAIL_LIMITER.allow?(canonical_email(email))
355
356     if blocked
357       logger.info "Blocked signup from #{request.remote_ip} for #{email}"
358
359       render :action => "blocked"
360     end
361
362     !blocked
363   end
364
365   def canonical_email(email)
366     local_part, domain = if email.nil?
367                            nil
368                          else
369                            email.split("@")
370                          end
371
372     local_part.sub!(/\+.*$/, "")
373
374     local_part.delete!(".") if %w[gmail.com googlemail.com].include?(domain)
375
376     "#{local_part}@#{domain}"
377   end
378
379   ##
380   # get list of MX servers for a domains
381   def domain_mx_servers(domain)
382     Resolv::DNS.open do |dns|
383       dns.getresources(domain, Resolv::DNS::Resource::IN::MX).collect { |mx| mx.exchange.to_s }
384     end
385   end
386 end