User management

The operations performed on users, such as updating and deleting, have an effect on all products (chat, feeds and video).

Creating users

When creating users, there are a few important things to keep in mind:

  • The id field is mandatory, in most cases you want this to be the same ID you use on your database.
  • The role field is optional, by default it is set to user but you can specify any existing role.
  • Custom data can be added to users in the custom field.
  • name and image are optional and handled by all SDKs automatically to render users.
use GetStream\ClientBuilder;
use GetStream\GeneratedModels;

$client = (new ClientBuilder())
    ->apiKey($apiKey)
    ->apiSecret($apiSecret)
    ->build();

$response = $client->updateUsers(new GeneratedModels\UpdateUsersRequest(
    users: [
        'user-id-1' => [
            'id' => 'user-id-1',
            'name' => 'Test User 1',
            'role' => 'user',
            'custom' => (object)[
                'color' => 'red'
            ]
        ],
        'user-id-2' => [
            'id' => 'user-id-2',
            'name' => 'Test User 2',
            'role' => 'user'
        ]
    ]
));

Built-in fields for users

UserResponse

NameTypeDescriptionConstraints
avg_response_timeinteger--
ban_expiresnumberDate when ban expires-
bannedbooleanWhether a user is banned or notRequired
blocked_user_idsstring[]-Required
created_atnumberDate/time of creationRequired
customobjectCustom data for this objectRequired
deactivated_atnumberDate of deactivation-
deleted_atnumberDate/time of deletion-
devicesDeviceResponse[]List of devices user is using-
idstringUnique user identifierRequired
imagestring--
invisibleboolean-Required
languagestringPreferred language of a userRequired
last_activenumberDate of last activity-
namestringOptional name of user-
onlinebooleanWhether a user online or notRequired
privacy_settingsPrivacySettingsResponseUser privacy settings-
push_notificationsPushNotificationSettingsResponseUser push notification settings-
revoke_tokens_issued_beforenumberRevocation date for tokens-
rolestringDetermines the set of user permissionsRequired
shadow_bannedbooleanWhether a user is shadow bannedRequired
teamsstring[]List of teams user is a part ofRequired
teams_roleobject--
updated_atnumberDate/time of the last updateRequired

Querying users

You can query and filter users using the queryUsers endpoint. This allows you to search for users based on various criteria such as custom fields, roles, and other user properties.

$response = $client->queryUsers(
    new GeneratedModels\QueryUsersPayload(
        filterConditions: (object)['role' => 'admin'],
        sort: [
            ['field' => 'created_at', 'direction' => -1]
        ],
        limit: 10,
        offset: 0
    )
);

All filters use a Mongoose-style syntax; however, we do not run MongoDB on the backend, so only a subset of Mongoose queries are supported. The supported filters are described below.

Supported Filters

NameTypeDescriptionAllowed Operators
idstringID of the user$eq, $gt, $gte, $lt, $lte, $in, $autocomplete
rolestringRole of the user$eq, $gt, $gte, $lt, $lte, $in
bannedbooleanWhether the user is banned$eq
shadow_bannedbooleanWhether the user is shadow banned$eq
created_atstring, must be formatted as an RFC3339 timestampTime when the user was created$eq, $gt, $gte, $lt, $lte, $in
updated_atstring, must be formatted as an RFC3339 timestampTime when the user was updated$eq, $gt, $gte, $lt, $lte, $in
last_activestring, must be formatted as an RFC3339 timestampTime when the user was last active$eq, $gt, $gte, $lt, $lte, $in, $exists
teamsstringTeams the user belongs to$eq, $contains
namestringName of the user$eq, $autocomplete
usernamestringUsername of the user$eq, $autocomplete
custom propertiesstring, boolean, intCustom user properties$eq, $gt, $gte, $lt, $lte, $in

Supported Sort

You can sort results by specifying a field and direction (1 for ascending, -1 for descending).

NameDescription
idUser ID
created_atTime when the user was created
updated_atTime when the user was updated
last_activeTime when the user was last active
roleRole of the user

Supported Options

The options for the queryUsers method are primarily used for pagination.

NameTypeDescriptionDefaultOptional
limitintegerNumber of users to return30
offsetintegerOffset for pagination0
id_gtstringID-based pagination. Return IDs greater than this ID. If this is not empty, the default sort order will be [{id: -1}].-
id_gtestringID-based pagination. Return IDs greater than or equal to this ID. If this is not empty, the default sort order will be [{id: -1}].-
id_ltstringID-based pagination. Return IDs less than this ID. If this is not empty, the default sort order will be [{id: -1}].-
id_ltestringID-based pagination. Return IDs less than or equal to this ID. If this is not empty, the default sort order will be [{id: -1}].-
include_deactivated_usersbooleanInclude deactivated users in the response-

The maximum offset value is 1000.

Filter examples

You can use various filter operators to query users:

// Query users by custom field
$response = $client->queryUsers(
    new GeneratedModels\QueryUsersPayload(
        filterConditions: (object)['custom.color' => 'red']
    )
);

