-
-
Save clayton/556f80441f58b35451346dce466ecf53 to your computer and use it in GitHub Desktop.
Apple Authentication Concern for Mixing into a User model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## | |
| # | |
| # 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