How to check if the logged-in Realm user logged in via "Sign in with Apple"?

Viewed 308

The alternative title is "How to check the logged-in Realm user logged in via certain authentication provider?" OR "How to check a user is using a specific authentication provider/method?"


For an app start with an anonymous user and then linked to another authentication provider using user.linkUser(credentials: credential). Since the user always has a value either an anonymous user or a linked user.

How can I know if the current logged-in user is already linked with another auth provider e.g. "Sign in with Apple" or "Google"? This information needs to be known in order to hide the auth provider sign-in button.

2 Answers

In RealmSwift 10.12.0

There is an identifiers property under user. It is an array of RLMUserIdentity. the user identity contains a providerType string, https://docs.mongodb.com/realm-sdks/objc/latest/Classes/RLMUserIdentity.html#/c:objc(cs)RLMUserIdentity(py)providerType

Below is a sample output

print(">>> DEBUG:", user.identities.map { identity in (identity.identifier, identity.providerType)

[("611a27f9a1575af5ed15234e-lnnaeteekatdftrnsmpbpldr", "anon-user"), ("000766.23cbd125344c140b18ef0baa4deccaf32.61234", "oauth2-apple")]

Now you can check if the user identities contains the provider you care and hide the "sign in" button/link for that provider

https://github.com/realm/realm-cocoa/blob/d407cdc1c8be5f04c3decd37b88524855edfa7e8/Realm/RLMCredentials.mm

When you initialize a realm app, it checks by default for the accessToken, refresh token and other stuff that Realm does to store user data on the device after successful login. So, the default value when you declare your current user should be retrieved from Realm app instance. In my case, I use web development and it looks like this for React application.

import React, { useState } from 'react';    
import LoginPage from 'containers/LoginPage';
import { RealmApp, getCustomCredentials } from './RealmApp';

function App() {
  const [currentUser, setCurrentUser] = useState(RealmApp.currentUser);

  const onAuth = async (data) => {
    const credentials = getCustomCredentials(data);
    const user = await RealmApp.logIn(credentials);
    setCurrentUser(user);
  };

  const App = () => {
    return (
      <Box className="app-root-component" sx={{ display: 'flex' }}>
        <h1>App</>
      </Box>
    );
  };

  return currentUser ? <App /> : <LoginPage onAuth={onAuth} />;
}

export default App;

here I have my variable & it's setter function

const [currentUser, setCurrentUser] = useState(RealmApp.currentUser);

I wish that helps you to get closer with apple sign in

Related