]> git.openstreetmap.org Git - rails.git/blob - app/controllers/users_controller.rb
Improve heatmap data caching
[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 && (@user.visible? || current_user&.administrator?)
25       @title = @user.display_name
26
27       @heatmap_data = Rails.cache.fetch("heatmap_data_of_user_#{@user.id}", :expires_at => Time.zone.now.end_of_day) do
28         one_year_ago = 1.year.ago.beginning_of_day
29         today = Time.zone.now.end_of_day
30
31         mapped = Changeset
32                  .where(:user_id => @user.id)
33                  .where(:created_at => one_year_ago..today)
34                  .where(:num_changes => 1..)
35                  .group("date_trunc('day', created_at)")
36                  .select("date_trunc('day', created_at) AS date, SUM(num_changes) AS total_changes, MAX(id) AS max_id")
37                  .order("date")
38                  .map do |changeset|
39                    {
40                      :date => changeset.date.to_date,
41                      :total_changes => changeset.total_changes.to_i,
42                      :max_id => changeset.max_id
43                    }
44                  end
45
46         indexed = mapped.index_by { |entry| entry[:date] }
47
48         # Pad the start by one week to ensure the heatmap can start on the first day of the week
49         all_days = ((1.year.ago - 1.week).beginning_of_day.to_date..today.to_date).map do |date|
50           indexed[date] || { :date => date, :total_changes => 0 }
51         end
52
53         # Get unique months with repeating months and count into the next year with numbers over 12
54         month_offset = 0
55         months = ((1.year.ago - 2.weeks).beginning_of_day.to_date..(today + 1.week).to_date)
56                  .map(&:month)
57                  .chunk_while { |before, after| before == after }
58                  .map(&:first)
59                  .map do |month|
60                    month_offset += 12 if month == 1
61                    month + month_offset
62                  end
63
64         total = mapped.sum { |entry| entry[:total_changes] }
65         max_per_day = mapped.map { |entry| entry[:total_changes] }.max
66
67         {
68           :days => all_days,
69           :months => months,
70           :total => total,
71           :max_per_day => max_per_day
72         }
73       end
74     else
75       render_unknown_user params[:display_name]
76     end
77   end
78
79   def new
80     @title = t ".title"
81     @referer = safe_referer(params[:referer])
82
83     parse_oauth_referer @referer
84
85     if current_user
86       # The user is logged in already, so don't show them the signup
87       # page, instead send them to the home page
88       redirect_to @referer || { :controller => "site", :action => "index" }
89     elsif params.key?(:auth_provider) && params.key?(:auth_uid)
90       @email_hmac = params[:email_hmac]
91
92       self.current_user = User.new(:email => params[:email],
93                                    :display_name => params[:nickname],
94                                    :auth_provider => params[:auth_provider],
95                                    :auth_uid => params[:auth_uid])
96
97       if current_user.valid? || current_user.errors[:email].empty?
98         flash.now[:notice] = render_to_string :partial => "auth_association"
99       else
100         flash.now[:warning] = t ".duplicate_social_email"
101       end
102     else
103       check_signup_allowed
104
105       self.current_user = User.new
106     end
107   end
108
109   def create
110     self.current_user = User.new(user_params)
111
112     if check_signup_allowed(current_user.email)
113       if current_user.auth_uid.present?
114         # We are creating an account with external authentication and
115         # no password was specified so create a random one
116         current_user.pass_crypt = SecureRandom.base64(16)
117         current_user.pass_crypt_confirmation = current_user.pass_crypt
118       end
119
120       if current_user.invalid?
121         # Something is wrong with a new user, so rerender the form
122         render :action => "new"
123       else
124         # Save the user record
125         if save_new_user params[:email_hmac]
126           SIGNUP_IP_LIMITER&.update(request.remote_ip)
127           SIGNUP_EMAIL_LIMITER&.update(canonical_email(current_user.email))
128
129           flash[:matomo_goal] = Settings.matomo["goals"]["signup"] if defined?(Settings.matomo)
130
131           referer = welcome_path(welcome_options(params[:referer]))
132
133           if current_user.status == "active"
134             successful_login(current_user, referer)
135           else
136             session[:pending_user] = current_user.id
137             UserMailer.signup_confirm(current_user, current_user.generate_token_for(:new_user), referer).deliver_later
138             redirect_to :controller => :confirmations, :action => :confirm, :display_name => current_user.display_name
139           end
140         else
141           render :action => "new", :referer => params[:referer]
142         end
143       end
144     end
145   end
146
147   def go_public
148     current_user.data_public = true
149     current_user.save
150     flash[:notice] = t ".flash success"
151     redirect_to account_path
152   end
153
154   ##
155   # omniauth success callback
156   def auth_success
157     referer = request.env["omniauth.params"]["referer"]
158     auth_info = request.env["omniauth.auth"]
159
160     provider = auth_info[:provider]
161     uid = auth_info[:uid]
162     name = auth_info[:info][:name]
163     email = auth_info[:info][:email]
164
165     email_verified = case provider
166                      when "openid"
167                        uid.match(%r{https://www.google.com/accounts/o8/id?(.*)}) ||
168                        uid.match(%r{https://me.yahoo.com/(.*)})
169                      when "google", "facebook", "microsoft", "github", "wikipedia"
170                        true
171                      else
172                        false
173                      end
174
175     if settings = session.delete(:new_user_settings)
176       current_user.auth_provider = provider
177       current_user.auth_uid = uid
178
179       update_user(current_user, settings)
180
181       flash.discard
182
183       session[:user_errors] = current_user.errors.as_json
184
185       redirect_to account_path
186     else
187       user = User.find_by(:auth_provider => provider, :auth_uid => uid)
188
189       if user.nil? && provider == "google"
190         openid_url = auth_info[:extra][:id_info]["openid_id"]
191         user = User.find_by(:auth_provider => "openid", :auth_uid => openid_url) if openid_url
192         user&.update(:auth_provider => provider, :auth_uid => uid)
193       end
194
195       if user
196         case user.status
197         when "pending"
198           unconfirmed_login(user, referer)
199         when "active", "confirmed"
200           successful_login(user, referer)
201         when "suspended"
202           failed_login({ :partial => "sessions/suspended_flash" }, user.display_name, referer)
203         else
204           failed_login(t("sessions.new.auth failure"), user.display_name, referer)
205         end
206       else
207         email_hmac = UsersController.message_hmac(email) if email_verified && email
208         redirect_to :action => "new", :nickname => name, :email => email, :email_hmac => email_hmac,
209                     :auth_provider => provider, :auth_uid => uid, :referer => referer
210       end
211     end
212   end
213
214   ##
215   # omniauth failure callback
216   def auth_failure
217     flash[:error] = t(params[:message], :scope => "users.auth_failure", :default => t(".unknown_error"))
218
219     origin = safe_referer(params[:origin]) if params[:origin]
220
221     redirect_to origin || login_url
222   end
223
224   def self.message_hmac(text)
225     sha256 = Digest::SHA256.new
226     sha256 << Rails.application.key_generator.generate_key("openstreetmap/email_address")
227     sha256 << text
228     Base64.urlsafe_encode64(sha256.digest)
229   end
230
231   private
232
233   def save_new_user(email_hmac)
234     current_user.data_public = true
235     current_user.description = "" if current_user.description.nil?
236     current_user.creation_address = request.remote_ip
237     current_user.languages = http_accept_language.user_preferred_languages
238     current_user.terms_agreed = Time.now.utc
239     current_user.tou_agreed = Time.now.utc
240     current_user.terms_seen = true
241
242     if current_user.auth_uid.blank?
243       current_user.auth_provider = nil
244       current_user.auth_uid = nil
245     elsif email_hmac && ActiveSupport::SecurityUtils.secure_compare(email_hmac, UsersController.message_hmac(current_user.email))
246       current_user.activate
247     end
248
249     current_user.save
250   end
251
252   def welcome_options(referer = nil)
253     uri = URI(referer) if referer.present?
254
255     return { "oauth_return_url" => uri&.to_s } if uri&.path == oauth_authorization_path
256
257     begin
258       %r{map=(.*)/(.*)/(.*)}.match(uri.fragment) do |m|
259         editor = Rack::Utils.parse_query(uri.query).slice("editor")
260         return { "zoom" => m[1], "lat" => m[2], "lon" => m[3] }.merge(editor)
261       end
262     rescue StandardError
263       # Use default
264     end
265   end
266
267   ##
268   # return permitted user parameters
269   def user_params
270     params.expect(:user => [:email, :display_name,
271                             :auth_provider, :auth_uid,
272                             :pass_crypt, :pass_crypt_confirmation])
273   end
274
275   ##
276   # check signup acls
277   def check_signup_allowed(email = nil)
278     domain = if email.nil?
279                nil
280              else
281                email.split("@").last
282              end
283
284     mx_servers = if domain.nil?
285                    nil
286                  else
287                    domain_mx_servers(domain)
288                  end
289
290     return true if Acl.allow_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
291
292     blocked = Acl.no_account_creation(request.remote_ip, :domain => domain, :mx => mx_servers)
293
294     blocked ||= SIGNUP_IP_LIMITER && !SIGNUP_IP_LIMITER.allow?(request.remote_ip)
295
296     blocked ||= email && SIGNUP_EMAIL_LIMITER && !SIGNUP_EMAIL_LIMITER.allow?(canonical_email(email))
297
298     if blocked
299       logger.info "Blocked signup from #{request.remote_ip} for #{email}"
300
301       render :action => "blocked"
302     end
303
304     !blocked
305   end
306 end