El SDK de Realm permite múltiples Los usuarios deben iniciar sesión simultáneamente en una aplicación en un dispositivo determinado. Las aplicaciones cliente de Realm se ejecutan en el contexto de un solo usuario activo, incluso si varios usuarios inician sesión simultáneamente. Puede cambiar rápidamente entre usuarios autenticados sin necesidad de que vuelvan a iniciar sesión.
Importante
Cualquier usuario que haya iniciado sesión puede convertirse en el usuario activo sin tener que volver a autenticarse. Dependiendo de la aplicación, esto podría representar una vulnerabilidad de seguridad. Por ejemplo, un usuario en un dispositivo compartido podría cambiar a la cuenta iniciada de un compañero sin proporcionar sus credenciales ni requerir su permiso explícito. Si su aplicación requiere una autenticación más estricta, evite cambiar de usuario y cierre la sesión del usuario activo explícitamente antes de autenticar a otro.
User Account States
Cuando un usuario inicia sesión por primera vez a través de un SDK de Realm en un dispositivo o navegador determinado, el SDK guarda la información del usuario y rastrea el estado del usuario en el dispositivo. Los datos del usuario permanecen en el dispositivo, incluso si cierra sesión, a menos que remuevas al usuarioactivamente.
Los siguientes estados describen a un usuario en el dispositivo en un momento dado:
Autenticado: cualquier usuario que haya iniciado sesión en el dispositivo y no haya cerrado sesión o se le haya revocado la sesión.
Active: a single authenticated user that is currently using the app on a given device. The SDK associates this user with outgoing requests and Atlas App Services evaluates data access permissions and runs functions in this user's context. See active user for more information.
Inactive: all authenticated users that are not the current active user. You can switch the active user to a currently inactive user at any time.
Logged Out: any user that authenticated on the device but has since logged out or had their session revoked.
El siguiente diagrama muestra cómo los usuarios dentro de una aplicación cliente de App Services pasan entre estados cuando ocurren ciertos eventos:

Agregar un nuevo usuario al dispositivo
El SDK de Realm añade automáticamente usuarios a un dispositivo cuando inician sesión por primera vez. Al iniciar sesión, se convierte inmediatamente en usuario activo de la aplicación.
Ejemplo
En el siguiente ejemplo, un usuario con el correo electrónico joe@example.com Inicia sesión y se convierte en el usuario activo. Posteriormente, un usuario con el correo electrónico emma@example.com inicia sesión y se convierte en el usuario activo.
const app = new Realm.App({ id: "myapp-abcde" }); // Log in as Joe const joeCredentials = Realm.Credentials.emailPassword("joe@example.com", "passw0rd") const joe = await app.logIn(joeCredentials); // The active user is now Joe assert(joe.id === app.currentUser.id); // Log in as Emma const emmaCredentials = Realm.Credentials.emailPassword("emma@example.com", "pa55word") const emma = await app.logIn(emmaCredentials); // The active user is now Emma, but Joe is still logged in assert(emma.id === app.currentUser.id);
const app = new Realm.App({ id: "myapp-abcde" }); // Log in as Joe const joeCredentials = Realm.Credentials.emailPassword("joe@example.com", "passw0rd") const joe = await app.logIn(joeCredentials); // The active user is now Joe assert(joe.id === app.currentUser.id); // Log in as Emma const emmaCredentials = Realm.Credentials.emailPassword("emma@example.com", "pa55word") const emma = await app.logIn(emmaCredentials); // The active user is now Emma, but Joe is still logged in assert(emma.id === app.currentUser.id);
Listar todos los usuarios del dispositivo
You can access a list of all user accounts on the device. This list includes all users that have logged in to the client app on a given device.
Ejemplo
En el siguiente ejemplo, un desarrollador imprime todos los usuarios conectados al dispositivo recorriendo Realm.App.allUsers.
// Get a list of all Users app.allUsers.forEach(user => { console.log(`User with id ${user.id} is ${user.isLoggedIn ? "logged in" : "logged out"}`); });
// Get a list of all Users app.allUsers.forEach((user: Realm.User) => { console.log(`User with id ${user.id} is ${user.isLoggedIn ? "logged in" : "logged out"}`); });
Remove a User from the Device
You can remove all information about a user from the device and automatically log the user out.
Ejemplo
En el siguiente ejemplo, el usuario actual se elimina del dispositivo mediante el método Realm.App.removeUser().
// Remove the current user from the device const user = app.currentUser; await app.removeUser(user); // The user is no longer the active user if(app.currentUser) { // The active user is now the logged in user (if there still is one) that was // most recently active assert(user.id !== app.currentUser.id) } // The user is no longer on the device assert(app.allUsers.find(({ id }) => id === user.id) === undefined);
// Remove the current user from the device const user = app.currentUser; await app.removeUser(user); // The user is no longer the active user // The active user is now the logged in user (if there still is one) that was // most recently active assert(user.id !== app.currentUser?.id) // The removed user is no longer on the device assert(app.allUsers.find(({ id }) => id === user.id) === undefined);
Cambiar el usuario activo
You can quickly switch an app's active user to another logged-in user at any time.
Ejemplo
En el siguiente ejemplo, el usuario activo se cambia inicialmente a user1 usando el Realm.aplicación.switchUser() método. Luego, el usuario activo se cambia a user2.
// Get some logged-in users const authenticatedUsers = app.allUsers.filter(user => user.isLoggedIn); const user1 = authenticatedUsers[0]; const user2 = authenticatedUsers[1]; // Switch to user1 app.switchUser(user1); // The active user is now user1 assert(app.currentUser.id === user1.id); // Switch to user2 app.switchUser(user2); // The active user is now user2 assert(app.currentUser.id === user2.id);
// Get some logged-in users const authenticatedUsers = app.allUsers.filter(user => user.isLoggedIn); const user1 = authenticatedUsers[0]; const user2 = authenticatedUsers[1]; // Switch to user1 app.switchUser(user1); // The active user is now user1 assert(app.currentUser.id === user1.id); // Switch to user2 app.switchUser(user2); // The active user is now user2 assert(app.currentUser.id === user2.id);