mirror of
https://github.com/documenso/documenso.git
synced 2025-11-13 08:13:56 +10:00
refactor: extract api implementation to package
Extracts the API implementation to a package so we can potentially reuse it across different applications in the event that we move off using a Next.js API route. Additionally tidies up the tokens page and form to be more simplified.
This commit is contained in:
37
packages/api/v1/middleware/authenticated.ts
Normal file
37
packages/api/v1/middleware/authenticated.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import type { NextApiRequest } from 'next';
|
||||
|
||||
import { getUserByApiToken } from '@documenso/lib/server-only/public-api/get-user-by-token';
|
||||
import type { User } from '@documenso/prisma/client';
|
||||
|
||||
export const authenticatedMiddleware = <
|
||||
T extends {
|
||||
req: NextApiRequest;
|
||||
},
|
||||
R extends {
|
||||
status: number;
|
||||
body: unknown;
|
||||
},
|
||||
>(
|
||||
handler: (args: T, user: User) => Promise<R>,
|
||||
) => {
|
||||
return async (args: T) => {
|
||||
try {
|
||||
const { authorization: token } = args.req.headers;
|
||||
|
||||
if (!token) {
|
||||
throw new Error('Token was not provided for authenticated middleware');
|
||||
}
|
||||
|
||||
const user = await getUserByApiToken({ token });
|
||||
|
||||
return await handler(args, user);
|
||||
} catch (_err) {
|
||||
return {
|
||||
status: 401,
|
||||
body: {
|
||||
message: 'Unauthorized',
|
||||
},
|
||||
} as const;
|
||||
}
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user