updateUserScopes static method

Future<UserInfo?> updateUserScopes(
  1. Session session,
  2. int userId,
  3. Set<Scope> newScopes
)

Updates the scopes a user can access.

Implementation

static Future<UserInfo?> updateUserScopes(
  Session session,
  int userId,
  Set<Scope> newScopes,
) async {
  var userInfo = await findUserByUserId(session, userId, useCache: false);
  if (userInfo == null) return null;

  var removedScopes = userInfo.scopes.difference(newScopes);
  var scopeStrs = newScopes.map((s) => s.name).whereType<String>().toList();
  userInfo.scopeNames = scopeStrs;
  await UserInfo.db.updateRow(session, userInfo);

  // Update all authentication keys too.
  var json = SerializationManager.encode(scopeStrs);
  await session.db.unsafeQuery(
      'UPDATE serverpod_auth_key SET "scopeNames"=\'$json\' WHERE "userId" = $userId');

  if (AuthConfig.current.onUserUpdated != null) {
    await AuthConfig.current.onUserUpdated!(session, userInfo);
  }

  var scopesHaveBeenRevoked = removedScopes.isNotEmpty;
  if (scopesHaveBeenRevoked) {
    var removedScopesList =
        removedScopes.map((s) => s.name).whereType<String>().toList();
    await session.messages.authenticationRevoked(
      userId,
      RevokedAuthenticationScope(
        scopes: removedScopesList,
      ),
    );
  }

  await invalidateCacheForUser(session, userId);
  return userInfo;
}