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