← back to Norma

app/api/auth/session/route.ts

51 lines

import { NextRequest, NextResponse } from 'next/server';
import { verifyAuth } from '@/lib/auth';
import { query } from '@/lib/db';

export async function GET(request: NextRequest) {
  const session = verifyAuth(request);

  if (session) {
    // Fetch full identity from tier_credentials so the UI never has to guess
    // who's logged in (header chrome, Gmail CRM, audit log, etc.)
    let displayName: string | null = null;
    let clientType:  string | null = null;
    let email:       string | null = null;
    try {
      const res = await query(
        'SELECT display_name, client_type FROM tier_credentials WHERE username = $1',
        [session.username],
      );
      if (res.rows.length > 0) {
        displayName = res.rows[0].display_name;
        clientType  = res.rows[0].client_type;
      }
    } catch {
      // Non-fatal — proceed without display name
    }

    // Infer email from the username when it's already an email-shaped string
    // (e.g. 'info@studentdebtcrisis.org') — tier_credentials has no email column.
    if (session.username.includes('@')) {
      email = session.username;
    }

    return NextResponse.json({
      authenticated: true,
      user: session.username,
      role: session.role,
      orgId: session.orgId,
      displayName,
      fullName: displayName,
      email,
      clientType,
      isInteriorDesigner: clientType === 'trade',
    });
  }

  // Guests get a 200 with authenticated:false so unauthenticated Pulse pages
  // can render normally without spamming red 401s in the browser console.
  // Clients should check `data.authenticated` rather than `res.ok`.
  return NextResponse.json({ authenticated: false });
}