Move the user api methods into a separate controller in the api namespace
[rails.git] / app / controllers / users_controller.rb
1 class UsersController < ApplicationController
2   layout "site"
3
4   skip_before_action :verify_authenticity_token, :only => [:auth_success]
5   before_action :disable_terms_redirect, :only => [:terms, :save, :logout]
6   before_action :authorize_web
7   before_action :set_locale
8
9   authorize_resource
10
11   before_action :require_self, :only => [:account]
12   before_action :check_database_readable, :except => [:login]
13   before_action :check_database_writable, :only => [:new, :account, :confirm, :confirm_email, :lost_password, :reset_password, :go_public, :make_friend, :remove_friend]
14   before_action :require_cookies, :only => [:new, :login, :confirm]
15   before_action :lookup_user_by_name, :only => [:set_status, :delete]
16   before_action :allow_thirdparty_images, :only => [:show, :account]
17
18   def terms
19     @legale = params[:legale] || OSM.ip_to_country(request.remote_ip) || DEFAULT_LEGALE
20     @text = OSM.legal_text_for_country(@legale)
21
22     if request.xhr?
23       render :partial => "terms"
24     else
25       @title = t "users.terms.title"
26
27       if current_user&.terms_agreed?
28         # Already agreed to terms, so just show settings
29         redirect_to :action => :account, :display_name => current_user.display_name
30       elsif current_user.nil? && session[:new_user].nil?
31         redirect_to :action => :login, :referer => request.fullpath
32       end
33     end
34   end
35
36   def save
37     @title = t "users.new.title"
38
39     if params[:decline]
40       if current_user
41         current_user.terms_seen = true
42
43         flash[:notice] = t("users.new.terms declined", :url => t("users.new.terms declined url")).html_safe if current_user.save
44
45         if params[:referer]
46           redirect_to params[:referer]
47         else
48           redirect_to :action => :account, :display_name => current_user.display_name
49         end
50       else
51         redirect_to t("users.terms.declined")
52       end
53     elsif current_user
54       unless current_user.terms_agreed?
55         current_user.consider_pd = params[:user][:consider_pd]
56         current_user.terms_agreed = Time.now.getutc
57         current_user.terms_seen = true
58
59         flash[:notice] = t "users.new.terms accepted" if current_user.save
60       end
61
62       if params[:referer]
63         redirect_to params[:referer]
64       else
65         redirect_to :action => :account, :display_name => current_user.display_name
66       end
67     else
68       self.current_user = session.delete(:new_user)
69
70       if check_signup_allowed(current_user.email)
71         current_user.data_public = true
72         current_user.description = "" if current_user.description.nil?
73         current_user.creation_ip = request.remote_ip
74         current_user.languages = http_accept_language.user_preferred_languages
75         current_user.terms_agreed = Time.now.getutc
76         current_user.terms_seen = true
77
78         if current_user.auth_uid.blank?
79           current_user.auth_provider = nil
80           current_user.auth_uid = nil
81         end
82
83         if current_user.save
84           flash[:piwik_goal] = PIWIK["goals"]["signup"] if defined?(PIWIK)
85
86           referer = welcome_path
87
88           begin
89             uri = URI(session[:referer])
90             %r{map=(.*)/(.*)/(.*)}.match(uri.fragment) do |m|
91               editor = Rack::Utils.parse_query(uri.query).slice("editor")
92               referer = welcome_path({ "zoom" => m[1],
93                                        "lat" => m[2],
94                                        "lon" => m[3] }.merge(editor))
95             end
96           rescue StandardError
97             # Use default
98           end
99
100           if current_user.status == "active"
101             session[:referer] = referer
102             successful_login(current_user)
103           else
104             session[:token] = current_user.tokens.create.token
105             Notifier.signup_confirm(current_user, current_user.tokens.create(:referer => referer)).deliver_later
106             redirect_to :action => "confirm", :display_name => current_user.display_name
107           end
108         else
109           render :action => "new", :referer => params[:referer]
110         end
111       end
112     end
113   end
114
115   def account
116     @tokens = current_user.oauth_tokens.authorized
117
118     if params[:user] && params[:user][:display_name] && params[:user][:description]
119       if params[:user][:auth_provider].blank? ||
120          (params[:user][:auth_provider] == current_user.auth_provider &&
121           params[:user][:auth_uid] == current_user.auth_uid)
122         update_user(current_user, params)
123       else
124         session[:new_user_settings] = params
125         redirect_to auth_url(params[:user][:auth_provider], params[:user][:auth_uid])
126       end
127     elsif errors = session.delete(:user_errors)
128       errors.each do |attribute, error|
129         current_user.errors.add(attribute, error)
130       end
131     end
132     @title = t "users.account.title"
133   end
134
135   def go_public
136     current_user.data_public = true
137     current_user.save
138     flash[:notice] = t "users.go_public.flash success"
139     redirect_to :action => "account", :display_name => current_user.display_name
140   end
141
142   def lost_password
143     @title = t "users.lost_password.title"
144
145     if params[:user] && params[:user][:email]
146       user = User.visible.find_by(:email => params[:user][:email])
147
148       if user.nil?
149         users = User.visible.where("LOWER(email) = LOWER(?)", params[:user][:email])
150
151         user = users.first if users.count == 1
152       end
153
154       if user
155         token = user.tokens.create
156         Notifier.lost_password(user, token).deliver_later
157         flash[:notice] = t "users.lost_password.notice email on way"
158         redirect_to :action => "login"
159       else
160         flash.now[:error] = t "users.lost_password.notice email cannot find"
161       end
162     end
163   end
164
165   def reset_password
166     @title = t "users.reset_password.title"
167
168     if params[:token]
169       token = UserToken.find_by(:token => params[:token])
170
171       if token
172         self.current_user = token.user
173
174         if params[:user]
175           current_user.pass_crypt = params[:user][:pass_crypt]
176           current_user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
177           current_user.status = "active" if current_user.status == "pending"
178           current_user.email_valid = true
179
180           if current_user.save
181             token.destroy
182             flash[:notice] = t "users.reset_password.flash changed"
183             successful_login(current_user)
184           end
185         end
186       else
187         flash[:error] = t "users.reset_password.flash token bad"
188         redirect_to :action => "lost_password"
189       end
190     else
191       head :bad_request
192     end
193   end
194
195   def new
196     @title = t "users.new.title"
197     @referer = params[:referer] || session[:referer]
198
199     append_content_security_policy_directives(
200       :form_action => %w[accounts.google.com *.facebook.com login.live.com github.com meta.wikimedia.org]
201     )
202
203     if current_user
204       # The user is logged in already, so don't show them the signup
205       # page, instead send them to the home page
206       if @referer
207         redirect_to @referer
208       else
209         redirect_to :controller => "site", :action => "index"
210       end
211     elsif params.key?(:auth_provider) && params.key?(:auth_uid)
212       self.current_user = User.new(:email => params[:email],
213                                    :email_confirmation => params[:email],
214                                    :display_name => params[:nickname],
215                                    :auth_provider => params[:auth_provider],
216                                    :auth_uid => params[:auth_uid])
217
218       flash.now[:notice] = render_to_string :partial => "auth_association"
219     else
220       check_signup_allowed
221
222       self.current_user = User.new
223     end
224   end
225
226   def create
227     self.current_user = User.new(user_params)
228
229     if check_signup_allowed(current_user.email)
230       session[:referer] = params[:referer]
231
232       current_user.status = "pending"
233
234       if current_user.auth_provider.present? && current_user.pass_crypt.empty?
235         # We are creating an account with external authentication and
236         # no password was specified so create a random one
237         current_user.pass_crypt = SecureRandom.base64(16)
238         current_user.pass_crypt_confirmation = current_user.pass_crypt
239       end
240
241       if current_user.invalid?
242         # Something is wrong with a new user, so rerender the form
243         render :action => "new"
244       elsif current_user.auth_provider.present?
245         # Verify external authenticator before moving on
246         session[:new_user] = current_user
247         redirect_to auth_url(current_user.auth_provider, current_user.auth_uid)
248       else
249         # Save the user record
250         session[:new_user] = current_user
251         redirect_to :action => :terms
252       end
253     end
254   end
255
256   def login
257     session[:referer] = params[:referer] if params[:referer]
258
259     if params[:username].present? && params[:password].present?
260       session[:remember_me] ||= params[:remember_me]
261       password_authentication(params[:username], params[:password])
262     elsif params[:openid_url].present?
263       session[:remember_me] ||= params[:remember_me_openid]
264       redirect_to auth_url("openid", params[:openid_url], params[:referer])
265     end
266   end
267
268   def logout
269     @title = t "users.logout.title"
270
271     if params[:session] == session.id
272       if session[:token]
273         token = UserToken.find_by(:token => session[:token])
274         token&.destroy
275         session.delete(:token)
276       end
277       session.delete(:user)
278       session_expires_automatically
279       if params[:referer]
280         redirect_to params[:referer]
281       else
282         redirect_to :controller => "site", :action => "index"
283       end
284     end
285   end
286
287   def confirm
288     if request.post?
289       token = UserToken.find_by(:token => params[:confirm_string])
290       if token&.user&.active?
291         flash[:error] = t("users.confirm.already active")
292         redirect_to :action => "login"
293       elsif !token || token.expired?
294         flash[:error] = t("users.confirm.unknown token")
295         redirect_to :action => "confirm"
296       else
297         user = token.user
298         user.status = "active"
299         user.email_valid = true
300         flash[:notice] = gravatar_status_message(user) if gravatar_enable(user)
301         user.save!
302         referer = token.referer
303         token.destroy
304
305         if session[:token]
306           token = UserToken.find_by(:token => session[:token])
307           session.delete(:token)
308         else
309           token = nil
310         end
311
312         if token.nil? || token.user != user
313           flash[:notice] = t("users.confirm.success")
314           redirect_to :action => :login, :referer => referer
315         else
316           token.destroy
317
318           session[:user] = user.id
319
320           redirect_to referer || welcome_path
321         end
322       end
323     else
324       user = User.find_by(:display_name => params[:display_name])
325
326       redirect_to root_path if user.nil? || user.active?
327     end
328   end
329
330   def confirm_resend
331     user = User.find_by(:display_name => params[:display_name])
332     token = UserToken.find_by(:token => session[:token])
333
334     if user.nil? || token.nil? || token.user != user
335       flash[:error] = t "users.confirm_resend.failure", :name => params[:display_name]
336     else
337       Notifier.signup_confirm(user, user.tokens.create).deliver_later
338       flash[:notice] = t("users.confirm_resend.success", :email => user.email, :sender => SUPPORT_EMAIL).html_safe
339     end
340
341     redirect_to :action => "login"
342   end
343
344   def confirm_email
345     if request.post?
346       token = UserToken.find_by(:token => params[:confirm_string])
347       if token&.user&.new_email?
348         self.current_user = token.user
349         current_user.email = current_user.new_email
350         current_user.new_email = nil
351         current_user.email_valid = true
352         gravatar_enabled = gravatar_enable(current_user)
353         if current_user.save
354           flash[:notice] = if gravatar_enabled
355                              t("users.confirm_email.success") + " " + gravatar_status_message(current_user)
356                            else
357                              t("users.confirm_email.success")
358                            end
359         else
360           flash[:errors] = current_user.errors
361         end
362         token.destroy
363         session[:user] = current_user.id
364         redirect_to :action => "account", :display_name => current_user.display_name
365       elsif token
366         flash[:error] = t "users.confirm_email.failure"
367         redirect_to :action => "account", :display_name => token.user.display_name
368       else
369         flash[:error] = t "users.confirm_email.unknown_token"
370       end
371     end
372   end
373
374   def show
375     @user = User.find_by(:display_name => params[:display_name])
376
377     if @user &&
378        (@user.visible? || (current_user&.administrator?))
379       @title = @user.display_name
380     else
381       render_unknown_user params[:display_name]
382     end
383   end
384
385   def make_friend
386     @new_friend = User.find_by(:display_name => params[:display_name])
387
388     if @new_friend
389       if request.post?
390         friend = Friend.new
391         friend.befriender = current_user
392         friend.befriendee = @new_friend
393         if current_user.is_friends_with?(@new_friend)
394           flash[:warning] = t "users.make_friend.already_a_friend", :name => @new_friend.display_name
395         elsif friend.save
396           flash[:notice] = t "users.make_friend.success", :name => @new_friend.display_name
397           Notifier.friend_notification(friend).deliver_later
398         else
399           friend.add_error(t("users.make_friend.failed", :name => @new_friend.display_name))
400         end
401
402         if params[:referer]
403           redirect_to params[:referer]
404         else
405           redirect_to :action => "show"
406         end
407       end
408     else
409       render_unknown_user params[:display_name]
410     end
411   end
412
413   def remove_friend
414     @friend = User.find_by(:display_name => params[:display_name])
415
416     if @friend
417       if request.post?
418         if current_user.is_friends_with?(@friend)
419           Friend.where(:user_id => current_user.id, :friend_user_id => @friend.id).delete_all
420           flash[:notice] = t "users.remove_friend.success", :name => @friend.display_name
421         else
422           flash[:error] = t "users.remove_friend.not_a_friend", :name => @friend.display_name
423         end
424
425         if params[:referer]
426           redirect_to params[:referer]
427         else
428           redirect_to :action => "show"
429         end
430       end
431     else
432       render_unknown_user params[:display_name]
433     end
434   end
435
436   ##
437   # sets a user's status
438   def set_status
439     @user.status = params[:status]
440     @user.save
441     redirect_to user_path(:display_name => params[:display_name])
442   end
443
444   ##
445   # delete a user, marking them as deleted and removing personal data
446   def delete
447     @user.delete
448     redirect_to user_path(:display_name => params[:display_name])
449   end
450
451   ##
452   # display a list of users matching specified criteria
453   def index
454     if request.post?
455       ids = params[:user].keys.collect(&:to_i)
456
457       User.where(:id => ids).update_all(:status => "confirmed") if params[:confirm]
458       User.where(:id => ids).update_all(:status => "deleted") if params[:hide]
459
460       redirect_to url_for(:status => params[:status], :ip => params[:ip], :page => params[:page])
461     else
462       @params = params.permit(:status, :ip)
463
464       conditions = {}
465       conditions[:status] = @params[:status] if @params[:status]
466       conditions[:creation_ip] = @params[:ip] if @params[:ip]
467
468       @user_pages, @users = paginate(:users,
469                                      :conditions => conditions,
470                                      :order => :id,
471                                      :per_page => 50)
472     end
473   end
474
475   ##
476   # omniauth success callback
477   def auth_success
478     auth_info = request.env["omniauth.auth"]
479
480     provider = auth_info[:provider]
481     uid = auth_info[:uid]
482     name = auth_info[:info][:name]
483     email = auth_info[:info][:email]
484
485     case provider
486     when "openid"
487       email_verified = uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
488                        uid.match(%r{https://me.yahoo.com/(.*)})
489     when "google", "facebook"
490       email_verified = true
491     else
492       email_verified = false
493     end
494
495     if settings = session.delete(:new_user_settings)
496       current_user.auth_provider = provider
497       current_user.auth_uid = uid
498
499       update_user(current_user, settings)
500
501       session[:user_errors] = current_user.errors.as_json
502
503       redirect_to :action => "account", :display_name => current_user.display_name
504     elsif session[:new_user]
505       session[:new_user].auth_provider = provider
506       session[:new_user].auth_uid = uid
507
508       session[:new_user].status = "active" if email_verified && email == session[:new_user].email
509
510       redirect_to :action => "terms"
511     else
512       user = User.find_by(:auth_provider => provider, :auth_uid => uid)
513
514       if user.nil? && provider == "google"
515         openid_url = auth_info[:extra][:id_info]["openid_id"]
516         user = User.find_by(:auth_provider => "openid", :auth_uid => openid_url) if openid_url
517         user&.update(:auth_provider => provider, :auth_uid => uid)
518       end
519
520       if user
521         case user.status
522         when "pending" then
523           unconfirmed_login(user)
524         when "active", "confirmed" then
525           successful_login(user, request.env["omniauth.params"]["referer"])
526         when "suspended" then
527           failed_login t("users.login.account is suspended", :webmaster => "mailto:#{SUPPORT_EMAIL}").html_safe
528         else
529           failed_login t("users.login.auth failure")
530         end
531       else
532         redirect_to :action => "new", :nickname => name, :email => email,
533                     :auth_provider => provider, :auth_uid => uid
534       end
535     end
536   end
537
538   ##
539   # omniauth failure callback
540   def auth_failure
541     flash[:error] = t("users.auth_failure." + params[:message])
542     redirect_to params[:origin] || login_url
543   end
544
545   private
546
547   ##
548   # handle password authentication
549   def password_authentication(username, password)
550     if user = User.authenticate(:username => username, :password => password)
551       successful_login(user)
552     elsif user = User.authenticate(:username => username, :password => password, :pending => true)
553       unconfirmed_login(user)
554     elsif User.authenticate(:username => username, :password => password, :suspended => true)
555       failed_login t("users.login.account is suspended", :webmaster => "mailto:#{SUPPORT_EMAIL}").html_safe, username
556     else
557       failed_login t("users.login.auth failure"), username
558     end
559   end
560
561   ##
562   # return the URL to use for authentication
563   def auth_url(provider, uid, referer = nil)
564     params = { :provider => provider }
565
566     params[:openid_url] = openid_expand_url(uid) if provider == "openid"
567
568     if referer.nil?
569       params[:origin] = request.path
570     else
571       params[:origin] = request.path + "?referer=" + CGI.escape(referer)
572       params[:referer] = referer
573     end
574
575     auth_path(params)
576   end
577
578   ##
579   # special case some common OpenID providers by applying heuristics to
580   # try and come up with the correct URL based on what the user entered
581   def openid_expand_url(openid_url)
582     if openid_url.nil?
583       nil
584     elsif openid_url.match(%r{(.*)gmail.com(/?)$}) || openid_url.match(%r{(.*)googlemail.com(/?)$})
585       # Special case gmail.com as it is potentially a popular OpenID
586       # provider and, unlike yahoo.com, where it works automatically, Google
587       # have hidden their OpenID endpoint somewhere obscure this making it
588       # somewhat less user friendly.
589       "https://www.google.com/accounts/o8/id"
590     else
591       openid_url
592     end
593   end
594
595   ##
596   # process a successful login
597   def successful_login(user, referer = nil)
598     session[:user] = user.id
599     session_expires_after 28.days if session[:remember_me]
600
601     target = referer || session[:referer] || url_for(:controller => :site, :action => :index)
602
603     # The user is logged in, so decide where to send them:
604     #
605     # - If they haven't seen the contributor terms, send them there.
606     # - If they have a block on them, show them that.
607     # - If they were referred to the login, send them back there.
608     # - Otherwise, send them to the home page.
609     if !user.terms_seen
610       redirect_to :action => :terms, :referer => target
611     elsif user.blocked_on_view
612       redirect_to user.blocked_on_view, :referer => target
613     else
614       redirect_to target
615     end
616
617     session.delete(:remember_me)
618     session.delete(:referer)
619   end
620
621   ##
622   # process a failed login
623   def failed_login(message, username = nil)
624     flash[:error] = message
625
626     redirect_to :action => "login", :referer => session[:referer],
627                 :username => username, :remember_me => session[:remember_me]
628
629     session.delete(:remember_me)
630     session.delete(:referer)
631   end
632
633   ##
634   #
635   def unconfirmed_login(user)
636     session[:token] = user.tokens.create.token
637
638     redirect_to :action => "confirm", :display_name => user.display_name
639
640     session.delete(:remember_me)
641     session.delete(:referer)
642   end
643
644   ##
645   # update a user's details
646   def update_user(user, params)
647     user.display_name = params[:user][:display_name]
648     user.new_email = params[:user][:new_email]
649
650     unless params[:user][:pass_crypt].empty? && params[:user][:pass_crypt_confirmation].empty?
651       user.pass_crypt = params[:user][:pass_crypt]
652       user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
653     end
654
655     if params[:user][:description] != user.description
656       user.description = params[:user][:description]
657       user.description_format = "markdown"
658     end
659
660     user.languages = params[:user][:languages].split(",")
661
662     case params[:image_action]
663     when "new" then
664       user.image = params[:user][:image]
665       user.image_use_gravatar = false
666     when "delete" then
667       user.image = nil
668       user.image_use_gravatar = false
669     when "gravatar" then
670       user.image = nil
671       user.image_use_gravatar = true
672     end
673
674     user.home_lat = params[:user][:home_lat]
675     user.home_lon = params[:user][:home_lon]
676
677     user.preferred_editor = if params[:user][:preferred_editor] == "default"
678                               nil
679                             else
680                               params[:user][:preferred_editor]
681                             end
682
683     if params[:user][:auth_provider].nil? || params[:user][:auth_provider].blank?
684       user.auth_provider = nil
685       user.auth_uid = nil
686     end
687
688     if user.save
689       set_locale(true)
690
691       if user.new_email.blank? || user.new_email == user.email
692         flash.now[:notice] = t "users.account.flash update success"
693       else
694         user.email = user.new_email
695
696         if user.valid?
697           flash.now[:notice] = t "users.account.flash update success confirm needed"
698
699           begin
700             Notifier.email_confirm(user, user.tokens.create).deliver_later
701           rescue StandardError
702             # Ignore errors sending email
703           end
704         else
705           current_user.errors.add(:new_email, current_user.errors[:email])
706           current_user.errors.add(:email, [])
707         end
708
709         user.restore_email!
710       end
711     end
712   end
713
714   ##
715   # require that the user in the URL is the logged in user
716   def require_self
717     head :forbidden if params[:display_name] != current_user.display_name
718   end
719
720   ##
721   # ensure that there is a "user" instance variable
722   def lookup_user_by_name
723     @user = User.find_by(:display_name => params[:display_name])
724   rescue ActiveRecord::RecordNotFound
725     redirect_to :action => "view", :display_name => params[:display_name] unless @user
726   end
727
728   ##
729   #
730   def disable_terms_redirect
731     # this is necessary otherwise going to the user terms page, when
732     # having not agreed already would cause an infinite redirect loop.
733     # it's .now so that this doesn't propagate to other pages.
734     flash.now[:skip_terms] = true
735   end
736
737   ##
738   # return permitted user parameters
739   def user_params
740     params.require(:user).permit(:email, :email_confirmation, :display_name,
741                                  :auth_provider, :auth_uid,
742                                  :pass_crypt, :pass_crypt_confirmation)
743   end
744
745   ##
746   # check signup acls
747   def check_signup_allowed(email = nil)
748     domain = if email.nil?
749                nil
750              else
751                email.split("@").last
752              end
753
754     if blocked = Acl.no_account_creation(request.remote_ip, domain)
755       logger.info "Blocked signup from #{request.remote_ip} for #{email}"
756
757       render :action => "blocked"
758     end
759
760     !blocked
761   end
762
763   ##
764   # check if this user has a gravatar and set the user pref is true
765   def gravatar_enable(user)
766     # code from example https://en.gravatar.com/site/implement/images/ruby/
767     return false if user.image.present?
768
769     hash = Digest::MD5.hexdigest(user.email.downcase)
770     url = "https://www.gravatar.com/avatar/#{hash}?d=404" # without d=404 we will always get an image back
771     response = OSM.http_client.get(URI.parse(url))
772     oldsetting = user.image_use_gravatar
773     user.image_use_gravatar = response.success?
774     oldsetting != user.image_use_gravatar
775   end
776
777   ##
778   # display a message about th current status of the gravatar setting
779   def gravatar_status_message(user)
780     if user.image_use_gravatar
781       t "users.account.gravatar.enabled"
782     else
783       t "users.account.gravatar.disabled"
784     end
785   end
786 end