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