- Newest
- Most votes
- Most comments
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:
- 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 }; } })) });
- 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
Relevant content
- asked 5 months ago
- AWS OFFICIALUpdated 4 years ago
- AWS OFFICIALUpdated 4 years ago
