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