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