Managing Users
All chat applications have a notion of a user. It's important to be able to uniquely identify users as they interact with the PubNub Network. Usually, a user is a human end user—a person using an app to interact with a system (via a laptop, phone, tablet, or kiosk).
For more details on working with users, refer to User and Device Management.
Set user identifier
You use a uuid
to uniquely identify each user on the system. Users can connect from multiple devices, such as phones, tablets, desktops, etc., using the same uuid
. If a user is connected from multiple devices simultaneously, they will receive the same messages on each device.
First, set up your application. Then, initialize the PubNub client API context and establish account-level credentials such as publish and subscribe keys. You can create a free account and get your keys from the Admin Portal.
Each client should pass a uuid
that represents the user when it connects to PubNub. A uuid
is a string with a maximum length of 64 characters.
UUID is Required
The uuid
is required to ensure that your billing is accurate, and for other features like presence and storage to work as expected.
const pubnub = new PubNub({
subscribeKey: "mySubscribeKey",
publishKey: "myPublishKey",
uuid: "user-1",
autoNetworkDetection: true, // enable for non-browser environment automatic reconnection
restore: true, // enable catchup on missed messages
});
var config = PubNubConfiguration(publishKey: "myPublishKey", subscribeKey: "mySubscribeKey")
config.uuid = "user-1"
config.catchUpOnSubscriptionRestore = true // enable catchup on missed messages
let pubnub = PubNub(configuration: config)
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("mySubscribeKey");
pnConfiguration.setPublishKey("myPublishKey");
pnConfiguration.setUuid("user-1");
PubNub pubnub = new PubNub(pnConfiguration);
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "mySubscribeKey";
pnConfiguration.PublishKey = "myPublishKey";
pnConfiguration.UUID = "user-1";
PubNub pubnub = new PubNub(pnConfiguration);
const pubnub = new PubNub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
uuid: "server-1"
});
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.PublishKey = "myPublishKey";
pnConfiguration.SubscribeKey = "mySubscribeKey";
pnConfiguration.Secure = true;
pnConfiguration.Uuid = "server-1";
PubNub pubnub = new PubNub(pnConfiguration);
import (
pubnub "github.com/pubnub/go"
)
config := pubnub.NewConfig()
config.PublishKey = "myPublishKey"
config.SubscribeKey = "mySubscribeKey"
config.UUID = "server-1"
pn := pubnub.NewPubNub(config)
Manage user metadata
Clients can optionally store metadata such as a name, profile URL, external ID, and email address. You can also use a custom field to store additional data for a user. The metadata can be fetched by other users and persists in the database until it's explicitly removed. Some examples of custom data are display names, last online time, and user roles.
PubNub generates user metadata events when a user metadata is set or deleted. Clients can add Objects Listeners to receive these events.
Set user metadata
The setUUIDMetadata
method stores user metadata in PubNub. You can use it to add new or update existing metadata properties. The method returns the updated user metadata, including the user's custom data.
Note
If you update the custom
property, you must completely replace the entire object; partial updates aren't supported.
pubnub.objects.setUUIDMetadata({
data: {
name: "John Doe",
email: "johndoe@pubnub.com",
custom: {
"nickname": "Mr. Mysterious"
}
}
});
let johnDoe = PubNubUUIDMetadataBase(
id: "john-doe", name: "John Doe",
custom: ["title": "Mr. Manager"]
)
pubnub.set(user: johnDoe) { result in
switch result {
case let .success(uuidMetadata):
print("The metadata for `\(uuidMetadata.metadataId)`: \(uuidMetadata)")
case let .failure(error):
print("Create request failed with error: \(error.localized### Description)")
}
}
self.client.objects().setUUIDMetadata()
.uuid(@"uuid")
.name(@"John Doe")
.custom(@{ @"nickname": @("Mr. Mysterious") })
.email(@"johndoe@pubnub.com")
.includeFields(PNUUIDCustomField)
.performWithCompletion(^(PNSetUUIDMetadataStatus *status) {
if (!status.isError) {
/**
* UUID metadata successfully has been set.
* UUID metadata information available here: status.data.metadata
*/
} else {
/**
* Handle UUID metadata set error. Check 'category' property to find out possible issue
* because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
Map<String, Object> custom = new HashMap<>();
custom.put("nickname", "Mr. Mysterious");
pubnub.setUUIDMetadata()
.name("John Doe")
.email("johndoe@pubnub.com")
.custom(custom)
.includeCustom(true)
.async(new PNCallback<PNSetUUIDMetadataResult>() {
@Override
public void onResponse(@Nullable final PNSetUUIDMetadataResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
}
else {
//handle result
}
}
});
PNResult<PNSetUuidMetadataResult> setUuidMetadataResponse = await pubnub.SetUuidMetadata()
.Uuid(config.Uuid)
.Name("John Doe")
.Email("johndoe@pubnub.com")
.Custom(new Dictionary<string, object>() { { "nickname", "Mr. Mysterious" } })
.ExecuteAsync();
PNSetUuidMetadataResult setUuidMetadataResult = setUuidMetadataResponse.Result;
PNStatus status = setUuidMetadataResponse.Status;
Sample user metadata event:
{
"channel":"ch-1",
"message":{
"event":"set",
"type":"uuid",
"data":{
"id":"uuid-1",
"name":"John Doe",
"email":"john@email.com",
"updated":"2020-06-10T16:22:11.035374Z",
"eTag":"AY39mJKK//C0VA"
}
},
"subscription":null,
"timetoken":"15119446002445794"
}
Refer to User Metadata to learn more about working with user metadata.