Class: Collavre::GoogleAuthController

Inherits:
ApplicationController show all
Defined in:
app/controllers/collavre/google_auth_controller.rb

Instance Method Summary collapse

Instance Method Details

#callbackObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'app/controllers/collavre/google_auth_controller.rb', line 6

def callback
  auth = request.env["omniauth.auth"]
  user = Collavre::User.find_or_initialize_by(email: auth.info.email)
  if user.new_record?
    user.name = auth.info.name.presence || auth.info.email.split("@").first
    random_password = SecureRandom.hex(16)
    user.password = random_password
    user.password_confirmation = random_password
    user.email_verified_at = Time.current
  end

  if auth.info.image.present? && !user.avatar.attached? && user.avatar_url.blank?
    user.avatar_url = auth.info.image
  end

  # for personal google service (like google calendar)
  user.google_uid = auth.uid
  user.google_access_token = auth.credentials.token
  # Only update refresh_token if Google provides a new one
  # (Google doesn't always return refresh_token on re-authentication)
  if auth.credentials.refresh_token.present?
    user.google_refresh_token = auth.credentials.refresh_token
  end
  user.google_token_expires_at = Time.at(auth.credentials.expires_at) if auth.credentials.expires_at

  user.save! if user.new_record? || user.changed?

  # Ensure app calendar exists if the granted scope allows creating an app calendar
  begin
    ::GoogleCalendarService.new(user: user).ensure_app_calendar!
  rescue StandardError => e
    Rails.logger.error("Post-login calendar setup failed: #{e.message}")
  end

  tz = request.env["omniauth.params"] && request.env["omniauth.params"]["timezone"]
  user.update(timezone: tz) if tz.present? && user.timezone != tz

  return_to = session[:return_to_after_authenticating]
  reset_session
  session[:return_to_after_authenticating] = return_to if return_to
  start_new_session_for(user)
  redirect_to after_authentication_url
end