Skip to content

Commit

Permalink
feat: improve validators for captcha
Browse files Browse the repository at this point in the history
  • Loading branch information
darkskygit committed Mar 29, 2024
1 parent b9dfb8d commit 711632a
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import test from 'ava';

import { validators } from '../validators';

test('can validate', t => {
t.notThrows(() => validators.assertValidEmail('[email protected]'));
t.throws(() => validators.assertValidEmail('test@example'));
t.throws(() => validators.assertValidEmail('test'));

t.notThrows(() => validators.assertValidPassword('password'));
t.notThrows(() => validators.assertValidPassword('a'));
t.throws(() => validators.assertValidPassword(''));
t.throws(() => validators.assertValidPassword('aaaaaaaaaaaaaaaaaaaaa'));

t.notThrows(() =>
validators.assertValidCredential({
email: '[email protected]',
password: 'password',
})
);
t.notThrows(() =>
validators.assertValidCredential({
email: '[email protected]',
password: 'password',
challenge: 'challenge',
})
);
t.notThrows(() =>
validators.assertValidCredential({
email: '[email protected]',
password: 'password',
verifyToken: 'verifyToken',
})
);
// challenge and verifyToken should not be both provided
t.throws(() =>
validators.assertValidCredential({
email: '[email protected]',
password: 'password',
challenge: 'challenge',
verifyToken: 'verifyToken',
})
);
});
26 changes: 25 additions & 1 deletion packages/backend/server/src/core/utils/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,28 @@ function getAuthCredentialValidator() {
.required();
}

function getAuthCredentialWithCaptchaValidator() {
return getAuthCredentialValidator()
.extend({
verifyToken: z.string().optional(),
challenge: z.string().optional(),
})
.refine(
data => {
const hasChallenge = !!data.challenge;
const hasVerifyToken = !!data.verifyToken;
return (
(!hasChallenge && !hasVerifyToken) ||
(hasChallenge && !hasVerifyToken) ||
(!hasChallenge && hasVerifyToken)
);
},
{
message: 'verifyToken and challenge should not be both provided',
}
);
}

function assertValid<T>(z: z.ZodType<T>, value: unknown) {
const result = z.safeParse(value);

Expand All @@ -45,8 +67,10 @@ export function assertValidPassword(password: string) {
export function assertValidCredential(credential: {
email: string;
password: string;
challenge?: string;
verifyToken?: string;
}) {
assertValid(getAuthCredentialValidator(), credential);
assertValid(getAuthCredentialWithCaptchaValidator(), credential);
}

export const validators = {
Expand Down

0 comments on commit 711632a

Please sign in to comment.