Skip to content

Commit

Permalink
refactor: url and email validation (#335)
Browse files Browse the repository at this point in the history
* refactor: starter-kitty usage

* fix: install starter-kitty from public registry
  • Loading branch information
zeyu2001 authored Sep 27, 2024
1 parent 396cd00 commit e328168
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 31 deletions.
27 changes: 20 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"@hookform/resolvers": "^3.3.4",
"@opengovsg/design-system-react": "^1.15.0",
"@opengovsg/sgid-client": "^2.2.0",
"@opengovsg/starter-kitty-validators": "^1.0.1",
"@opengovsg/starter-kitty-validators": "^1.2.5",
"@paralleldrive/cuid2": "^2.2.2",
"@prisma/client": "^5.7.1",
"@sendgrid/mail": "^8.1.3",
Expand Down
34 changes: 12 additions & 22 deletions src/schemas/url.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,21 @@
import { z } from 'zod'
import { HOME } from '~/lib/routes'
import { UrlValidator } from '@opengovsg/starter-kitty-validators'
import { createUrlSchema } from '@opengovsg/starter-kitty-validators/url'
import { getBaseUrl } from '~/utils/getBaseUrl'

const baseUrl = getBaseUrl()

const validator = new UrlValidator({
baseOrigin: new URL(baseUrl).origin,
whitelist: {
protocols: ['http', 'https'],
hosts: [new URL(baseUrl).host],
},
})
const baseUrl = new URL(getBaseUrl())

export const callbackUrlSchema = z
.string()
.optional()
.default(HOME)
.transform((url, ctx) => {
try {
return validator.parse(url)
} catch (error) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: (error as Error).message,
})
return z.NEVER
}
})
.catch(new URL(HOME, baseUrl))
.pipe(
createUrlSchema({
baseOrigin: baseUrl.origin,
whitelist: {
protocols: ['http', 'https'],
hosts: [baseUrl.host],
},
}),
)
.catch(new URL(HOME, baseUrl.origin))
9 changes: 8 additions & 1 deletion src/utils/email.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { createEmailSchema } from '@opengovsg/starter-kitty-validators/email'
import isEmail from 'validator/lib/isEmail'

const emailSchema = createEmailSchema({
domains: [{ domain: 'gov.sg', includeSubdomains: true }],
})

export const getEmailDomain = (email?: string) => {
if (!email) {
return undefined
Expand All @@ -15,6 +20,8 @@ export const getEmailDomain = (email?: string) => {
*/
export const isGovEmail = (value: unknown) => {
return (
typeof value === 'string' && isEmail(value) && value.endsWith('.gov.sg')
typeof value === 'string' &&
isEmail(value) &&
emailSchema.safeParse(value).success
)
}

0 comments on commit e328168

Please sign in to comment.