fix: invalid user id will broken all userId info query problem

pull/220/head
moonrailgun 11 months ago
parent d79a62bf45
commit de63b312ad

@ -1,4 +1,4 @@
import { buildCachedRegFn, buildRegFn } from '../buildRegFn';
import { buildCachedRegFn, buildRegFn } from '../buildReg';
describe('buildRegFn should be ok', () => {
test('normal', () => {

@ -12,6 +12,7 @@ import _flatten from 'lodash/flatten';
import _zipObject from 'lodash/zipObject';
import { t } from '../i18n';
import type { UserBaseInfo } from 'tailchat-types';
import { isObjectId } from '../utils/string-helper';
export type { UserBaseInfo };
@ -288,6 +289,10 @@ export async function fetchUserInfo(userId: string): Promise<UserBaseInfo> {
return builtinUserInfo[userId]();
}
if (!isObjectId(userId)) {
throw new Error(`Invalid userId: ${userId}`);
}
const userInfo = await _fetchUserInfo(userId);
return userInfo;

@ -1,4 +1,4 @@
import { isAvailableString, isUrl } from '../string-helper';
import { isAvailableString, isObjectId, isUrl } from '../string-helper';
describe('string-helper', () => {
describe('isAvailableString', () => {
@ -28,4 +28,14 @@ describe('string-helper', () => {
expect(isUrl(url)).toBe(res);
});
});
describe('isObjectId', () => {
test.each<[string, boolean]>([
['1', false],
['unknown', false],
['64b4a473a44c273805b25da5', true],
])('%s => %p', (input, res) => {
expect(isObjectId(input)).toBe(res);
});
});
});

@ -55,3 +55,18 @@ export function isLocalMessageId(str: unknown): boolean {
return str.startsWith('localMessage_');
}
/**
* MongoDBobjectId
*/
export function isObjectId(str: any): boolean {
if (typeof str === 'string' && str.length === 12) {
return true;
}
if (typeof str === 'string' && /^[0-9A-Fa-f]{24}$/.test(str)) {
return true;
}
return false;
}

Loading…
Cancel
Save