From 21b800f4312cc5594d414ac32cdce4e7607b89db Mon Sep 17 00:00:00 2001 From: Douglas Barone Date: Fri, 15 Dec 2023 16:02:47 -0400 Subject: [PATCH] Update password functionality and error handling --- src/server/lib/updatePassword.ts | 5 +++- src/server/trpc.ts | 39 ++++++++++++++++++++++---------- 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/src/server/lib/updatePassword.ts b/src/server/lib/updatePassword.ts index bd02bdd..e2f89e5 100644 --- a/src/server/lib/updatePassword.ts +++ b/src/server/lib/updatePassword.ts @@ -37,7 +37,7 @@ export async function updatePassword({ username: string password: string newPassword: string -}) { +}): Promise<'SUCCESS' | 'FAIL'> { try { const userDN = await getUserDN(username) await ldapClient.bind(userDN, password) @@ -58,9 +58,12 @@ export async function updatePassword({ }) }) ]) + + return 'SUCCESS' } catch (err) { console.error(err) } finally { await ldapClient.unbind() } + return 'FAIL' } diff --git a/src/server/trpc.ts b/src/server/trpc.ts index 7e58bc6..12e25a5 100644 --- a/src/server/trpc.ts +++ b/src/server/trpc.ts @@ -1,29 +1,44 @@ -import { initTRPC, TRPCError } from "@trpc/server"; -import * as trpcExpress from "@trpc/server/adapters/express"; +import { initTRPC, TRPCError } from '@trpc/server' +import * as trpcExpress from '@trpc/server/adapters/express' -import { z } from "zod"; +import { z } from 'zod' +import { updatePassword } from './lib/updatePassword' -export const { procedure, router } = initTRPC.create(); +export const { procedure, router } = initTRPC.create() -const { query, mutation, input } = procedure; +const { query, input } = procedure export const appRouter = router({ hello: query(async () => { - return "Hello World!"; + return 'Hello World!' }), updatePassword: input( z.object({ username: z.string(), password: z.string(), - newPassword: z.string().min(8), + newPassword: z.string().min(8) }) - ).mutation(async () => {}), -}); + ).mutation(async ({ input }) => { + const { username, password, newPassword } = input + try { + await updatePassword({ + username, + password, + newPassword + }) + } catch (err: any) { + throw new TRPCError({ + code: 'BAD_REQUEST', + message: err.message + }) + } + }) +}) // export type definition of API -export type AppRouter = typeof appRouter; +export type AppRouter = typeof appRouter export const trpcMiddleware = trpcExpress.createExpressMiddleware({ - router: appRouter, -}); + router: appRouter +})