refactor: centralize domain values and enforce numeric lint
This commit is contained in:
@@ -7,20 +7,26 @@ import {
|
||||
ValidatorConstraint,
|
||||
} from 'class-validator';
|
||||
|
||||
const MAX_EMAIL_LENGTH = 254;
|
||||
const ASCII_SPACE = 32;
|
||||
const ASCII_DELETE = 127;
|
||||
const MIN_PASSWORD_LENGTH = 12;
|
||||
const MAX_PASSWORD_BYTES = 72;
|
||||
|
||||
@ValidatorConstraint({ name: 'email' })
|
||||
class EmailConstraint {
|
||||
validate(value: unknown): boolean {
|
||||
return (
|
||||
typeof value === 'string' &&
|
||||
value.length <= 254 &&
|
||||
value.length <= MAX_EMAIL_LENGTH &&
|
||||
value.split('@').length === 2 &&
|
||||
!value
|
||||
.split('')
|
||||
.some(
|
||||
(character) =>
|
||||
/\s/.test(character) ||
|
||||
character.charCodeAt(0) < 32 ||
|
||||
character.charCodeAt(0) === 127,
|
||||
character.charCodeAt(0) < ASCII_SPACE ||
|
||||
character.charCodeAt(0) === ASCII_DELETE,
|
||||
) &&
|
||||
value.split('@').every(Boolean)
|
||||
);
|
||||
@@ -33,7 +39,10 @@ class EmailConstraint {
|
||||
@ValidatorConstraint({ name: 'passwordBytes' })
|
||||
class PasswordBytesConstraint {
|
||||
validate(value: unknown): boolean {
|
||||
return typeof value === 'string' && Buffer.byteLength(value, 'utf8') <= 72;
|
||||
return (
|
||||
typeof value === 'string' &&
|
||||
Buffer.byteLength(value, 'utf8') <= MAX_PASSWORD_BYTES
|
||||
);
|
||||
}
|
||||
defaultMessage(): string {
|
||||
return 'must not exceed 72 UTF-8 bytes';
|
||||
@@ -49,9 +58,13 @@ export class CredentialsDto {
|
||||
@Validate(EmailConstraint)
|
||||
declare email: string;
|
||||
|
||||
@ApiProperty({ minLength: 12, maxLength: 72, example: 'a secure password' })
|
||||
@ApiProperty({
|
||||
minLength: MIN_PASSWORD_LENGTH,
|
||||
maxLength: MAX_PASSWORD_BYTES,
|
||||
example: 'a secure password',
|
||||
})
|
||||
@IsString()
|
||||
@MinLength(12)
|
||||
@MinLength(MIN_PASSWORD_LENGTH)
|
||||
@Validate(PasswordBytesConstraint)
|
||||
declare password: string;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user