Skip to content

Instantly share code, notes, and snippets.

@clayton
Last active March 25, 2025 05:22
Show Gist options
  • Select an option

  • Save clayton/556f80441f58b35451346dce466ecf53 to your computer and use it in GitHub Desktop.

Select an option

Save clayton/556f80441f58b35451346dce466ecf53 to your computer and use it in GitHub Desktop.
Apple Authentication Concern for Mixing into a User model
##
#
# Intended to be included in your User model
# class User < ApplicationRecord
# include AppleAuthenticatable
#
# <everything else>
#
# end
#
module AppleAuthenticatable
extend ActiveSupport::Concern
included do
# Class method to find existing user or create a new one from Apple Sign In data
def self.find_or_create_from_apple(id_token, user_params)
# Try to find existing user by Apple's unique identifier
user = User.find_by(
oauth_uid: id_token.sub,
oauth_provider: "apple"
)
# Return existing user if found
return user if user.present?
# Otherwise create a new user
user = User.new
# Store Apple's unique identifier (sub) as the oauth_uid
user.oauth_uid = id_token.sub
user.oauth_provider = "apple"
# Generate a secure random password (user won't need this for OAuth login)
# Optional, but if you have a password field that's validated, you might need
# to set it here when creating a user.
# user.password = SecureRandom.hex(16)
# user.password_confirmation = user.password
# Set email if provided by Apple (may be nil for private email relay)
user.email = user_params["email"] if user_params["email"].present?
# Combine first and last name if provided
user.name = [ user_params["name"]["firstName"], user_params["name"]["lastName"] ].compact.join(" ") if user_params["name"].present?
# Save the new user
user.save!
user
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment