]> git.openstreetmap.org Git - rails.git/blob - app/controllers/users_controller.rb
Use resourceful route for user status
[rails.git] / app / controllers / users_controller.rb
1 class UsersController < ApplicationController
2   include EmailMethods
3   include SessionMethods
4   include UserMethods
5
6   layout "site"
7
8   skip_before_action :verify_authenticity_token, :only => [:auth_success]
9   before_action :authorize_web
10   before_action :set_locale
11   before_action :check_database_readable
12
13   authorize_resource
14
15   before_action :check_database_writable, :only => [:new, :go_public]
16   before_action :require_cookies, :only => [:new]
17
18   allow_thirdparty_images :only => :show
19   allow_social_login :only => :new
20
21   def show
22     @user = User.find_by(:display_name => params[:display_name])
23
24     if @user &&
25        (@user.visible? || current_user&.administrator?)
26       @title = @user.display_name
27     else
28       render_unknown_user params[:display_name]
29     end
30   end
31
32   def new
33     @title = t ".title"
34     @referer = safe_referer(params[:referer])
35
36     parse_oauth_referer @referer
37
38     if current_user
39       # The user is logged in already, so don't show them the signup
40       # page, instead send them to the home page
41       redirect_to @referer || { :controller => "site", :action => "index" }
42     elsif params.key?(:auth_provider) && params.key?(:auth_uid)
43       @email_hmac = params[:email_hmac]
44
45       self.current_user = User.new(:email => params[:email],
46                                    :display_name => params[:nickname],
47                                    :auth_provider => params[:auth_provider],
48                                    :auth_uid => params[:auth_uid])
49
50       if current_user.valid? || current_user.errors[:email].empty?
51         flash.now[:notice] = render_to_string :partial => "auth_association"
52       else
53         flash.now[:warning] = t ".duplicate_social_email"
54       end
55     else
56       check_signup_allowed
57
58       self.current_user = User.new
59     end
60   end
61
62   def create
63     self.current_user = User.new(user_params)
64
65     if check_signup_allowed(current_user.email)
66       if current_user.auth_uid.present?
67         # We are creating an account with external authentication and
68         # no password was specified so create a random one
69         current_user.pass_crypt = SecureRandom.base64(16)
70         current_user.pass_crypt_confirmation = current_user.pass_crypt
71       end
72
73       if current_user.invalid?
74         # Something is wrong with a new user, so rerender the form
75         render :action => "new"
76       else
77         # Save the user record
78         if save_new_user params[:email_hmac]
79           SIGNUP_IP_LIMITER&.update(request.remote_ip)
80           SIGNUP_EMAIL_LIMITER&.update(canonical_email(current_user.email))
81
82           flash[:matomo_goal] = Settings.matomo["goals"]["signup"] if defined?(Settings.matomo)
83
84           referer = welcome_path(welcome_options(params[:referer]))
85
86           if current_user.status == "active"
87             successful_login(current_user, referer)
88           else
89             session[:pending_user] = current_user.id
90             UserMailer.signup_confirm(current_user, current_user.generate_token_for(:new_user), referer).deliver_later
91             redirect_to :controller => :confirmations, :action => :confirm, :display_name => current_user.display_name
92           end
93         else
94           render :action => "new", :referer => params[:referer]
95         end
96       end
97     end
98   end
99
100   def go_public
101     current_user.data_public = true
102     current_user.save
103     flash[:notice] = t ".flash success"
104     redirect_to edit_account_path
105   end
106
107   ##
108   # omniauth success callback
109   def auth_success
110     referer = request.env["omniauth.params"]["referer"]
111     auth_info = request.env["omniauth.auth"]
112
113     provider = auth_info[:provider]
114     uid = auth_info[:uid]
115     name = auth_info[:info][:name]
116     email = auth_info[:info][:email]
117
118     email_verified = case provider
119                      when "openid"
120                        uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
121                        uid.match(%r{https://me.yahoo.com/(.*)})
122                      when "google", "facebook", "microsoft", "github", "wikipedia"
123                        true
124                      else
125                        false
126                      end
127
128     if settings = session.delete(:new_user_settings)
129       current_user.auth_provider = provider
130       current_user.auth_uid = uid
131
132       update_user(current_user, settings)
133
134       flash.discard
135
136       session[:user_errors] = current_user.errors.as_json
137
138       redirect_to edit_account_path
139     else
140       user = User.find_by(:auth_provider => provider, :auth_uid => uid)
141
142       if user.nil? && provider == "google"
143         openid_url = auth_info[:extra][:id_info]["openid_id"]
144         user = User.find_by(:auth_provider => "openid", :auth_uid => openid_url) if openid_url
145         user&.update(:auth_provider => provider, :auth_uid => uid)
146       end
147
148       if user
149         case user.status
150         when "pending"
151           unconfirmed_login(user, referer)
152         when "active", "confirmed"
153           successful_login(user, referer)
154         when "suspended"
155           failed_login({ :partial => "sessions/suspended_flash" }, user.display_name, referer)
156         else
157           failed_login(t("sessions.new.auth failure"), user.display_name, referer)
158         end
159       else
160         email_hmac = UsersController.message_hmac(email) if email_verified && email
161         redirect_to :action => "new", :nickname => name, :email => email, :email_hmac => email_hmac,
162                     :auth_provider => provider, :auth_uid => uid, :referer => referer
163       end
164     end
165   end
166
167   ##
168   # omniauth failure callback
169   def auth_failure
170     flash[:error] = t(params[:message], :scope => "users.auth_failure", :default => t(".unknown_error"))
171
172     origin = safe_referer(params[:origin]) if params[:origin]
173
174     redirect_to origin || login_url
175   end
176
177   def self.message_hmac(text)
178     sha256 = Digest::SHA256.new
179     sha256 << Rails.application.key_generator.generate_key("openstreetmap/email_address")
180     sha256 << text
181     Base64.urlsafe_encode64(sha256.digest)
182   end
183
184   private
185
186   def save_new_user(email_hmac)
187     current_user.data_public = true
188     current_user.description = "" if current_user.description.nil?
189     current_user.creation_address = request.remote_ip
190     current_user.languages = http_accept_language.user_preferred_languages
191     current_user.terms_agreed = Time.now.utc
192     current_user.tou_agreed = Time.now.utc
193     current_user.terms_seen = true
194
195     if current_user.auth_uid.blank?
196       current_user.auth_provider = nil
197       current_user.auth_uid = nil
198     elsif email_hmac && ActiveSupport::SecurityUtils.secure_compare(email_hmac, UsersController.message_hmac(current_user.email))
199       current_user.activate
200     end
201
202     current_user.save
203   end
204
205   def welcome_options(referer = nil)
206     uri = URI(referer) if referer.present?
207
208     return { "oauth_return_url" => uri&.to_s } if uri&.path == oauth_authorization_path
209
210     begin
211       %r{map=(.*)/(.*)/(.*)}.match(uri.fragment) do |m|
212         editor = Rack::Utils.parse_query(uri.query).slice("editor")
213         return { "zoom" => m[1], "lat" => m[2], "lon" => m[3] }.merge(editor)
214       end
215     rescue StandardError
216       # Use default
217     end
218   end
219
220   ##
221   # return permitted user parameters
222   def user_params
223     params.require(:user).permit(:email, :display_name,
224                                  :auth_provider, :auth_uid,
225                                  :pass_crypt, :pass_crypt_confirmation,
226                                  :consider_pd)
227   end
228
229   ##
230   # check signup acls
231   def check_signup_allowed(email = nil)
232     domain = if email.nil?
233                nil
234              else
235                email.split("@").last
236              end
237
238     mx_servers = if domain.nil?
239                    nil
240                  else
241                    domain_mx_servers(domain)
242                  end
243
244     return true if Acl.allow_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
245
246     blocked = Acl.no_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
247
248     blocked ||= SIGNUP_IP_LIMITER && !SIGNUP_IP_LIMITER.allow?(request.remote_ip)
249
250     blocked ||= email && SIGNUP_EMAIL_LIMITER && !SIGNUP_EMAIL_LIMITER.allow?(canonical_email(email))
251
252     if blocked
253       logger.info "Blocked signup from #{request.remote_ip} for #{email}"
254
255       render :action => "blocked"
256     end
257
258     !blocked
259   end
260 end