import { respondWithAuthenticatedUser } from '../../auth/meJson.js'; import * as db from '../../../db/googleAuth.js'; import { toPictureBuffer } from '../../../util/pictureBinary.js'; /** * Registers the current-user route (requires prior auth middleware populating `req.user`). * @param {import('express').Application} app - Express app * @param {string} [basePath=''] - Optional URL prefix for all routes in this module */ export function register(app, basePath = '') { /** * @openapi * /auth/me: * get: * tags: [Auth] * summary: Current user * description: | * Returns the authenticated user from the session cookie and the Google client ID. * `user.picture` is the stored profile image as a base64 string when present. * Unauthenticated calls still receive `googleClientId` with 401. * security: * - cookieAuth: [] * x-markdown: auth/me.md * responses: * 200: * description: Authenticated * content: * application/json: * schema: * type: object * properties: * user: * $ref: '#/components/schemas/User' * googleClientId: * type: string * 401: * description: Unauthorized — still includes `googleClientId` for the frontend * content: * application/json: * schema: * type: object * properties: * error: * type: string * googleClientId: * type: string */ app.get(`${basePath}/auth/me`, async (req, res) => { try { const row = await db.getById(req.user.id); if (!row) { return respondWithAuthenticatedUser(res, 403, { error: 'User is no longer authorized' }); } const pictureBinary = toPictureBuffer(row.pictureBinary); const user = { id: row.id, email: row.email, selectedCompanyId: row.selectedCompanyId, ...(pictureBinary && { picture: pictureBinary.toString('base64') }), }; respondWithAuthenticatedUser(res, 200, { user }); } catch (error) { console.error('Get current user failed:', error); respondWithAuthenticatedUser(res, 500, { error: 'Failed to load user' }); } }); }