-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(authorizer): added authorization
- Loading branch information
1 parent
4317290
commit 292ccc9
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
const aws = require('aws-sdk'); | ||
|
||
const dynamoDB = new aws.DynamoDB.DocumentClient(); | ||
|
||
function generatePolicy(principalId, effect, resource) { | ||
const policy = { | ||
principalId, | ||
policyDocument: { | ||
Version: '2012-10-17', | ||
Statement: [{ | ||
Action: 'execute-api:Invoke', | ||
Effect: effect, | ||
Resource: resource | ||
}] | ||
} | ||
}; | ||
return policy; | ||
} | ||
|
||
async function validateToken(userToken) { | ||
const token = userToken.split('Bearer ')[1]; | ||
const params = { | ||
TableName: process.env.dynamodb_table_name, | ||
IndexName: process.env.dynamodb_index_name, | ||
KeyConditionExpression: '#token = :token', | ||
ExpressionAttributeNames: { | ||
'#token': 'bearer_token' | ||
}, | ||
ExpressionAttributeValues: { | ||
':token': token | ||
} | ||
}; | ||
const data = await dynamoDB.query(params).promise(); | ||
return data.Items[0]; | ||
} | ||
|
||
exports.handler = async (event) => { // eslint-disable-line no-unused-vars | ||
const userToken = event.authorizationToken; | ||
const arn = event.methodArn; | ||
const user = await validateToken(userToken); | ||
if (user) { | ||
return generatePolicy('user', 'Allow', arn); | ||
} else { // eslint-disable-line no-else-return | ||
return generatePolicy('user', 'Deny', arn); | ||
} | ||
}; |