]> git.openstreetmap.org Git - rails.git/blob - app/controllers/users_controller.rb
Add missing callbacks to session controller
[rails.git] / app / controllers / users_controller.rb
1 class UsersController < ApplicationController
2   include SessionMethods
3
4   layout "site"
5
6   skip_before_action :verify_authenticity_token, :only => [:auth_success]
7   before_action :disable_terms_redirect, :only => [:terms, :save]
8   before_action :authorize_web
9   before_action :set_locale
10   before_action :check_database_readable
11
12   authorize_resource
13
14   before_action :require_self, :only => [:account]
15   before_action :check_database_writable, :only => [:new, :account, :confirm, :confirm_email, :lost_password, :reset_password, :go_public]
16   before_action :require_cookies, :only => [:new, :confirm]
17   before_action :lookup_user_by_name, :only => [:set_status, :destroy]
18   before_action :allow_thirdparty_images, :only => [:show, :account]
19
20   def terms
21     @legale = params[:legale] || OSM.ip_to_country(request.remote_ip) || Settings.default_legale
22     @text = OSM.legal_text_for_country(@legale)
23
24     if request.xhr?
25       render :partial => "terms"
26     else
27       @title = t "users.terms.title"
28
29       if current_user&.terms_agreed?
30         # Already agreed to terms, so just show settings
31         redirect_to :action => :account, :display_name => current_user.display_name
32       elsif current_user.nil? && session[:new_user].nil?
33         redirect_to :action => :login, :referer => request.fullpath
34       end
35     end
36   end
37
38   def save
39     @title = t "users.new.title"
40
41     if params[:decline] || !(params[:read_tou] && params[:read_ct])
42       if current_user
43         current_user.terms_seen = true
44
45         flash[:notice] = t("users.new.terms declined", :url => t("users.new.terms declined url")).html_safe if current_user.save
46
47         if params[:referer]
48           redirect_to safe_referer(params[:referer])
49         else
50           redirect_to :action => :account, :display_name => current_user.display_name
51         end
52       elsif params[:decline]
53         redirect_to t("users.terms.declined")
54       else
55         redirect_to :action => :terms
56       end
57     elsif current_user
58       unless current_user.terms_agreed?
59         current_user.consider_pd = params[:user][:consider_pd]
60         current_user.tou_agreed = Time.now.getutc
61         current_user.terms_agreed = Time.now.getutc
62         current_user.terms_seen = true
63
64         flash[:notice] = t "users.new.terms accepted" if current_user.save
65       end
66
67       if params[:referer]
68         redirect_to safe_referer(params[:referer])
69       else
70         redirect_to :action => :account, :display_name => current_user.display_name
71       end
72     else
73       self.current_user = session.delete(:new_user)
74
75       if check_signup_allowed(current_user.email)
76         current_user.data_public = true
77         current_user.description = "" if current_user.description.nil?
78         current_user.creation_ip = request.remote_ip
79         current_user.languages = http_accept_language.user_preferred_languages
80         current_user.terms_agreed = Time.now.getutc
81         current_user.tou_agreed = Time.now.getutc
82         current_user.terms_seen = true
83
84         if current_user.auth_uid.blank?
85           current_user.auth_provider = nil
86           current_user.auth_uid = nil
87         end
88
89         if current_user.save
90           flash[:piwik_goal] = PIWIK["goals"]["signup"] if defined?(PIWIK)
91
92           referer = welcome_path
93
94           begin
95             uri = URI(session[:referer])
96             %r{map=(.*)/(.*)/(.*)}.match(uri.fragment) do |m|
97               editor = Rack::Utils.parse_query(uri.query).slice("editor")
98               referer = welcome_path({ "zoom" => m[1],
99                                        "lat" => m[2],
100                                        "lon" => m[3] }.merge(editor))
101             end
102           rescue StandardError
103             # Use default
104           end
105
106           if current_user.status == "active"
107             session[:referer] = referer
108             successful_login(current_user)
109           else
110             session[:token] = current_user.tokens.create.token
111             UserMailer.signup_confirm(current_user, current_user.tokens.create(:referer => referer)).deliver_later
112             redirect_to :action => "confirm", :display_name => current_user.display_name
113           end
114         else
115           render :action => "new", :referer => params[:referer]
116         end
117       end
118     end
119   end
120
121   def account
122     @tokens = current_user.oauth_tokens.authorized
123
124     append_content_security_policy_directives(
125       :form_action => %w[accounts.google.com *.facebook.com login.live.com github.com meta.wikimedia.org]
126     )
127
128     if request.post?
129       if params[:user][:auth_provider].blank? ||
130          (params[:user][:auth_provider] == current_user.auth_provider &&
131           params[:user][:auth_uid] == current_user.auth_uid)
132         update_user(current_user, params)
133         redirect_to user_account_url(current_user) if current_user.errors.count.zero?
134       else
135         session[:new_user_settings] = params
136         redirect_to auth_url(params[:user][:auth_provider], params[:user][:auth_uid]), :status => :temporary_redirect
137       end
138     elsif errors = session.delete(:user_errors)
139       errors.each do |attribute, error|
140         current_user.errors.add(attribute, error)
141       end
142     end
143     @title = t "users.account.title"
144   end
145
146   def go_public
147     current_user.data_public = true
148     current_user.save
149     flash[:notice] = t "users.go_public.flash success"
150     redirect_to :action => "account", :display_name => current_user.display_name
151   end
152
153   def lost_password
154     @title = t "users.lost_password.title"
155
156     if request.post?
157       user = User.visible.find_by(:email => params[:email])
158
159       if user.nil?
160         users = User.visible.where("LOWER(email) = LOWER(?)", params[:email])
161
162         user = users.first if users.count == 1
163       end
164
165       if user
166         token = user.tokens.create
167         UserMailer.lost_password(user, token).deliver_later
168         flash[:notice] = t "users.lost_password.notice email on way"
169         redirect_to login_path
170       else
171         flash.now[:error] = t "users.lost_password.notice email cannot find"
172       end
173     end
174   end
175
176   def reset_password
177     @title = t "users.reset_password.title"
178
179     if params[:token]
180       token = UserToken.find_by(:token => params[:token])
181
182       if token
183         self.current_user = token.user
184
185         if params[:user]
186           current_user.pass_crypt = params[:user][:pass_crypt]
187           current_user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
188           current_user.status = "active" if current_user.status == "pending"
189           current_user.email_valid = true
190
191           if current_user.save
192             token.destroy
193             session[:fingerprint] = current_user.fingerprint
194             flash[:notice] = t "users.reset_password.flash changed"
195             successful_login(current_user)
196           end
197         end
198       else
199         flash[:error] = t "users.reset_password.flash token bad"
200         redirect_to :action => "lost_password"
201       end
202     else
203       head :bad_request
204     end
205   end
206
207   def new
208     @title = t "users.new.title"
209     @referer = if params[:referer]
210                  safe_referer(params[:referer])
211                else
212                  session[:referer]
213                end
214
215     append_content_security_policy_directives(
216       :form_action => %w[accounts.google.com *.facebook.com login.live.com github.com meta.wikimedia.org]
217     )
218
219     if current_user
220       # The user is logged in already, so don't show them the signup
221       # page, instead send them to the home page
222       if @referer
223         redirect_to @referer
224       else
225         redirect_to :controller => "site", :action => "index"
226       end
227     elsif params.key?(:auth_provider) && params.key?(:auth_uid)
228       self.current_user = User.new(:email => params[:email],
229                                    :email_confirmation => params[:email],
230                                    :display_name => params[:nickname],
231                                    :auth_provider => params[:auth_provider],
232                                    :auth_uid => params[:auth_uid])
233
234       flash.now[:notice] = render_to_string :partial => "auth_association"
235     else
236       check_signup_allowed
237
238       self.current_user = User.new
239     end
240   end
241
242   def create
243     self.current_user = User.new(user_params)
244
245     if check_signup_allowed(current_user.email)
246       session[:referer] = safe_referer(params[:referer]) if params[:referer]
247
248       Rails.logger.info "create: #{session[:referer]}"
249
250       current_user.status = "pending"
251
252       if current_user.auth_provider.present? && current_user.pass_crypt.empty?
253         # We are creating an account with external authentication and
254         # no password was specified so create a random one
255         current_user.pass_crypt = SecureRandom.base64(16)
256         current_user.pass_crypt_confirmation = current_user.pass_crypt
257       end
258
259       if current_user.invalid?
260         # Something is wrong with a new user, so rerender the form
261         render :action => "new"
262       elsif current_user.auth_provider.present?
263         # Verify external authenticator before moving on
264         session[:new_user] = current_user
265         redirect_to auth_url(current_user.auth_provider, current_user.auth_uid), :status => :temporary_redirect
266       else
267         # Save the user record
268         session[:new_user] = current_user
269         redirect_to :action => :terms
270       end
271     end
272   end
273
274   def confirm
275     if request.post?
276       token = UserToken.find_by(:token => params[:confirm_string])
277       if token&.user&.active?
278         flash[:error] = t("users.confirm.already active")
279         redirect_to login_path
280       elsif !token || token.expired?
281         flash[:error] = t("users.confirm.unknown token")
282         redirect_to :action => "confirm"
283       else
284         user = token.user
285         user.status = "active"
286         user.email_valid = true
287         flash[:notice] = gravatar_status_message(user) if gravatar_enable(user)
288         user.save!
289         referer = safe_referer(token.referer) if token.referer
290         token.destroy
291
292         if session[:token]
293           token = UserToken.find_by(:token => session[:token])
294           session.delete(:token)
295         else
296           token = nil
297         end
298
299         if token.nil? || token.user != user
300           flash[:notice] = t("users.confirm.success")
301           redirect_to login_path(:referer => referer)
302         else
303           token.destroy
304
305           session[:user] = user.id
306           session[:fingerprint] = user.fingerprint
307
308           redirect_to referer || welcome_path
309         end
310       end
311     else
312       user = User.find_by(:display_name => params[:display_name])
313
314       redirect_to root_path if user.nil? || user.active?
315     end
316   end
317
318   def confirm_resend
319     user = User.find_by(:display_name => params[:display_name])
320     token = UserToken.find_by(:token => session[:token])
321
322     if user.nil? || token.nil? || token.user != user
323       flash[:error] = t "users.confirm_resend.failure", :name => params[:display_name]
324     else
325       UserMailer.signup_confirm(user, user.tokens.create).deliver_later
326       flash[:notice] = t "users.confirm_resend.success_html", :email => user.email, :sender => Settings.support_email
327     end
328
329     redirect_to login_path
330   end
331
332   def confirm_email
333     if request.post?
334       token = UserToken.find_by(:token => params[:confirm_string])
335       if token&.user&.new_email?
336         self.current_user = token.user
337         current_user.email = current_user.new_email
338         current_user.new_email = nil
339         current_user.email_valid = true
340         gravatar_enabled = gravatar_enable(current_user)
341         if current_user.save
342           flash[:notice] = if gravatar_enabled
343                              "#{t('users.confirm_email.success')} #{gravatar_status_message(current_user)}"
344                            else
345                              t("users.confirm_email.success")
346                            end
347         else
348           flash[:errors] = current_user.errors
349         end
350         current_user.tokens.delete_all
351         session[:user] = current_user.id
352         session[:fingerprint] = current_user.fingerprint
353         redirect_to :action => "account", :display_name => current_user.display_name
354       elsif token
355         flash[:error] = t "users.confirm_email.failure"
356         redirect_to :action => "account", :display_name => token.user.display_name
357       else
358         flash[:error] = t "users.confirm_email.unknown_token"
359       end
360     end
361   end
362
363   def show
364     @user = User.find_by(:display_name => params[:display_name])
365
366     if @user &&
367        (@user.visible? || current_user&.administrator?)
368       @title = @user.display_name
369     else
370       render_unknown_user params[:display_name]
371     end
372   end
373
374   ##
375   # sets a user's status
376   def set_status
377     @user.status = params[:status]
378     @user.save
379     redirect_to user_path(:display_name => params[:display_name])
380   end
381
382   ##
383   # delete a user, marking them as deleted and removing personal data
384   def destroy
385     @user.delete
386     redirect_to user_path(:display_name => params[:display_name])
387   end
388
389   ##
390   # display a list of users matching specified criteria
391   def index
392     if request.post?
393       ids = params[:user].keys.collect(&:to_i)
394
395       User.where(:id => ids).update_all(:status => "confirmed") if params[:confirm]
396       User.where(:id => ids).update_all(:status => "deleted") if params[:hide]
397
398       redirect_to url_for(:status => params[:status], :ip => params[:ip], :page => params[:page])
399     else
400       @params = params.permit(:status, :ip)
401
402       conditions = {}
403       conditions[:status] = @params[:status] if @params[:status]
404       conditions[:creation_ip] = @params[:ip] if @params[:ip]
405
406       @user_pages, @users = paginate(:users,
407                                      :conditions => conditions,
408                                      :order => :id,
409                                      :per_page => 50)
410     end
411   end
412
413   ##
414   # omniauth success callback
415   def auth_success
416     auth_info = request.env["omniauth.auth"]
417
418     provider = auth_info[:provider]
419     uid = auth_info[:uid]
420     name = auth_info[:info][:name]
421     email = auth_info[:info][:email]
422
423     case provider
424     when "openid"
425       email_verified = uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
426                        uid.match(%r{https://me.yahoo.com/(.*)})
427     when "google", "facebook"
428       email_verified = true
429     else
430       email_verified = false
431     end
432
433     if settings = session.delete(:new_user_settings)
434       current_user.auth_provider = provider
435       current_user.auth_uid = uid
436
437       update_user(current_user, settings)
438
439       flash.discard
440
441       session[:user_errors] = current_user.errors.as_json
442
443       redirect_to :action => "account", :display_name => current_user.display_name
444     elsif session[:new_user]
445       session[:new_user].auth_provider = provider
446       session[:new_user].auth_uid = uid
447
448       session[:new_user].status = "active" if email_verified && email == session[:new_user].email
449
450       redirect_to :action => "terms"
451     else
452       user = User.find_by(:auth_provider => provider, :auth_uid => uid)
453
454       if user.nil? && provider == "google"
455         openid_url = auth_info[:extra][:id_info]["openid_id"]
456         user = User.find_by(:auth_provider => "openid", :auth_uid => openid_url) if openid_url
457         user&.update(:auth_provider => provider, :auth_uid => uid)
458       end
459
460       if user
461         case user.status
462         when "pending"
463           unconfirmed_login(user)
464         when "active", "confirmed"
465           successful_login(user, request.env["omniauth.params"]["referer"])
466         when "suspended"
467           failed_login t("users.login.account is suspended", :webmaster => "mailto:#{Settings.support_email}").html_safe
468         else
469           failed_login t("users.login.auth failure")
470         end
471       else
472         redirect_to :action => "new", :nickname => name, :email => email,
473                     :auth_provider => provider, :auth_uid => uid
474       end
475     end
476   end
477
478   ##
479   # omniauth failure callback
480   def auth_failure
481     flash[:error] = t("users.auth_failure.#{params[:message]}")
482     redirect_to params[:origin] || login_url
483   end
484
485   private
486
487   ##
488   #
489   def unconfirmed_login(user)
490     session[:token] = user.tokens.create.token
491
492     redirect_to :action => "confirm", :display_name => user.display_name
493
494     session.delete(:remember_me)
495     session.delete(:referer)
496   end
497
498   ##
499   # update a user's details
500   def update_user(user, params)
501     user.display_name = params[:user][:display_name]
502     user.new_email = params[:user][:new_email]
503
504     unless params[:user][:pass_crypt].empty? && params[:user][:pass_crypt_confirmation].empty?
505       user.pass_crypt = params[:user][:pass_crypt]
506       user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
507     end
508
509     if params[:user][:description] != user.description
510       user.description = params[:user][:description]
511       user.description_format = "markdown"
512     end
513
514     user.languages = params[:user][:languages].split(",")
515
516     case params[:avatar_action]
517     when "new"
518       user.avatar.attach(params[:user][:avatar])
519       user.image_use_gravatar = false
520     when "delete"
521       user.avatar.purge_later
522       user.image_use_gravatar = false
523     when "gravatar"
524       user.avatar.purge_later
525       user.image_use_gravatar = true
526     end
527
528     user.home_lat = params[:user][:home_lat]
529     user.home_lon = params[:user][:home_lon]
530
531     user.preferred_editor = if params[:user][:preferred_editor] == "default"
532                               nil
533                             else
534                               params[:user][:preferred_editor]
535                             end
536
537     if params[:user][:auth_provider].nil? || params[:user][:auth_provider].blank?
538       user.auth_provider = nil
539       user.auth_uid = nil
540     end
541
542     if user.save
543       session[:fingerprint] = user.fingerprint
544
545       set_locale(:reset => true)
546
547       if user.new_email.blank? || user.new_email == user.email
548         flash[:notice] = t "users.account.flash update success"
549       else
550         user.email = user.new_email
551
552         if user.valid?
553           flash[:notice] = t "users.account.flash update success confirm needed"
554
555           begin
556             UserMailer.email_confirm(user, user.tokens.create).deliver_later
557           rescue StandardError
558             # Ignore errors sending email
559           end
560         else
561           current_user.errors.add(:new_email, current_user.errors[:email])
562           current_user.errors.add(:email, [])
563         end
564
565         user.restore_email!
566       end
567     end
568   end
569
570   ##
571   # require that the user in the URL is the logged in user
572   def require_self
573     head :forbidden if params[:display_name] != current_user.display_name
574   end
575
576   ##
577   # ensure that there is a "user" instance variable
578   def lookup_user_by_name
579     @user = User.find_by(:display_name => params[:display_name])
580   rescue ActiveRecord::RecordNotFound
581     redirect_to :action => "view", :display_name => params[:display_name] unless @user
582   end
583
584   ##
585   # return permitted user parameters
586   def user_params
587     params.require(:user).permit(:email, :email_confirmation, :display_name,
588                                  :auth_provider, :auth_uid,
589                                  :pass_crypt, :pass_crypt_confirmation)
590   end
591
592   ##
593   # check signup acls
594   def check_signup_allowed(email = nil)
595     domain = if email.nil?
596                nil
597              else
598                email.split("@").last
599              end
600
601     mx_servers = if domain.nil?
602                    nil
603                  else
604                    domain_mx_servers(domain)
605                  end
606
607     if blocked = Acl.no_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
608       logger.info "Blocked signup from #{request.remote_ip} for #{email}"
609
610       render :action => "blocked"
611     end
612
613     !blocked
614   end
615
616   ##
617   # get list of MX servers for a domains
618   def domain_mx_servers(domain)
619     Resolv::DNS.open do |dns|
620       dns.getresources(domain, Resolv::DNS::Resource::IN::MX).collect(&:exchange).collect(&:to_s)
621     end
622   end
623
624   ##
625   # check if this user has a gravatar and set the user pref is true
626   def gravatar_enable(user)
627     # code from example https://en.gravatar.com/site/implement/images/ruby/
628     return false if user.avatar.attached?
629
630     begin
631       hash = Digest::MD5.hexdigest(user.email.downcase)
632       url = "https://www.gravatar.com/avatar/#{hash}?d=404" # without d=404 we will always get an image back
633       response = OSM.http_client.get(URI.parse(url))
634       available = response.success?
635     rescue StandardError
636       available = false
637     end
638
639     oldsetting = user.image_use_gravatar
640     user.image_use_gravatar = available
641     oldsetting != user.image_use_gravatar
642   end
643
644   ##
645   # display a message about th current status of the gravatar setting
646   def gravatar_status_message(user)
647     if user.image_use_gravatar
648       t "users.account.gravatar.enabled"
649     else
650       t "users.account.gravatar.disabled"
651     end
652   end
653 end