Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nachoab/5088e1ea8877028dae05c5b3911ef389 to your computer and use it in GitHub Desktop.
Save nachoab/5088e1ea8877028dae05c5b3911ef389 to your computer and use it in GitHub Desktop.
<!--
TO USE THIS client:
- Go to the google developer console and get your client id. This is pretty
well documented somewhere else. Use your localhost(:port)? as url to work in
your local as always.
- Go to AWS and create a new Federated identity pool
* Associate an Authenticated role and Unauthenticated role to the pool
At least you need cognito-identity and apigateway, edit this for your needs
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cognito-identity:*",
"cognito-sync:*"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"apigateway:*"
],
"Resource": [
"*"
]
}
]
}
- Create your lambda functions with your api gateway endpoints
- Once you have deployed your app, go to the API gateway console and and edit
your methods and set Authorization to AWS_IAM (this is not supported
in sls yet: https://github.com/serverless/serverless/issues/2186)
- EXTRA: You will probably need a trigger when you sync datasets:
* Create your lambda function using sls
* Go to Cognito console, edit your pool and in "Cognito events" set your
sync trigger to that lambda
* In that lambda you can do whatever you want with the data synced
-->
<html>
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID">
<script src="bower_components/aws-sdk/dist/aws-sdk.js"></script>
<!--
Google oauth
https://developers.google.com/identity/sign-in/web/sign-in
-->
<script src="https://apis.google.com/js/platform.js" async defer></script>
<!--
Optional. If you want store data in cognito for your user
http://docs.aws.amazon.com/cognito/latest/developerguide/synchronizing-data.html
Get it form https://github.com/aws/amazon-cognito-js
-->
<script src="aws-sync-manager.js"></script>
<!--
This is a automatically generated SDK frmo the API Gateway console:
generate a SDK automatically for you. Go to the API Gateway
console -> your api -> stages -> pick stage -> SDK generation -> platform Javascript
-->
<script type="text/javascript" src="api_client/lib/axios/dist/axios.standalone.js"></script>
<script type="text/javascript" src="api_client/lib/CryptoJS/rollups/hmac-sha256.js"></script>
<script type="text/javascript" src="api_client/lib/CryptoJS/rollups/sha256.js"></script>
<script type="text/javascript" src="api_client/lib/CryptoJS/components/hmac.js"></script>
<script type="text/javascript" src="api_client/lib/CryptoJS/components/enc-base64.js"></script>
<script type="text/javascript" src="api_client/lib/url-template/url-template.js"></script>
<script type="text/javascript" src="api_client/lib/apiGatewayCore/sigV4Client.js"></script>
<script type="text/javascript" src="api_client/lib/apiGatewayCore/apiGatewayClient.js"></script>
<script type="text/javascript" src="api_client/lib/apiGatewayCore/simpleHttpClient.js"></script>
<script type="text/javascript" src="api_client/lib/apiGatewayCore/utils.js"></script>
<script type="text/javascript" src="api_client/apigClient.js"></script>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<a href="#" onclick="signOut();">Sign out</a>
<script>
var apigClient;
/**
* User has logged in to Google
*/
function onSignIn(googleUser) {
// Get the id_token
var profile = googleUser.getBasicProfile();
signinCallback(googleUser.getAuthResponse().id_token);
};
function signinCallback(id_token) {
AWS.config.region = 'eu-west-1';
// Add the Google access token to the Cognito credentials login map.
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'eu-west-1:fdb1f41f-2c07-437b-bec1-9f5afd482fcc',
// You can connect with any other oauth provider too
Logins: {
'accounts.google.com': id_token
}
});
// Obtain AWS credentials using the Goole id_token
// This will perform a request to your AWS cognito, validate the provided
// token and create the user associated if it doesn't exists
AWS.config.credentials.get(() => {
// could not login...
if (!AWS.config.credentials.accessKeyId) {
return;
}
// User logged in.
// Now you can do 2 things in order to perform request to your API Gateway:
//
// 1. you could generate the needed header tokens to each request. This
// is documented in AWS doc
//
// 2. AWS can generate a SDK automatically for you. Go to the API Gateway
// console -> your api -> stages -> pick stage -> SDK generation -> platform Javascript
//
// Here we are going to use the second for simplicity. (If you want to
// use 1, in the generated SDK is written the code needed to generated
// the headers)
// Also, dont forget to enable cors for your api endpoints !
apigClient = apigClientFactory.newClient({
accessKey: AWS.config.credentials.accessKeyId,
secretKey: AWS.config.credentials.secretAccessKey,
sessionToken: AWS.config.credentials.sessionToken,
region: AWS.config.region
});
// Now we can perform authenticated requests to our api using the
// apigClient:
//
// apigClient.myFuncGet().then(function(response) {
//
// });
// EXTRA: Now you might want to store data for your user in cognito.
// Each user can store few datasets.
// In the client, you can use the CognitoSyncManager.
var syncClient = new AWS.CognitoSyncManager();
// Create or open a new dataset called 'userinfo'
syncClient.openOrCreateDataset('userinfo', (err, dataset) => {
// Store new data.
// Here I want to store name, email and picture from the user.
//
// I could just send it from here:
// dataset.putAll({ name, email, picture })
// And then validate it using lambda triggers
//
// Instead I chose to send the id_token only.
// Then, associated with my pool I have a sync trigger that will
// receive this token, decode it and extract name, email and picture
// and fill the datastore.
dataset.putAll({ googleTokenId: id_token }, (err, record) => {
dataset.synchronize({
onSuccess: (data, newRecords) => {
console.log('synced', newRecords)
},
onFailure: () => {}
});
});
});
});
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
AWS.config.credentials.clearCachedId();
});
}
</script>
@mims92
Copy link

mims92 commented Jun 25, 2020

You saved my life!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment