Skip to content

Commit

Permalink
connect to nats with client token
Browse files Browse the repository at this point in the history
  • Loading branch information
swelborn committed Jan 17, 2025
1 parent 4dffa72 commit a3ca753
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
22 changes: 22 additions & 0 deletions frontend/interactEM/src/client/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Auth, Client } from "@hey-api/client-axios"

export const getTokenFromClient = async (
client: Client,
): Promise<string | undefined> => {
const auth = client.getConfig().auth

if (!auth) {
return undefined
}

if (typeof auth === "string") {
return auth
}

const defaultAuth: Auth = {
type: "http",
scheme: "bearer",
}

return await auth(defaultAuth)
}
23 changes: 22 additions & 1 deletion frontend/interactEM/src/nats/NatsContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
} from "@nats-io/jetstream"
import { Kvm } from "@nats-io/kv"
import config from "../config"
import { client } from "../client"
import { getTokenFromClient } from "../client/utils"

interface NatsContextType {
natsConnection: NatsConnection | null
Expand All @@ -20,6 +22,15 @@ interface NatsContextType {

const NatsContext = createContext<NatsContextType | undefined>(undefined)

const getConnectionId = () => {
let id = sessionStorage.getItem("interactEM-connection-id")
if (!id) {
id = `interactEM-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`
sessionStorage.setItem("interactEM-connection-id", id)
}
return id
}

export const useNats = (): NatsContextType => {
const context = useContext(NatsContext)
if (!context) {
Expand All @@ -45,7 +56,17 @@ export const NatsProvider: React.FC<{ children: React.ReactNode }> = ({
useEffect(() => {
const setupNatsConnection = async () => {
try {
const nc = await wsconnect({ servers: [config.NATS_SERVER_URL] })
const token = await getTokenFromClient(client)
if (!token) {
console.error("Failed to get token from client")
return
}
console.log("Connecting to NATS with token:", token)
const nc = await wsconnect({
servers: [config.NATS_SERVER_URL],
name: getConnectionId(),
token: token,
})
setNatsConnection(nc)
setIsConnected(true)

Expand Down

0 comments on commit a3ca753

Please sign in to comment.