Class: Panda::Core::User

Inherits:
ApplicationRecord show all
Defined in:
app/models/panda/core/user.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.find_or_create_from_auth_hash(auth_hash) ⇒ Object



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
49
50
51
52
53
54
55
56
57
# File 'app/models/panda/core/user.rb', line 18

def self.find_or_create_from_auth_hash(auth_hash)
  user = find_by(email: auth_hash.info.email.downcase)

  # Handle avatar for both new and existing users
  avatar_url = auth_hash.info.image
  if user
    # Update avatar if URL has changed or no avatar is attached
    if avatar_url.present? && (avatar_url != user.oauth_avatar_url || !user.avatar.attached?)
      AttachAvatarService.call(user: user, avatar_url: avatar_url)
    end
    return user
  end

  # Support both schema versions: 'name' column or 'firstname'/'lastname' columns
  attributes = {
    email: auth_hash.info.email.downcase,
    image_url: auth_hash.info.image,
    is_admin: User.count.zero? # First user is admin
  }

  # Add name attributes based on schema
  if column_names.include?("name")
    attributes[:name] = auth_hash.info.name || "Unknown User"
  elsif column_names.include?("firstname") && column_names.include?("lastname")
    # Split name into firstname/lastname if provided
    full_name = auth_hash.info.name || "Unknown User"
    name_parts = full_name.split(" ", 2)
    attributes[:firstname] = name_parts[0] || "Unknown"
    attributes[:lastname] = name_parts[1] || "User"
  end

  user = create!(attributes)

  # Attach avatar for new user
  if avatar_url.present?
    AttachAvatarService.call(user: user, avatar_url: avatar_url)
  end

  user
end

Instance Method Details

#active_for_authentication?Boolean

Returns:

  • (Boolean)


63
64
65
# File 'app/models/panda/core/user.rb', line 63

def active_for_authentication?
  true
end

#admin?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'app/models/panda/core/user.rb', line 59

def admin?
  is_admin
end

#avatar_urlObject

Returns the URL for the user’s avatar Prefers Active Storage attachment over OAuth provider URL



82
83
84
85
86
87
88
89
# File 'app/models/panda/core/user.rb', line 82

def avatar_url
  if avatar.attached?
    Rails.application.routes.url_helpers.rails_blob_path(avatar, only_path: true)
  elsif self[:image_url].present?
    # Fallback to OAuth provider URL if no avatar is attached yet
    self[:image_url]
  end
end

#nameObject



67
68
69
70
71
72
73
74
75
76
77
78
# File 'app/models/panda/core/user.rb', line 67

def name
  # Support both schema versions:
  # - Main app: has 'name' column
  # - Test app: has 'firstname' and 'lastname' columns
  if respond_to?(:firstname) && respond_to?(:lastname)
    "#{firstname} #{lastname}".strip
  elsif self[:name].present?
    self[:name]
  else
    email&.split("@")&.first || "Unknown User"
  end
end