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