import { cookies } from 'next/headers'; import { NextResponse } from 'next/server'; import { api, ApiError, getTenant } from '../../../lib/meshkee/api'; import { ACCESS_COOKIE,REFRESH_COOKIE,setSessionCookies } from '../../../lib/meshkee/session'; type BusinessMembership={businessId?:number|string;id?:number|string;isOwner?:boolean;teamRole?:'admin'|'editor'|'viewer'|null}; type User={firstName?:string;lastName?:string;businesses?:BusinessMembership[];isSuperAdmin?:boolean;roles?:string[]}; const headers={'Cache-Control':'no-store'}; function hasWebsiteAccess(user:User, businessId:number|string){ if(user.isSuperAdmin||user.roles?.includes('super_admin'))return true; return user.businesses?.some(membership=> String(membership.businessId??membership.id)===String(businessId) && (membership.isOwner===true||membership.teamRole==='admin'||membership.teamRole==='editor'||membership.teamRole==='viewer') )??false; } export async function GET(request:Request){ const jar=await cookies();const token=jar.get(ACCESS_COOKIE)?.value;const refreshToken=jar.get(REFRESH_COOKIE)?.value; if(!token&&!refreshToken)return NextResponse.json({user:null},{headers}); let refreshed:{accessToken:string;refreshToken:string}|undefined; try{ let result:{user:User}; try{ if(!token)throw new ApiError(401); result=await api<{user:User}>('/auth/me',{headers:{Authorization:`Bearer ${token}`}}); }catch(error){ if(!(error instanceof ApiError)||error.status!==401||!refreshToken)throw error; refreshed=await api<{accessToken:string;refreshToken:string}>('/auth/refresh',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({refreshToken})}); if(!refreshed.accessToken||!refreshed.refreshToken)throw new Error('Invalid refresh response'); result=await api<{user:User}>('/auth/me',{headers:{Authorization:`Bearer ${refreshed.accessToken}`}}); } const tenant=await getTenant(); const response=NextResponse.json({user:{name:[result.user.firstName,result.user.lastName].filter(Boolean).join(' ')||'کاربر',isAdmin:hasWebsiteAccess(result.user,tenant.id)}},{headers}); if(refreshed)setSessionCookies(response,request,refreshed); return response; }catch(error){return NextResponse.json({user:null},{status:error instanceof ApiError&&error.status===401?401:503,headers})} }