]> git.openstreetmap.org Git - rails.git/blob - app/controllers/users_controller.rb
Merge remote-tracking branch 'upstream/pull/5391'
[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         save_new_user params[:email_hmac], params[:referer]
81       end
82     end
83   end
84
85   ##
86   # destroy a user, marking them as deleted and removing personal data
87   def destroy
88     @user.soft_destroy!
89     redirect_to user_path(:display_name => params[:display_name])
90   end
91
92   def terms
93     @legale = params[:legale] || OSM.ip_to_country(request.remote_ip) || Settings.default_legale
94     @text = OSM.legal_text_for_country(@legale)
95
96     if request.xhr?
97       render :partial => "terms"
98     else
99       @title = t ".title"
100
101       if current_user&.terms_agreed?
102         # Already agreed to terms, so just show settings
103         redirect_to edit_account_path
104       elsif current_user.nil?
105         redirect_to login_path(:referer => request.fullpath)
106       end
107     end
108   end
109
110   def save
111     @title = t "users.new.title"
112
113     if params[:decline] || !(params[:read_tou] && params[:read_ct])
114       if current_user
115         current_user.terms_seen = true
116
117         flash[:notice] = { :partial => "users/terms_declined_flash" } if current_user.save
118
119         referer = safe_referer(params[:referer]) if params[:referer]
120
121         redirect_to referer || edit_account_path
122       elsif params[:decline]
123         redirect_to t("users.terms.declined"), :allow_other_host => true
124       else
125         redirect_to :action => :terms
126       end
127     elsif current_user
128       unless current_user.terms_agreed?
129         current_user.consider_pd = params[:user][:consider_pd]
130         current_user.tou_agreed = Time.now.utc
131         current_user.terms_agreed = Time.now.utc
132         current_user.terms_seen = true
133
134         flash[:notice] = t "users.new.terms accepted" if current_user.save
135       end
136
137       referer = safe_referer(params[:referer]) if params[:referer]
138
139       redirect_to referer || edit_account_path
140     end
141   end
142
143   def go_public
144     current_user.data_public = true
145     current_user.save
146     flash[:notice] = t ".flash success"
147     redirect_to edit_account_path
148   end
149
150   ##
151   # sets a user's status
152   def set_status
153     @user.activate! if params[:event] == "activate"
154     @user.confirm! if params[:event] == "confirm"
155     @user.unconfirm! if params[:event] == "unconfirm"
156     @user.hide! if params[:event] == "hide"
157     @user.unhide! if params[:event] == "unhide"
158     @user.unsuspend! if params[:event] == "unsuspend"
159     redirect_to user_path(:display_name => params[:display_name])
160   end
161
162   ##
163   # omniauth success callback
164   def auth_success
165     referer = request.env["omniauth.params"]["referer"]
166     auth_info = request.env["omniauth.auth"]
167
168     provider = auth_info[:provider]
169     uid = auth_info[:uid]
170     name = auth_info[:info][:name]
171     email = auth_info[:info][:email]
172
173     email_verified = case provider
174                      when "openid"
175                        uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
176                        uid.match(%r{https://me.yahoo.com/(.*)})
177                      when "google", "facebook", "microsoft", "github", "wikipedia"
178                        true
179                      else
180                        false
181                      end
182
183     if settings = session.delete(:new_user_settings)
184       current_user.auth_provider = provider
185       current_user.auth_uid = uid
186
187       update_user(current_user, settings)
188
189       flash.discard
190
191       session[:user_errors] = current_user.errors.as_json
192
193       redirect_to edit_account_path
194     else
195       user = User.find_by(:auth_provider => provider, :auth_uid => uid)
196
197       if user.nil? && provider == "google"
198         openid_url = auth_info[:extra][:id_info]["openid_id"]
199         user = User.find_by(:auth_provider => "openid", :auth_uid => openid_url) if openid_url
200         user&.update(:auth_provider => provider, :auth_uid => uid)
201       end
202
203       if user
204         case user.status
205         when "pending"
206           unconfirmed_login(user, referer)
207         when "active", "confirmed"
208           successful_login(user, referer)
209         when "suspended"
210           failed_login({ :partial => "sessions/suspended_flash" }, user.display_name, referer)
211         else
212           failed_login(t("sessions.new.auth failure"), user.display_name, referer)
213         end
214       else
215         email_hmac = UsersController.message_hmac(email) if email_verified && email
216         redirect_to :action => "new", :nickname => name, :email => email, :email_hmac => email_hmac,
217                     :auth_provider => provider, :auth_uid => uid, :referer => referer
218       end
219     end
220   end
221
222   ##
223   # omniauth failure callback
224   def auth_failure
225     flash[:error] = t(params[:message], :scope => "users.auth_failure", :default => t(".unknown_error"))
226
227     origin = safe_referer(params[:origin]) if params[:origin]
228
229     redirect_to origin || login_url
230   end
231
232   def self.message_hmac(text)
233     sha256 = Digest::SHA256.new
234     sha256 << Rails.application.key_generator.generate_key("openstreetmap/email_address")
235     sha256 << text
236     Base64.urlsafe_encode64(sha256.digest)
237   end
238
239   private
240
241   def save_new_user(email_hmac, referer = nil)
242     current_user.data_public = true
243     current_user.description = "" if current_user.description.nil?
244     current_user.creation_address = request.remote_ip
245     current_user.languages = http_accept_language.user_preferred_languages
246     current_user.terms_agreed = Time.now.utc
247     current_user.tou_agreed = Time.now.utc
248     current_user.terms_seen = true
249
250     if current_user.auth_uid.blank?
251       current_user.auth_provider = nil
252       current_user.auth_uid = nil
253     elsif email_hmac && ActiveSupport::SecurityUtils.secure_compare(email_hmac, UsersController.message_hmac(current_user.email))
254       current_user.activate
255     end
256
257     if current_user.save
258       SIGNUP_IP_LIMITER&.update(request.remote_ip)
259       SIGNUP_EMAIL_LIMITER&.update(canonical_email(current_user.email))
260
261       flash[:matomo_goal] = Settings.matomo["goals"]["signup"] if defined?(Settings.matomo)
262
263       referer = welcome_path(welcome_options(referer))
264
265       if current_user.status == "active"
266         successful_login(current_user, referer)
267       else
268         session[:pending_user] = current_user.id
269         UserMailer.signup_confirm(current_user, current_user.generate_token_for(:new_user), referer).deliver_later
270         redirect_to :controller => :confirmations, :action => :confirm, :display_name => current_user.display_name
271       end
272     else
273       render :action => "new", :referer => params[:referer]
274     end
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