1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-22 19:07:54 +01:00

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.
This commit is contained in:
Nuno Góis 2023-10-17 09:18:44 +01:00 committed by GitHub
parent 5619db33ed
commit fd580c9539
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 1 deletions

View File

@ -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');
});
});

View File

@ -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 {