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