@@ -96,10 +96,6 @@ async function verifyWebsiteAccess(
9696 ctx : AuthContext ,
9797 websiteId : string
9898) : Promise < boolean > {
99- if ( ! ctx . isAuthenticated ) {
100- return false ;
101- }
102-
10399 const website = await db . query . websites . findFirst ( {
104100 where : eq ( websites . id , websiteId ) ,
105101 columns : {
@@ -118,6 +114,10 @@ async function verifyWebsiteAccess(
118114 return true ;
119115 }
120116
117+ if ( ! ctx . isAuthenticated ) {
118+ return false ;
119+ }
120+
121121 if ( ctx . apiKey ) {
122122 if ( hasGlobalAccess ( ctx . apiKey ) ) {
123123 if ( ctx . apiKey . organizationId ) {
@@ -276,22 +276,27 @@ export const query = new Elysia({ prefix: "/v1/query" })
276276 query : { website_id ?: string ; timezone ?: string } ;
277277 auth : AuthContext ;
278278 } ) => {
279- if ( ! ctx . isAuthenticated ) {
280- return AUTH_FAILED ;
281- }
282-
279+ // Check website access first (handles public websites)
283280 if ( q . website_id ) {
284281 const hasAccess = await verifyWebsiteAccess ( ctx , q . website_id ) ;
285282 if ( ! hasAccess ) {
286283 return new Response (
287284 JSON . stringify ( {
288285 success : false ,
289- error : "Access denied to this website" ,
290- code : "ACCESS_DENIED" ,
286+ error : ctx . isAuthenticated
287+ ? "Access denied to this website"
288+ : "Authentication required" ,
289+ code : ctx . isAuthenticated ? "ACCESS_DENIED" : "AUTH_REQUIRED" ,
291290 } ) ,
292- { status : 403 , headers : { "Content-Type" : "application/json" } }
291+ {
292+ status : ctx . isAuthenticated ? 403 : 401 ,
293+ headers : { "Content-Type" : "application/json" } ,
294+ }
293295 ) ;
294296 }
297+ } else if ( ! ctx . isAuthenticated ) {
298+ // No website_id and not authenticated
299+ return AUTH_FAILED ;
295300 }
296301
297302 try {
@@ -324,19 +329,21 @@ export const query = new Elysia({ prefix: "/v1/query" })
324329 auth : AuthContext ;
325330 } ) =>
326331 record ( "executeQuery" , async ( ) => {
327- if ( ! ctx . isAuthenticated ) {
328- return AUTH_FAILED ;
329- }
330-
332+ // Check website access first (handles public websites)
331333 if ( q . website_id ) {
332334 const hasAccess = await verifyWebsiteAccess ( ctx , q . website_id ) ;
333335 if ( ! hasAccess ) {
334336 return {
335337 success : false ,
336- error : "Access denied to this website" ,
337- code : "ACCESS_DENIED" ,
338+ error : ctx . isAuthenticated
339+ ? "Access denied to this website"
340+ : "Authentication required" ,
341+ code : ctx . isAuthenticated ? "ACCESS_DENIED" : "AUTH_REQUIRED" ,
338342 } ;
339343 }
344+ } else if ( ! ctx . isAuthenticated ) {
345+ // No website_id and not authenticated
346+ return AUTH_FAILED ;
340347 }
341348
342349 const tz = q . timezone || "UTC" ;
0 commit comments