// Query users with multiple conditions
$response2 = $client->queryUsers(
    new GeneratedModels\QueryUsersPayload(
        filterConditions: (object)[
            'role' => (object)['$in' => ['admin', 'moderator']],
            'custom.age' => (object)['$gte' => 18],
        ]
    )
);

// Query users by name (text search)
$response3 = $client->queryUsers(
    new GeneratedModels\QueryUsersPayload(
        filterConditions: (object)[
            'name' => (object)['$autocomplete' => 'john'],
        ]
    )
);

Updating users

You can update users in two ways:

  • Replace updates: replace the entire user object with the one provided to the API call
  • Partial update: choose which fields you want to change
// Example 1: Upsert users (replace update)
$client->updateUsers(new GeneratedModels\UpdateUsersRequest(
    users: [
        'userid' => [
            'id' => 'userid',
            'name' => 'This is a test user',
            'role' => 'user',
            'custom' => (object)[
                'color' => 'blue'
            ],
            'image' => 'link/to/profile/image'
        ]
    ]
));

// Example 2: Partial update users
$client->updateUsersPartial(new GeneratedModels\UpdateUsersPartialRequest(
    users: [
        [
            'id' => 'userid',
            'set' => (object)[
                'new-field' => 'value'
            ],
            'unset' => ['name']
        ]
    ]
));

Deactivating and deleting users

Depending on your use-case, you can choose to delete users or de-activating them. There are some differences between these two approach.

Deactivating users:

  • the user will not be allowed to perform API requests / connect
  • user data is retained on Stream's side and returned from API
  • deactivated users can be re-activated

Deleting users:

  • the user will no longer be able to perform API requests / connect
  • the user is deleted and by default not returned from API
  • all data from the user is marked as deleted
  • by default the data is retained and "soft" deleted, you can optionally request hard deletion
  • deletion is not reversible

Note: Both deletion and deactivation are performed asynchronously by Stream API. A task ID is returned and you can use that to check the status of its processing.

Deactivating users

// Deactivating a single user
$client->deactivateUser(
    'user1',
    new GeneratedModels\DeactivateUserRequest()
);

// Deactivating users in bulk is performed asynchronously
$response = $client->deactivateUsers(
    new GeneratedModels\DeactivateUsersRequest(
        userIds: ['user1', 'user2']
    )
);

// Reactivate users
$client->reactivateUsers(
    new GeneratedModels\ReactivateUsersRequest(
        userIds: ['user1', 'user2']
    )
);

Deactivating users in bulk can take some time, this is how you can check the progress:

// Example of monitoring the status of an async task
// The logic is same for all async tasks
$response = _ // Result of a Stream async API request

$taskId = $response->getData()->taskID;

// you need to poll this endpoint
$taskResponse = $client->getTask($taskId);

echo $taskResponse->getData()->status === 'completed';

Deleting users

// Delete users (soft delete by default)
$client->deleteUsers(
    new GeneratedModels\DeleteUsersRequest(
        userIds: ['<id>']
    )
);

// Delete users with options (hard delete)
$client->deleteUsers(
    new GeneratedModels\DeleteUsersRequest(
        userIds: ['<id>'],
        user: 'hard',
        messages: 'hard',
        conversations: 'hard',
        newChannelOwnerID: 'new-owner-id'
    )
);

// Restore users
$client->restoreUsers(
    new GeneratedModels\RestoreUsersRequest(
        userIds: ['<id>']
    )
);

The delete users endpoints supports the following parameters to control which data needs to be deleted and how. By default users and their data are soft-deleted.

NameTypeDescriptionOptional
userEnum (soft, pruning, hard)- Soft: marks user as deleted and retains all user data.
- Pruning: marks user as deleted and nullifies user information.
- Hard: deletes user completely - this requires hard option for messages and conversation as well.
Yes
conversationsEnum (soft, hard)- Soft: marks all conversation channels as deleted (same effect as Delete Channels with 'hard' option disabled).
- Hard: deletes channel and all its data completely including messages (same effect as Delete Channels with 'hard' option enabled).
Yes
messagesEnum (soft, pruning, hard)- Soft: marks all user messages as deleted without removing any related message data.
- Pruning: marks all user messages as deleted, nullifies message information and removes some message data such as reactions and flags.
- Hard: deletes messages completely with all related information.
Yes
new_channel_owner_idstringChannels owned by hard-deleted users will be transferred to this userID. If you doesn't provide a value, the channel owner will have a system generated ID like delete-user-8219f6578a7395gYes
callsEnum (soft, hard)- Soft: marks calls and related data as deleted.
- Hard: deletes calls and related data completely
Note that this applies only to 1:1 calls, not group calls
Yes

Deleting users in bulk can take some time, this is how you can check the progress:

// Example of monitoring the status of an async task
// The logic is same for all async tasks
$response = _ // Result of a Stream async API request

$taskId = $response->getData()->taskID;

// you need to poll this endpoint
$taskResponse = $client->getTask($taskId);

echo $taskResponse->getData()->status === 'completed';