@@ -56,37 +56,30 @@ export async function getUID(
5656) : Promise < string > {
5757 let uid = getCookie ( "uid" , { req, res } ) ;
5858 if ( uid && typeof uid === "string" ) {
59- // uids can be anonymous, so we need to check if the user exists
60-
61- const [ user ] = await db
62- . select ( )
63- . from ( schema . users )
64- . where ( eq ( schema . users . id , uid ) )
65- . limit ( 1 ) ;
66-
67- if ( user ) {
68- // user exists, so we check if the user is authenticated
69- // verify that the user has a stored token
70- let token = getCookie ( "token" , { req, res } ) ;
71- if ( ! token ) {
72- res . status ( 400 ) ;
73- throw new Error ( "User is not authenticated (1)" ) ;
74- }
75- // verify that the token is valid
76- const { valid, userId } = verifyToken (
77- token as string ,
78- user . cookie_secret ,
79- ) ;
80- if ( ! valid || userId !== uid ) {
81- res . status ( 400 ) ;
82- throw new Error ( `User is not authenticated (valid token: ${ valid } )` ) ;
59+ // Only authenticated users (those with a token cookie) need a DB lookup.
60+ // Anonymous users will never be in the users table, so skip the query.
61+ const token = getCookie ( "token" , { req, res } ) ;
62+ if ( token ) {
63+ const [ user ] = await db
64+ . select ( )
65+ . from ( schema . users )
66+ . where ( eq ( schema . users . id , uid ) )
67+ . limit ( 1 ) ;
68+
69+ if ( user ) {
70+ const { valid, userId } = verifyToken (
71+ token as string ,
72+ user . cookie_secret ,
73+ ) ;
74+ if ( ! valid || userId !== uid ) {
75+ res . status ( 400 ) ;
76+ throw new Error ( `User is not authenticated (valid token: ${ valid } )` ) ;
77+ }
8378 }
8479 }
85- // everything is ok, so we return the uid
8680 return uid as string ;
8781 } else {
8882 console . log ( "Generating new UID..." ) ;
89- // no uid, so we create an anonymous one
9083 uid = crypto . randomBytes ( 16 ) . toString ( "hex" ) ;
9184 setCookie ( "uid" , uid , {
9285 req,
0 commit comments