From 8dc2be1eeed3f81759df577267c78a113285620e Mon Sep 17 00:00:00 2001 From: wangsijie Date: Fri, 11 Nov 2022 15:17:12 +0800 Subject: [PATCH] feat(core): revoke tokens when user is suspended (#2407) --- packages/core/src/queries/oidc-model-instance.ts | 8 ++++++++ packages/core/src/routes/admin-user.test.ts | 7 +++++++ packages/core/src/routes/admin-user.ts | 5 +++++ 3 files changed, 20 insertions(+) diff --git a/packages/core/src/queries/oidc-model-instance.ts b/packages/core/src/queries/oidc-model-instance.ts index d7dedfba6..a2c660309 100644 --- a/packages/core/src/queries/oidc-model-instance.ts +++ b/packages/core/src/queries/oidc-model-instance.ts @@ -108,3 +108,11 @@ export const revokeInstanceByGrantId = async (modelName: string, grantId: string and ${fields.payload}->>'grantId'=${grantId} `); }; + +export const revokeInstanceByUserId = async (modelName: string, userId: string) => { + await envSet.pool.query(sql` + delete from ${table} + where ${fields.modelName}=${modelName} + and ${fields.payload}->>'accountId'=${userId} + `); +}; diff --git a/packages/core/src/routes/admin-user.test.ts b/packages/core/src/routes/admin-user.test.ts index 833f1912a..b3ec18e03 100644 --- a/packages/core/src/routes/admin-user.test.ts +++ b/packages/core/src/routes/admin-user.test.ts @@ -80,6 +80,12 @@ jest.mock('@/queries/roles', () => ({ ), })); +const revokeInstanceByUserId = jest.fn(); +jest.mock('@/queries/oidc-model-instance', () => ({ + revokeInstanceByUserId: async (modelName: string, userId: string) => + revokeInstanceByUserId(modelName, userId), +})); + describe('adminUserRoutes', () => { const userRequest = createRequester({ authedRoutes: adminUserRoutes }); @@ -324,6 +330,7 @@ describe('adminUserRoutes', () => { .patch(`/users/${mockedUserId}/is-suspended`) .send({ isSuspended: true }); expect(updateUserById).toHaveBeenCalledWith(mockedUserId, { isSuspended: true }); + expect(revokeInstanceByUserId).toHaveBeenCalledWith('refreshToken', mockedUserId); expect(response.status).toEqual(200); expect(response.body).toEqual({ ...mockUserResponse, diff --git a/packages/core/src/routes/admin-user.ts b/packages/core/src/routes/admin-user.ts index 718a2aaa7..3ebc6eef5 100644 --- a/packages/core/src/routes/admin-user.ts +++ b/packages/core/src/routes/admin-user.ts @@ -9,6 +9,7 @@ import RequestError from '@/errors/RequestError'; import { encryptUserPassword, generateUserId, insertUser } from '@/lib/user'; import koaGuard from '@/middleware/koa-guard'; import koaPagination from '@/middleware/koa-pagination'; +import { revokeInstanceByUserId } from '@/queries/oidc-model-instance'; import { findRolesByRoleNames } from '@/queries/roles'; import { deleteUserById, @@ -260,6 +261,10 @@ export default function adminUserRoutes(router: T) { isSuspended, }); + if (isSuspended) { + await revokeInstanceByUserId('refreshToken', user.id); + } + ctx.body = pick(user, ...userInfoSelectFields); return next();