Moderate misbehaving users
Requires App Context
To work with stored user metadata, you must enable App Context for your app's keyset in the Admin Portal.
Chat SDK provides moderation mechanisms for:
- Admins to mute misbehaving users on channels.
- Admins to ban misbehaving users from accessing channels.
For example, an admin can mute or ban the users from a given channel using Access Manager.
Mute or ban users
As an admin, you can mute/ban a specific user on a channel from accessing that channel or unmute/unban using three setRestrictions()
methods.
All of them give the same output. The only difference is that you call a given method on the Chat
, User
, or the Channel
object. Depending on the object, these methods take a different set of input parameters.
When an admin mutes or bans a user on a channel, a moderation
event is created (of type muted
or banned
). You can listen to these events and, for example, remove user's membership on that channel.
Also, when an admin mutes or bans a user, an additional moderation membership is created for that user. This membership copies the ID of the channel and adds the PUBNUB_INTERNAL_MODERATION_
prefix to it, even though no new channel gets created for that purpose. This moderation membership stores information about the user's current mute
and ban
restrictions under the custom
property.
The reason behind creating an additional moderation membership was to have an object that could be secured with Access Manager and made inaccessible to users. The standard membership object couldn't serve this purpose as it stores info on the users' lastReadMessageTimetoken
custom data that users should access to be able to see unread messages on channels.
The additional membership is created only for the moderation purposes - when fetching all channel memberships for a given user with the getMemberships()
method, you won't see the moderation membership as Chat SDK filters it out automatically with App Context Filtering Language.
When you lift restrictions on the user (unmute or unban them), the moderation membership is removed and a moderation
event of type lifted
is created.
To learn if a user is muted on a given channel or banned, use the Chat SDK methods to check moderation restrictions.
Requires Secret Key authentication
Mute and ban restrictions for the client devices should be set by servers initializing Chat SDK with a Secret Key (available on the Admin Portal on your app's keyset).
The secretKey
should only be used within a secure server and never exposed to client devices. If the secretKey
is ever compromised, it can be an extreme security risk to your application. If you suspect your secretKey
has been compromised, you can generate a new secretKey
for the existing PubNub keyset on the Admin Portal.
Method signature
These methods take the following parameters:
-
setRestrictions()
(on theChat
object)chat.setRestrictions(
restriction: Restriction
): PNFuture<Unit>Definition of the
Restriction
class:class Restriction(
val userId: String,
val channelId: String,
val ban: Boolean = false,
val mute: Boolean = false,
val reason: String?
) -
setRestrictions()
(on theUser
object)user.setRestrictions(
channel: Channel,
ban: Boolean = false,
mute: Boolean = false,
reason: String?,
): PNFuture<Unit> -
setRestrictions()
(on theChannel
object)channel.setRestrictions(
user: User,
ban: Boolean = false,
mute: Boolean = false,
reason: String?
): PNFuture<Unit>
Input
Parameter | Type | Required for Chat | Required for User | Required for Channel | Default | Description |
---|---|---|---|---|---|---|
userId | String | Yes | No | No | n/a | Unique User ID that becomes your app's current user. It's a string of up to 92 characters that identifies a single client (end user, device, or server) that connects to PubNub. Based on User ID, PubNub calculates pricing for your apps' usage. User ID should be persisted and remain unchanged. If you don't set userId , you won't be able to connect to PubNub. In this method, userId stands for the user that you want to mute or ban. |
channelId | String | Yes | No | No | n/a | ID of the channel on/from which the user should be muted or banned. |
channel | Channel | No | Yes | No | n/a | Channel object on/from which the user should be muted or banned. |
user | User | No | No | Yes | n/a | User object to be muted or banned. |
ban | Boolean | No | No | No | false | Value that represents the user's moderation restrictions. Set to true to ban the user from the channel or to false to unban them. |
mute | Boolean | No | No | No | false | Value that represents the user's moderation restrictions. Set to true to mute the user on the channel or to false to unmute them. |
reason | String | No | No | No | n/a | Reason why you want to ban or mute the user. |
Output
Type | Description |
---|---|
PNFuture<Unit> | Function that returns an instance of PNFuture that will be completed with Unit when the setRestrictions operation is completed. |
Basic usage
Mute
Mute support_agent_15
on the support
channel.
-
setRestrictions()
(on theChat
object)
show all 37 lines// reference the "chat" object and invoke the "getUser()" method
chat.getUser("support_agent_15").async { userResult ->
userResult.onSuccess { user ->
if (user != null) {
// get the "support" channel
chat.getChannel("support").async { channelResult ->
channelResult.onSuccess { channel ->
if (channel != null) {
// create a Restriction object to mute the user on the channel
val restriction = Restriction(
userId = user.id,
channelId = channel.id,
mute = true
) -
setRestrictions()
(on theUser
object)
show all 30 lines// reference the "chat" object and invoke the "getUser()" method
chat.getUser("support_agent_15").async { userResult ->
userResult.onSuccess { user ->
if (user != null) {
// get the "support" channel
chat.getChannel("support").async { channelResult ->
channelResult.onSuccess { channel ->
if (channel != null) {
// set the restriction using the User object
user.setRestrictions(channel, mute = true).async { restrictionResult ->
restrictionResult.onSuccess {
// handle success
}.onFailure {
// handle failure
} -
setRestrictions()
(on theChannel
object)
show all 30 lines// reference the "chat" object and invoke the "getUser()" method
chat.getUser("support_agent_15").async { userResult ->
userResult.onSuccess { user ->
if (user != null) {
// get the "support" channel
chat.getChannel("support").async { channelResult ->
channelResult.onSuccess { channel ->
if (channel != null) {
// set the restriction using the Channel object
channel.setRestrictions(user, mute = true).async { restrictionResult ->
restrictionResult.onSuccess {
// handle success
}.onFailure {
// handle failure
}
Ban
Ban support_agent_15
from the support
channel.
-
setRestrictions()
(on theChat
object)
show all 37 lines// reference the "chat" object and invoke the "getUser()" method
chat.getUser("support_agent_15").async { userResult ->
userResult.onSuccess { user ->
if (user != null) {
// get the "support" channel
chat.getChannel("support").async { channelResult ->
channelResult.onSuccess { channel ->
if (channel != null) {
// create a Restriction object to ban the user on the channel
val restriction = Restriction(
userId = user.id,
channelId = channel.id,
ban = true
) -
setRestrictions()
(on theUser
object)
show all 30 lines// reference the "chat" object and invoke the "getUser()" method
chat.getUser("support_agent_15").async { userResult ->
userResult.onSuccess { user ->
if (user != null) {
// get the "support" channel
chat.getChannel("support").async { channelResult ->
channelResult.onSuccess { channel ->
if (channel != null) {
// set the restriction using the User object
user.setRestrictions(channel, ban = true).async { restrictionResult ->
restrictionResult.onSuccess {
// handle success
}.onFailure {
// handle failure
} -
setRestrictions()
(on theChannel
object)
show all 30 lines// reference the "chat" object and invoke the "getUser()" method
chat.getUser("support_agent_15").async { userResult ->
userResult.onSuccess { user ->
if (user != null) {
// get the "support" channel
chat.getChannel("support").async { channelResult ->
channelResult.onSuccess { channel ->
if (channel != null) {
// set the restriction using the Channel object
channel.setRestrictions(user, ban = true).async { restrictionResult ->
restrictionResult.onSuccess {
// handle success
}.onFailure {
// handle failure
}
Check restrictions
One user on one channel
Check if there are any mute
or ban
restrictions set for a user on one channel using the getChannelRestrictions()
and getUserRestrictions()
methods.
Method signature
These methods take the following parameters:
-
getChannelRestrictions()
user.getChannelRestrictions(channel: Channel): PNFuture<Restriction>
-
getUserRestrictions()
channel.getUserRestrictions(user: User): PNFuture<Restriction>
Input
Parameter | Type | Required in getChannelRestrictions() | Required in getUserRestrictions() | Default | Description |
---|---|---|---|---|---|
channel | Channel | Yes | No | n/a | Channel object on/from which the user can be muted or banned. |
user | User | No | Yes | n/a | User object that can be muted or banned. |
Output
Type | Description |
---|---|
PNFuture<Restriction> | PNFuture containing the Restriction object with these properties: userId , channelId , ban mute , and reason . |
Basic usage
Check if the user support_agent_15
has any restrictions set on the support
channel.
-
getChannelRestrictions()
show all 30 lines// reference the "chat" object and invoke the "getUser()" method
chat.getUser("support_agent_15").async { userResult ->
userResult.onSuccess { user ->
if (user != null) {
// get the "support" channel
chat.getChannel("support").async { channelResult ->
channelResult.onSuccess { channel ->
if (channel != null) {
// get the channel restrictions for the user
user.getChannelRestrictions(channel).async { restrictionResult ->
restrictionResult.onSuccess { restriction ->
// handle the restriction object
}.onFailure {
// handle failure
} -
getUserRestrictions()
show all 30 lines// reference the "chat" object and invoke the "getUser()" method
chat.getUser("support_agent_15").async { userResult ->
userResult.onSuccess { user ->
if (user != null) {
// get the "support" channel
chat.getChannel("support").async { channelResult ->
channelResult.onSuccess { channel ->
if (channel != null) {
// get the user restrictions for the channel
channel.getUserRestrictions(user).async { restrictionResult ->
restrictionResult.onSuccess { restriction ->
// handle the restriction object
}.onFailure {
// handle failure
}
One user on all channels
Check if there are any mute
or ban
restrictions set for a user on all channels they are a member of using the getChannelsRestrictions()
method.
Method signature
This method takes the following parameters:
user.getChannelsRestrictions(
limit: Int?,
page: PNPage?,
sort: Collection<PNSortKey<PNMembershipKey>> = listOf(),
): PNFuture<GetRestrictionsResponse>
Input
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
limit | Int | No | 100 | Number of objects to return in response. The default (and maximum) value is 100 . |
page | PNPage | No | n/a | Object used for pagination to define which previous or next result page you want to fetch. |
sort | Collection<PNSortKey<PNMembershipKey>> | No | listOf() | Key-value pair of a property to sort by, and a sort direction. Available options are id , name , and updated . Use asc or desc to specify the sorting direction, or specify null to take the default sorting direction (ascending). For example: {name: "asc"} . By default, the items are sorted by the last updated date. |
Output
Type | Description |
---|---|
PNFuture<GetRestrictionsResponse> | PNFuture containing the GetRestrictionsResponse object with these properties: restrictions , next , prev , total , and status . |
Basic usage
List all mute
and ban
restrictions set for the user support_agent_15
.
// reference the "chat" object and invoke the "getUser()" method
chat.getUser("support_agent_15").async { result ->
result.onSuccess { user ->
if (user != null) {
// fetch the channel restrictions for the user
user.getChannelsRestrictions().async { restrictionsResult ->
restrictionsResult.onSuccess { getRestrictionsResponse ->
// process the returned restrictions
for (restriction in getRestrictionsResponse.restrictions) {
if (restriction.mute || restriction.ban) {
// handle the restriction object (either muted or banned)
println("User is restricted on channel ${restriction.channelId}: mute=${restriction.mute}, ban=${restriction.ban}")
}
}
}.onFailure {
show all 27 linesAll users on one channel
Check if there are any mute
or ban
restrictions set for user of a given channel using the getUsersRestrictions()
method.
Method signature
This method takes the following parameters:
channel.getUsersRestrictions(
limit: Int?,
page: PNPage?,
sort: Collection<PNSortKey<PNMemberKey>> = listOf(),
): PNFuture<GetRestrictionsResponse>
Input
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
limit | Int | No | 100 | Number of objects to return in response. The default (and maximum) value is 100 . |
page | PNPage | No | n/a | Object used for pagination to define which previous or next result page you want to fetch. |
sort | Collection<PNSortKey<PNMemberKey>> | No | listOf() | Key-value pair of a property to sort by, and a sort direction. Available options are id , name , and updated . Use asc or desc to specify the sorting direction, or specify null to take the default sorting direction (ascending). For example: {name: "asc"} . By default, the items are sorted by the last updated date. |
Output
Type | Description |
---|---|
PNFuture<GetRestrictionsResponse> | PNFuture containing the GetRestrictionsResponse object with these properties: restrictions , next , prev , total , and status . |
Basic usage
List all mute
and ban
restrictions set for the support
channel.
// reference the "chat" object and invoke the "getChannel()" method
chat.getChannel("support").async { result ->
result.onSuccess { channel ->
if (channel != null) {
// fetch the user restrictions for the channel
channel.getUsersRestrictions().async { restrictionsResult ->
restrictionsResult.onSuccess { getRestrictionsResponse ->
// process the returned restrictions
for (restriction in getRestrictionsResponse.restrictions) {
if (restriction.mute || restriction.ban) {
// handle the restriction object (either muted or banned)
println("User ${restriction.userId} is restricted in channel ${channel.id}: mute=${restriction.mute}, ban=${restriction.ban}")
}
}
}.onFailure {
show all 27 linesSecure moderation
You could try to use only the banning or muting restrictions on client devices and enforce some UI moderation, like not displaying channels for users who are banned from them, or not displaying input field for users who are muted on a given channel so that they couldn't post a message.
Still, such solely client-side restrictions can easily be bypassed if not secured with an additional server-side logic that uses Access Manager to allow or block user's access to PubNub resources (channels and users). This server-side can also be followed by additional client-side errors that inform app users about their restrictions up front.
Server-side restrictions
It's recommended to use Access Manager alongside the Chat SDK methods and grant or revoke permissions from users based on their muting or banning restrictions.
For example, you could have a UI moderation dashboard (like Channel Monitor) where admins set restrictions on users by muting or banning them from specific channels. After that, you can use one of the Chat SDK methods to get moderation restrictions for users and, based on results, call the Access Manager API to either generate or revoke grant tokens for PubNub resources (channels or users).
Let's look at sample steps that use Chat SDK methods to configure a chat app, set up server permissions, listen to any permission changes in Channel Monitor UI, and invoke access grant or revoke request on the server side.
-
Enable Access Manager.
Navigate to your app's keyset in the Admin Portal and turn on the ACCESS MANAGER option.
-
Secure backend initialization.
On the backend, initialize the Chat SDK with the secret key
secretKey
on your servers to secure your PubNub instance.Secret key
secretKey
is a secret shared between your application's server and PubNub and it's used to administer Access Manager permissions for your client applications by signing and verifying the authenticity of messages and requests. Remember to never expose thesecretKey
to client devices.
show all 25 linesval serverId = "auth-server"
var token: String
val clientUserIdValue = "clientUserId"
// ...
Chat.init(ChatConfiguration(), PNConfiguration.builder(UserId(serverId), subscribeKey = "your-subscribe-key-from-admin-portal") {
publishKey = "your-publish-key-from-admin-portal"
secretKey = "your-secret-key-from-admin-portal"
}.build()).async {
it.onSuccess { chat ->
chat.pubNub.grantToken(
ttl = 1,
channels = listOf(ChannelGrant.name(get = true, name = "anyChannelForNow")),
uuids = listOf(UUIDGrant.id(id = clientUserIdValue, get = true, update = true)) // this is important
).async { grantTokenResult -> -
Initialize Chat SDK with
token
.On the frontend of your app, initialize the Chat SDK (
init()
) with the token (generated by server-side code). Use it for all requests made to PubNub APIs to authenticate users in your application and grant them access to PubNub resources (other users' metadata and channels).val userId = "your-user-id"
val token = "token-generated-by-server-side"
// ...
Chat.init(ChatConfiguration(), PNConfiguration.builder(UserId(userId), subscribeKey = "your-subscribe-key-from-admin-portal") {
publishKey = "your-publish-key-from-admin-portal"
authToken = token
}.build()).async {
it.onSuccess { chat ->
// ...
}.onFailure {
// unable to initialize Chat
}
} -
Get user permissions.
Retrieve detailed user restrictions and convert these details into a simplified permission format where each channel is marked with whether the user can read, write, or access it, based on such restrictions as bans or mutes.
show all 24 linesval userId: String
// ...
// Retrieve user information and channel restrictions
chat.getUser(userId).async {
it.onSuccess { user ->
user?.getChannelsRestrictions()?.async {
it.onSuccess { restrictionsResponse ->
val grants = restrictionsResponse.restrictions.map { restriction ->
ChannelGrant.name(restriction.channelId,
read = !restriction.ban,
write = (!restriction.mute && !restriction.ban),
get = true,
)
} -
Generate authorization token.
Generate and assign an access token reflecting the user's permissions.
The token contains information about which channels the user can access and how (read/write), and it's configured with a specific validity period. This token serves as a key for users to interact with the application according to their permissions.
Operation-to-permission mapping
Read the Permissions document for a complete list of available operations that users can do with PubNub resources in apps created with the Chat SDK.
val restrictionGrants: List<ChannelGrant>
// ...
// Set up parameters for the authorization token
chat.pubNub.grantToken(ttl = 43200, authorizedUUID = userId, channels =
listOf(
ChannelGrant.pattern(".*", get = true, read = true, write = true),
) + restrictionGrants,
uuids = listOf(
UUIDGrant.id(userId, get = true, update = true)
)
)Set short TTLs
You can mute or ban a user for an indefinite amount of time, but you can unmute/unban them at any time. To make sure that the permissions set with Access Manager reflect the most up-to-date muting/banning restrictions on the client-side, it's recommended to set short-lived tokens (TTLs) for grant calls (valid for seconds and minutes rather than hours or days). Alternatively, if new muting/banning restrictions are set on the frontend side of your app, you can revoke Access Manager permissions on the backend using the
chat.sdk.revokeToken()
method. -
Listen for moderation events.
Set up a listener to listen for the
moderation
event type ("banned," "muted," or "lifted") generated when UI restrictions are added or removed.val handleModerationEvent : (event: Event<EventContent.Moderation>) -> Unit
// ...
val unsubscribe = chat.listenForEvents(
channelId = chat.currentUser.id,
callback = handleModerationEvent
)
// ...
// Remove the moderation event listener on cleanup
unsubscribe.close() -
Act on moderation events.
Update permissions in response to moderation events and generate new tokens if necessary.
show all 33 linesfun handleModerationEvent(event: Event<EventContent.Moderation>) {
val restriction = event.payload.restriction
val channelId = event.payload.channelId
val reason = event.payload.reason
// Handle different moderation events
when (restriction) {
RestrictionType.BAN -> {
// Revoke specific permissions for banning
println("User ${chat.currentUser.id} is banned on channel ${channelId}. Reason: ${reason ?: "N/A"}");
// Revoke access rights specific to banning logic here
// For example, you might remove write access
} -
Remove the event listener.
// remember to call close when you're done
unsubscribe.close()
Client-side restrictions
Once you enable and define server-side permissions with Access Manager, you can be sure that your muting and banning restrictions are always enforced.
Additionally, you can read moderation restrictions set with the Chat SDK methods also on your app's frontend to let a given user know upfront that they are muted on a channel or banned from accessing a channel using popup messages, iconography, etc. For example, before a user tries to write a message on a channel where they are muted and tries to search for the input field that is either greyed out or unavailable, you can display a popup message informing them about the restriction.
Listen to moderation
events
As an admin of your chat app, you can use the listenForEvents()
method to send notifications to the affected user when you mute or ban them on a channel, or to remove user channel membership each time they are banned.
Events documentation
To read more about the events of type moderation
, refer to the Chat events documentation.
Method signature
This method has the following parameters:
fun <reified T : EventContent> listenForEvents(
channel: String,
customMethod: EmitEventMethod?,
noinline callback: (event: Event<T>) -> Unit
): AutoCloseable
Input
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
T | reified T : EventContent | Yes | n/a | Reified type parameter bounded by the EventContent interface, allowing access to type information at runtime. |
channel | String | Yes | n/a | Channel to listen for new moderation events. It can be either the user's channel (ID of the moderated user) or any other channel, depending where you want to send moderation events. |
customMethod | String | No | n/a | An optional custom method for emitting events. If not provided, defaults to null . |
callback | noinline (event: Event<T>) -> Unit | Yes | n/a | A lambda function that is called with an Event<T> as its parameter. It defines the custom behavior to be executed whenever an moderation event type is detected on the specified channel. |
Output
Type | Description |
---|---|
AutoCloseable | Interface that lets you stop receiving moderation-related updates (moderation events) by invoking the close() method. |
Basic usage
Send a moderation
event to the muted user.
chat.listenForEvents(channelId = "support") { event: Event<EventContent.Moderation> ->
if (event.payload.restriction == RestrictionType.MUTE) {
println("You were muted on channel ${event.payload.channelId}")
}
}