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