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