habits.andr33v.ru/server/api/auth/me.get.ts

40 lines
1.1 KiB
TypeScript

import { getUserIdFromSession } from '../../utils/auth';
export default defineEventHandler(async (event) => {
// 1. Get user ID from session; this helper handles the 401 check.
const userId = await getUserIdFromSession(event);
// 2. Fetch the full user from the database
const user = await prisma.user.findUnique({
where: { id: userId },
});
if (!user) {
// This case might happen if the user was deleted but the session still exists.
// The helper can't handle this, so we clear the session here.
const session = await useSession(event, { password: process.env.SESSION_PASSWORD });
await session.clear();
throw createError({
statusCode: 401,
statusMessage: 'Unauthorized: User not found.',
});
}
// 3. Return user data DTO
return {
user: {
id: user.id,
email: user.email,
nickname: user.nickname,
avatar: user.avatar,
coins: user.coins,
exp: user.exp,
dailyStreak: user.dailyStreak,
soundOn: user.soundOn,
confettiOn: user.confettiOn,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
}
};
});