From fd580c9539d0ba57f02e7c9b5bd1859b08773c5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nuno=20G=C3=B3is?= Date: Tue, 17 Oct 2023 09:18:44 +0100 Subject: [PATCH] fix: extract username from user should not return undefined (#5061) This fixes a return type error by changing the logic of `extractUsernameFromUser` to never return undefined. In the previous code, `user` could be truthy, but that doesn't mean `email` or `username` were defined. This assumes we always fallback to "unknown" in those scenarios. --- src/lib/util/extract-user.test.ts | 32 +++++++++++++++++++++++++++++++ src/lib/util/extract-user.ts | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 src/lib/util/extract-user.test.ts diff --git a/src/lib/util/extract-user.test.ts b/src/lib/util/extract-user.test.ts new file mode 100644 index 0000000000..85494876e1 --- /dev/null +++ b/src/lib/util/extract-user.test.ts @@ -0,0 +1,32 @@ +import { IUser } from '../server-impl'; +import { extractUsernameFromUser } from './extract-user'; + +describe('extractUsernameFromUser', () => { + test('Should return the email if it exists', () => { + const user = { + email: 'ratatoskr@yggdrasil.com', + username: 'ratatoskr', + } as IUser; + + expect(extractUsernameFromUser(user)).toBe(user.email); + }); + + test('Should return the username if it exists and email does not', () => { + const user = { + username: 'ratatoskr', + } as IUser; + + expect(extractUsernameFromUser(user)).toBe(user.username); + }); + + test('Should return "unknown" if neither email nor username exists', () => { + const user = {} as IUser; + + expect(extractUsernameFromUser(user)).toBe('unknown'); + }); + + test('Should return "unknown" if user is null', () => { + const user = null as unknown as IUser; + expect(extractUsernameFromUser(user)).toBe('unknown'); + }); +}); diff --git a/src/lib/util/extract-user.ts b/src/lib/util/extract-user.ts index 75f1e38089..84ba126ce5 100644 --- a/src/lib/util/extract-user.ts +++ b/src/lib/util/extract-user.ts @@ -1,7 +1,7 @@ import { IAuthRequest, IUser } from '../server-impl'; export function extractUsernameFromUser(user: IUser): string { - return user ? user.email || user.username : 'unknown'; + return user?.email || user?.username || 'unknown'; } export function extractUsername(req: IAuthRequest): string {