Skip to content

Automatically Use Logged-In User ID in Amplify SQL Reference Queries/Mutations

0

Hello,

I am building a React Native app using AWS Amplify. I have several custom queries and mutations that reference SQL files using a.handler.sqlReference. Most of these operations require the logged-in user’s ID. Currently, I am passing the UserID manually from the frontend every time.

Here’s an example of a mutation from the Amplify doc(https://docs.amplify.aws/react/build-a-backend/data/connect-to-existing-data-sources/connect-postgres-mysql-database/):

const sqlSchema = generatedSqlSchema .authorization(allow => allow.guest()) .addToSchema({ createNewLocationWithLongLat: a.mutation() .arguments({ lat: a.float().required(), long: a.float().required(), name: a.string().required(), address: a.string().required() }) .returns(a.json().array()) .authorization(allow => allow.authenticated()) .handler(a.handler.sqlReference('./createNewLocationWithLongLat.sql')) });

SQL file:

INSERT INTO locations (name, address, geom) VALUES (:name, :address, ST_GEOMFROMTEXT(CONCAT('POINT (', :long, ' ', :lat, ')'), 4326));

I want to automatically use the logged-in user’s ID (ctx.identity.sub) in all my SQL reference queries/mutations without passing it manually from the frontend.

How can I modify these handlers so that UserID is always available in the SQL parameters?

Is there a best practice for making the logged-in user ID globally accessible in Amplify Gen 2 custom SQL queries and mutations?

Thank you!

1 Answer
-1

In AWS Amplify Gen 2, you can automatically access the logged-in user's ID in your SQL reference queries and mutations without manually passing it from the frontend. The user ID is available through the context object that's passed to your handler.

You can modify your SQL reference handlers to automatically include the user ID by accessing it from the context parameter. Here's how you can implement this:

  1. First, update your schema definition to include the context parameter in your handler:
const sqlSchema = generatedSqlSchema
.authorization(allow => allow.guest())
.addToSchema({
createNewLocationWithLongLat: a.mutation()
.arguments({
lat: a.float().required(),
long: a.float().required(),
name: a.string().required(),
address: a.string().required()
})
.returns(a.json().array())
.authorization(allow => allow.authenticated())
.handler(a.handler.sqlReference('./createNewLocationWithLongLat.sql', {
// This function will be called before executing the SQL
prepareParams: (params, context) => {
// Add the user ID from the context to the params
return {
...params,
userId: context.identity.sub
};
}
}))
});
  1. Then, update your SQL file to use the userId parameter:
INSERT INTO locations (name, address, geom, user_id)
VALUES (:name, :address, ST_GEOMFROMTEXT(CONCAT('POINT (', :long, ' ', :lat, ')'), 4326), :userId);

The prepareParams function allows you to modify the parameters that will be passed to your SQL query. It receives the original parameters from the request and the context object, which contains the authenticated user's information when using the .authorization(allow => allow.authenticated()) setting.

This approach ensures that the user ID is automatically available in all your SQL queries without having to pass it manually from the frontend. It also improves security by using the server-side authenticated identity rather than relying on client-provided user IDs.

For consistency across your application, you could create a helper function that wraps the SQL reference handler creation:

function createAuthenticatedSqlHandler(sqlFilePath) {
return a.handler.sqlReference(sqlFilePath, {
prepareParams: (params, context) => ({
...params,
userId: context.identity.sub
})
});
}

Then use it in your schema definitions:

.handler(createAuthenticatedSqlHandler('./createNewLocationWithLongLat.sql'))

This approach ensures that the user ID is consistently available across all your authenticated SQL operations.
Sources
How can I add all three alias attributes in AWS Cognito while setting up Amplify Gen2 Auth? | AWS re:Post
Building a Gen AI-Powered Manufacturing Search Engine with AWS Amplify Gen 2 | Front-End Web & Mobile

answered 4 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.