Skip to content

Commit

Permalink
+ handle jwt expiration within application
Browse files Browse the repository at this point in the history
  • Loading branch information
palkan committed Oct 25, 2023
1 parent 4d331ee commit b9de5af
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
22 changes: 17 additions & 5 deletions src/application/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,24 @@ export class Application<IdentifiersType extends IdentifiersMap = {}> {
}

async handleOpen(handle: ConnectionHandle<IdentifiersType>) {
await this.connect(handle)
try {
await this.connect(handle)

if (handle.rejected) {
handle.transmit({ type: 'disconnect', reason: 'unauthorized' })
} else {
handle.transmit({ type: 'welcome', sid: handle.id })
if (handle.rejected) {
handle.transmit({ type: 'disconnect', reason: 'unauthorized' })
} else {
handle.transmit({ type: 'welcome', sid: handle.id })
}
} catch (e) {
if ((e as any)?.code == 'ERR_JWT_EXPIRED') {
handle.reject().transmit({
type: 'disconnect',
reason: 'token_expired',
reconnect: false
})
} else {
throw e
}
}
}

Expand Down
25 changes: 25 additions & 0 deletions tests/application.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { errors } from 'jose'
import {
Application,
ConnectionHandle,
Expand Down Expand Up @@ -59,6 +60,30 @@ ApplicationTest('handleOpen when unauthorized', async () => {
])
})

ApplicationTest('handleOpen when token expired', async () => {
const app = new TestApplication()

const handle = new ConnectionHandle<TestIdentifiers>('123', {
url: 'http://localhost?user_id=1&token=expired'
})

app.connect = async (handle: ConnectionHandle<TestIdentifiers>) => {
throw new errors.JWTExpired('expired')
}

await app.handleOpen(handle)

assert.is(handle.rejected, true)
assert.is(handle.transmissions.length, 1)

const transmission = JSON.parse(handle.transmissions[0])
assert.equal(transmission, {
type: 'disconnect',
reason: 'token_expired',
reconnect: false
})
})

ApplicationTest('handleClose', async () => {
const app = new TestApplication()

Expand Down

0 comments on commit b9de5af

Please sign in to comment.