2024-10-12 21:23:12 -04:00
|
|
|
import { Request, Response, NextFunction } from "express";
|
|
|
|
import { z } from "zod";
|
|
|
|
import { db } from "@server/db";
|
|
|
|
import { users } from "@server/db/schema";
|
|
|
|
import { eq } from "drizzle-orm";
|
2024-10-01 21:34:07 -04:00
|
|
|
import response from "@server/utils/response";
|
2024-10-12 21:23:12 -04:00
|
|
|
import HttpCode from "@server/types/HttpCode";
|
|
|
|
import createHttpError from "http-errors";
|
|
|
|
import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
|
|
|
|
import logger from "@server/logger";
|
2024-10-01 21:53:49 -04:00
|
|
|
|
2024-10-12 21:23:12 -04:00
|
|
|
export type GetUserResponse = {
|
|
|
|
email: string;
|
|
|
|
twoFactorEnabled: boolean;
|
|
|
|
emailVerified: boolean;
|
|
|
|
};
|
2024-10-01 21:34:07 -04:00
|
|
|
|
2024-10-12 21:23:12 -04:00
|
|
|
export async function getUser(
|
|
|
|
req: Request,
|
|
|
|
res: Response,
|
|
|
|
next: NextFunction,
|
|
|
|
): Promise<any> {
|
2024-10-06 18:05:20 -04:00
|
|
|
try {
|
2024-10-13 17:13:47 -04:00
|
|
|
const userId = req.user?.userId;
|
2024-10-12 21:23:12 -04:00
|
|
|
|
2024-10-06 18:43:20 -04:00
|
|
|
if (!userId) {
|
2024-10-12 21:23:12 -04:00
|
|
|
return next(
|
|
|
|
createHttpError(HttpCode.UNAUTHORIZED, "User not found"),
|
|
|
|
);
|
2024-10-06 18:05:20 -04:00
|
|
|
}
|
2024-10-01 21:53:49 -04:00
|
|
|
|
2024-10-12 21:23:12 -04:00
|
|
|
const user = await db
|
|
|
|
.select()
|
2024-10-06 18:05:20 -04:00
|
|
|
.from(users)
|
2024-10-13 17:13:47 -04:00
|
|
|
.where(eq(users.userId, userId))
|
2024-10-06 18:05:20 -04:00
|
|
|
.limit(1);
|
2024-10-01 21:53:49 -04:00
|
|
|
|
2024-10-06 18:05:20 -04:00
|
|
|
if (user.length === 0) {
|
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.NOT_FOUND,
|
2024-10-12 21:23:12 -04:00
|
|
|
`User with ID ${userId} not found`,
|
|
|
|
),
|
2024-10-06 18:05:20 -04:00
|
|
|
);
|
|
|
|
}
|
2024-10-01 21:53:49 -04:00
|
|
|
|
2024-10-12 21:23:12 -04:00
|
|
|
return response<GetUserResponse>(res, {
|
2024-10-06 18:43:20 -04:00
|
|
|
data: {
|
|
|
|
email: user[0].email,
|
|
|
|
twoFactorEnabled: user[0].twoFactorEnabled,
|
2024-10-12 21:23:12 -04:00
|
|
|
emailVerified: user[0].emailVerified,
|
2024-10-06 18:43:20 -04:00
|
|
|
},
|
2024-10-06 18:05:20 -04:00
|
|
|
success: true,
|
|
|
|
error: false,
|
|
|
|
message: "User retrieved successfully",
|
|
|
|
status: HttpCode.OK,
|
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
logger.error(error);
|
2024-10-12 21:23:12 -04:00
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.INTERNAL_SERVER_ERROR,
|
|
|
|
"An error occurred...",
|
|
|
|
),
|
|
|
|
);
|
2024-10-06 18:05:20 -04:00
|
|
|
}
|
2024-10-02 00:04:40 -04:00
|
|
|
}
|