]> git.openstreetmap.org Git - rails.git/blob - app/controllers/users_controller.rb
Improve fallback behaviour for unsafe referer redirects
[rails.git] / app / controllers / users_controller.rb
1 class UsersController < ApplicationController
2   include SessionMethods
3
4   layout "site"
5
6   skip_before_action :verify_authenticity_token, :only => [:auth_success]
7   before_action :disable_terms_redirect, :only => [:terms, :save]
8   before_action :authorize_web
9   before_action :set_locale
10   before_action :check_database_readable
11
12   authorize_resource
13
14   before_action :require_self, :only => [:account]
15   before_action :check_database_writable, :only => [:new, :account, :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, :account]
19
20   def terms
21     @legale = params[:legale] || OSM.ip_to_country(request.remote_ip) || Settings.default_legale
22     @text = OSM.legal_text_for_country(@legale)
23
24     if request.xhr?
25       render :partial => "terms"
26     else
27       @title = t "users.terms.title"
28
29       if current_user&.terms_agreed?
30         # Already agreed to terms, so just show settings
31         redirect_to user_account_path(current_user)
32       elsif current_user.nil? && session[:new_user].nil?
33         redirect_to login_path(:referer => request.fullpath)
34       end
35     end
36   end
37
38   def save
39     @title = t "users.new.title"
40
41     if params[:decline] || !(params[:read_tou] && params[:read_ct])
42       if current_user
43         current_user.terms_seen = true
44
45         flash[:notice] = { :partial => "users/terms_declined_flash" } if current_user.save
46
47         referer = safe_referer(params[:referer]) if params[:referer]
48
49         redirect_to referer || user_account_path(current_user)
50       elsif params[:decline]
51         redirect_to t("users.terms.declined")
52       else
53         redirect_to :action => :terms
54       end
55     elsif current_user
56       unless current_user.terms_agreed?
57         current_user.consider_pd = params[:user][:consider_pd]
58         current_user.tou_agreed = Time.now.getutc
59         current_user.terms_agreed = Time.now.getutc
60         current_user.terms_seen = true
61
62         flash[:notice] = t "users.new.terms accepted" if current_user.save
63       end
64
65       referer = safe_referer(params[:referer]) if params[:referer]
66
67       redirect_to referer || user_account_path(current_user)
68     else
69       self.current_user = session.delete(:new_user)
70
71       if check_signup_allowed(current_user.email)
72         current_user.data_public = true
73         current_user.description = "" if current_user.description.nil?
74         current_user.creation_ip = request.remote_ip
75         current_user.languages = http_accept_language.user_preferred_languages
76         current_user.terms_agreed = Time.now.getutc
77         current_user.tou_agreed = Time.now.getutc
78         current_user.terms_seen = true
79
80         if current_user.auth_uid.blank?
81           current_user.auth_provider = nil
82           current_user.auth_uid = nil
83         end
84
85         if current_user.save
86           flash[:piwik_goal] = PIWIK["goals"]["signup"] if defined?(PIWIK)
87
88           referer = welcome_path
89
90           begin
91             uri = URI(session[:referer])
92             %r{map=(.*)/(.*)/(.*)}.match(uri.fragment) do |m|
93               editor = Rack::Utils.parse_query(uri.query).slice("editor")
94               referer = welcome_path({ "zoom" => m[1],
95                                        "lat" => m[2],
96                                        "lon" => m[3] }.merge(editor))
97             end
98           rescue StandardError
99             # Use default
100           end
101
102           if current_user.status == "active"
103             session[:referer] = referer
104             successful_login(current_user)
105           else
106             session[:token] = current_user.tokens.create.token
107             UserMailer.signup_confirm(current_user, current_user.tokens.create(:referer => referer)).deliver_later
108             redirect_to :controller => :confirmations, :action => :confirm, :display_name => current_user.display_name
109           end
110         else
111           render :action => "new", :referer => params[:referer]
112         end
113       end
114     end
115   end
116
117   def account
118     @tokens = current_user.oauth_tokens.authorized
119
120     append_content_security_policy_directives(
121       :form_action => %w[accounts.google.com *.facebook.com login.live.com github.com meta.wikimedia.org]
122     )
123
124     if request.post?
125       if params[:user][:auth_provider].blank? ||
126          (params[:user][:auth_provider] == current_user.auth_provider &&
127           params[:user][:auth_uid] == current_user.auth_uid)
128         update_user(current_user, params)
129         redirect_to user_account_url(current_user) if current_user.errors.count.zero?
130       else
131         session[:new_user_settings] = params
132         redirect_to auth_url(params[:user][:auth_provider], params[:user][:auth_uid]), :status => :temporary_redirect
133       end
134     elsif errors = session.delete(:user_errors)
135       errors.each do |attribute, error|
136         current_user.errors.add(attribute, error)
137       end
138     end
139     @title = t "users.account.title"
140   end
141
142   def go_public
143     current_user.data_public = true
144     current_user.save
145     flash[:notice] = t "users.go_public.flash success"
146     redirect_to user_account_path(current_user)
147   end
148
149   def new
150     @title = t "users.new.title"
151     @referer = if params[:referer]
152                  safe_referer(params[:referer])
153                else
154                  session[:referer]
155                end
156
157     append_content_security_policy_directives(
158       :form_action => %w[accounts.google.com *.facebook.com login.live.com github.com meta.wikimedia.org]
159     )
160
161     if current_user
162       # The user is logged in already, so don't show them the signup
163       # page, instead send them to the home page
164       if @referer
165         redirect_to @referer
166       else
167         redirect_to :controller => "site", :action => "index"
168       end
169     elsif params.key?(:auth_provider) && params.key?(:auth_uid)
170       self.current_user = User.new(:email => params[:email],
171                                    :email_confirmation => params[:email],
172                                    :display_name => params[:nickname],
173                                    :auth_provider => params[:auth_provider],
174                                    :auth_uid => params[:auth_uid])
175
176       flash.now[:notice] = render_to_string :partial => "auth_association"
177     else
178       check_signup_allowed
179
180       self.current_user = User.new
181     end
182   end
183
184   def create
185     self.current_user = User.new(user_params)
186
187     if check_signup_allowed(current_user.email)
188       session[:referer] = safe_referer(params[:referer]) if params[:referer]
189
190       Rails.logger.info "create: #{session[:referer]}"
191
192       current_user.status = "pending"
193
194       if current_user.auth_provider.present? && current_user.pass_crypt.empty?
195         # We are creating an account with external authentication and
196         # no password was specified so create a random one
197         current_user.pass_crypt = SecureRandom.base64(16)
198         current_user.pass_crypt_confirmation = current_user.pass_crypt
199       end
200
201       if current_user.invalid?
202         # Something is wrong with a new user, so rerender the form
203         render :action => "new"
204       elsif current_user.auth_provider.present?
205         # Verify external authenticator before moving on
206         session[:new_user] = current_user
207         redirect_to auth_url(current_user.auth_provider, current_user.auth_uid), :status => :temporary_redirect
208       else
209         # Save the user record
210         session[:new_user] = current_user
211         redirect_to :action => :terms
212       end
213     end
214   end
215
216   def show
217     @user = User.find_by(:display_name => params[:display_name])
218
219     if @user &&
220        (@user.visible? || current_user&.administrator?)
221       @title = @user.display_name
222     else
223       render_unknown_user params[:display_name]
224     end
225   end
226
227   ##
228   # sets a user's status
229   def set_status
230     @user.status = params[:status]
231     @user.save
232     redirect_to user_path(:display_name => params[:display_name])
233   end
234
235   ##
236   # delete a user, marking them as deleted and removing personal data
237   def destroy
238     @user.delete
239     redirect_to user_path(:display_name => params[:display_name])
240   end
241
242   ##
243   # display a list of users matching specified criteria
244   def index
245     if request.post?
246       ids = params[:user].keys.collect(&:to_i)
247
248       User.where(:id => ids).update_all(:status => "confirmed") if params[:confirm]
249       User.where(:id => ids).update_all(:status => "deleted") if params[:hide]
250
251       redirect_to url_for(:status => params[:status], :ip => params[:ip], :page => params[:page])
252     else
253       @params = params.permit(:status, :ip)
254
255       conditions = {}
256       conditions[:status] = @params[:status] if @params[:status]
257       conditions[:creation_ip] = @params[:ip] if @params[:ip]
258
259       @user_pages, @users = paginate(:users,
260                                      :conditions => conditions,
261                                      :order => :id,
262                                      :per_page => 50)
263     end
264   end
265
266   ##
267   # omniauth success callback
268   def auth_success
269     auth_info = request.env["omniauth.auth"]
270
271     provider = auth_info[:provider]
272     uid = auth_info[:uid]
273     name = auth_info[:info][:name]
274     email = auth_info[:info][:email]
275
276     email_verified = case provider
277                      when "openid"
278                        uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
279                        uid.match(%r{https://me.yahoo.com/(.*)})
280                      when "google", "facebook"
281                        true
282                      else
283                        false
284                      end
285
286     if settings = session.delete(:new_user_settings)
287       current_user.auth_provider = provider
288       current_user.auth_uid = uid
289
290       update_user(current_user, settings)
291
292       flash.discard
293
294       session[:user_errors] = current_user.errors.as_json
295
296       redirect_to user_account_path(current_user)
297     elsif session[:new_user]
298       session[:new_user].auth_provider = provider
299       session[:new_user].auth_uid = uid
300
301       session[:new_user].status = "active" if email_verified && email == session[:new_user].email
302
303       redirect_to :action => "terms"
304     else
305       user = User.find_by(:auth_provider => provider, :auth_uid => uid)
306
307       if user.nil? && provider == "google"
308         openid_url = auth_info[:extra][:id_info]["openid_id"]
309         user = User.find_by(:auth_provider => "openid", :auth_uid => openid_url) if openid_url
310         user&.update(:auth_provider => provider, :auth_uid => uid)
311       end
312
313       if user
314         case user.status
315         when "pending"
316           unconfirmed_login(user)
317         when "active", "confirmed"
318           successful_login(user, request.env["omniauth.params"]["referer"])
319         when "suspended"
320           failed_login t("sessions.new.account is suspended", :webmaster => "mailto:#{Settings.support_email}").html_safe
321         else
322           failed_login t("sessions.new.auth failure")
323         end
324       else
325         redirect_to :action => "new", :nickname => name, :email => email,
326                     :auth_provider => provider, :auth_uid => uid
327       end
328     end
329   end
330
331   ##
332   # omniauth failure callback
333   def auth_failure
334     flash[:error] = t(params[:message], :scope => "users.auth_failure", :default => t("users.auth_failure.unknown_error"))
335     redirect_to params[:origin] || login_url
336   end
337
338   private
339
340   ##
341   # update a user's details
342   def update_user(user, params)
343     user.display_name = params[:user][:display_name]
344     user.new_email = params[:user][:new_email]
345
346     unless params[:user][:pass_crypt].empty? && params[:user][:pass_crypt_confirmation].empty?
347       user.pass_crypt = params[:user][:pass_crypt]
348       user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
349     end
350
351     if params[:user][:auth_provider].nil? || params[:user][:auth_provider].blank?
352       user.auth_provider = nil
353       user.auth_uid = nil
354     end
355
356     if user.save
357       session[:fingerprint] = user.fingerprint
358
359       if user.new_email.blank? || user.new_email == user.email
360         flash[:notice] = t "users.account.flash update success"
361       else
362         user.email = user.new_email
363
364         if user.valid?
365           flash[:notice] = t "users.account.flash update success confirm needed"
366
367           begin
368             UserMailer.email_confirm(user, user.tokens.create).deliver_later
369           rescue StandardError
370             # Ignore errors sending email
371           end
372         else
373           current_user.errors.add(:new_email, current_user.errors[:email])
374           current_user.errors.add(:email, [])
375         end
376
377         user.restore_email!
378       end
379     end
380   end
381
382   ##
383   # require that the user in the URL is the logged in user
384   def require_self
385     head :forbidden if params[:display_name] != current_user.display_name
386   end
387
388   ##
389   # ensure that there is a "user" instance variable
390   def lookup_user_by_name
391     @user = User.find_by(:display_name => params[:display_name])
392   rescue ActiveRecord::RecordNotFound
393     redirect_to :action => "view", :display_name => params[:display_name] unless @user
394   end
395
396   ##
397   # return permitted user parameters
398   def user_params
399     params.require(:user).permit(:email, :email_confirmation, :display_name,
400                                  :auth_provider, :auth_uid,
401                                  :pass_crypt, :pass_crypt_confirmation)
402   end
403
404   ##
405   # check signup acls
406   def check_signup_allowed(email = nil)
407     domain = if email.nil?
408                nil
409              else
410                email.split("@").last
411              end
412
413     mx_servers = if domain.nil?
414                    nil
415                  else
416                    domain_mx_servers(domain)
417                  end
418
419     if blocked = Acl.no_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
420       logger.info "Blocked signup from #{request.remote_ip} for #{email}"
421
422       render :action => "blocked"
423     end
424
425     !blocked
426   end
427
428   ##
429   # get list of MX servers for a domains
430   def domain_mx_servers(domain)
431     Resolv::DNS.open do |dns|
432       dns.getresources(domain, Resolv::DNS::Resource::IN::MX).collect(&:exchange).collect(&:to_s)
433     end
434   end
435 end