pubnub / js-chat

PubNub JavaScript Chat SDK
https://github.com/pubnub/js-chat
8 stars 9 forks source link

Chat SDK + Access Manager #180

Open manfe opened 1 month ago

manfe commented 1 month ago

When Access Manager is enabled I am initializing the Chat SDK with:

const chatInstance = await Chat.init({
    publishKey: process.env.NEXT_PUBLIC_PUBNUB_PUBLISH_KEY,
    subscribeKey: process.env.NEXT_PUBLIC_PUBNUB_SUBSCRIBE_KEY,
    userId: "user-id-example",
    authKey: "my-token" // This authKey is the Access Manager authorized token
})

But if I need to update the access manager token after a period of time, I noticed that the pubnub is wrapped into the sdk property.

Is it ok to update the Access Manager token using the method below?

chatInstance.sdk.setToken("my-new-token")

Or there is other recommended way to do it?

Also if I need to listen 403 errors I continue listening on that sdk property?

piotr-suwala commented 1 month ago

Hello @manfe!

Yes, it's okay to update the Access Manager token using setToken on the sdk property. However we noticed that a stale value will be used in the setLastReadMessageTimetoken and we need to fix it soon. You should be good to go with setToken.

Regarding your second question: you can use code like this if you use React:

  useEffect(() => {
    if (!chat) {
      return
    }

    const listeners = {
      status(statusEvent: Pubnub.StatusEvent) {
        if (
          statusEvent.category === "PNNetworkDownCategory" ||
          statusEvent.category === "PNNetworkIssuesCategory" ||
          statusEvent.category === "PNConnectionErrorCategory"
        ) {
        }
        // do something
      },
    }

    chat.sdk.addListener(listeners)

    return () => {
      chat.sdk.removeListener(listeners)
    }
  }, [chat])
manfe commented 1 month ago

@piotr-suwala how are you able to import Pubnub only using "@pubnub/chat": "^0.8.2" ?

Because I am not seeing it exported.

piotr-suwala commented 1 month ago

You're right. This is not exported.

You can replace

status(statusEvent: Pubnub.StatusEvent)

with

status(statusEvent: { category: string })
manfe commented 1 month ago

@piotr-suwala another issue that I found.

If I have listeners to a channel or messages and the token is updated, those messages will keep the old token and while we don't stop listen and listen again (re-render all messages) with new listeners will not be able to toggle reaction on them or take any action with the stale token.

piotr-suwala commented 1 month ago

@manfe Did you use chatInstance.sdk.setToken("my-new-token") when your token is updated? Our PN Messages do not contain the AM token on their own.

manfe commented 1 month ago

@piotr-suwala yes, I was using this approach, but old messages couldn't have any kind o reaction.

So I had to initialize the chat again when a new token arrive.