GithubHelp home page GithubHelp logo

amazon-archives / amazon-cognito-js Goto Github PK

View Code? Open in Web Editor NEW
202.0 31.0 83.0 105 KB

Amazon Cognito Sync Manager for JavaScript

Home Page: http://aws.amazon.com/cognito

License: Apache License 2.0

JavaScript 100.00%

amazon-cognito-js's Introduction

Amazon Cognito Sync Manager for JavaScript

Developer Preview: We welcome developer feedback on this project. You can reach us by creating an issue on the GitHub repository or post to the Amazon Cognito forums:

Introduction

The Cognito Sync Manager for JavaScript allows your web application to store data in the cloud for your users and synchronize across other devices. The library uses the browser's local storage API to create a local cache for the data, similar to our mobile SDK. This allows your web application to access stored data even when there is no connectivity.

Note: This library is designed to run in the browser. It has not been tested for use in other environments.

Setup

  1. Download and include the AWS JavaScript SDK:
  1. Download and include the Cognito Sync Manager for JavaScript:
  • <script src="/path/to/amazon-cognito.min.js"></script>
  • Or... import 'amazon-cognito-js';
  • Or... require('amazon-cognito-js');

For NPM usage refer to the following issue: NPM usage.

Usage

Step 1. Log into Amazon Cognito management console and create a new identity pool. Be sure to enable the "unauthenticated identities" option. On the last step of the wizard, make a note of your Account ID, Identity Pool ID, and Unauthenticated Role ARN.

Step 2. Instantiate the AWS JavaScript SDK using the AWS.CognitoIdentityCredentials class, using the information you gathered from the previous step.

AWS.config.region = 'us-east-1';

AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'YOUR IDENTITY POOL ID',
});

Step 3. Make the call to obtain the credentials you configured, and in the callback, instantiate the CognitoSyncManager class. It will assume the credentials from the AWS SDK.

AWS.config.credentials.get(function() {

    client = new AWS.CognitoSyncManager();

    // YOUR CODE HERE

});

Step 4. Now you need to open or create a new dataset to start saving data to. Call .openOrCreateDataset() and pass in the desired dataset name.

client.openOrCreateDataset('myDatasetName', function(err, dataset) {

   // Do something with the dataset here.

});

Step 5. Once you have the dataset object, you can write, read, and delete records to that dataset. It is also possible to get all the records from a given dataset, get the amount of data used by a dataset, and more.

<!-- Read Records -->
dataset.get('myRecord', function(err, value) {
  console.log('myRecord: ' + value);
});

<!-- Write Records -->
dataset.put('newRecord', 'newValue', function(err, record) {
  console.log(record);
});

<!-- Delete Records -->
dataset.remove('oldKey', function(err, record) {
  if (!err) { console.log('success'); }
});

Step 6. Finally, synchronize the data to Cognito. You pass the synchronize function an object with callbacks to handle the various outcomes: onSuccess, onFailure, onConflict, onDatasetsMerged, onDatasetDeleted.

<!-- Synchronize -->
dataset.synchronize({

  onSuccess: function(dataset, newRecords) {
     //...
  },

  onFailure: function(err) {
     //...
  },

  onConflict: function(dataset, conflicts, callback) {

     var resolved = [];

     for (var i=0; i<conflicts.length; i++) {

        // Take remote version.
        resolved.push(conflicts[i].resolveWithRemoteRecord());

        // Or... take local version.
        // resolved.push(conflicts[i].resolveWithLocalRecord());

        // Or... use custom logic.
        // var newValue = conflicts[i].getRemoteRecord().getValue() + conflicts[i].getLocalRecord().getValue();
        // resolved.push(conflicts[i].resolveWithValue(newValue);

     }

     dataset.resolve(resolved, function() {
        return callback(true);
     });

     // Or... callback false to stop the synchronization process.
     // return callback(false);

  },

  onDatasetDeleted: function(dataset, datasetName, callback) {

     // Return true to delete the local copy of the dataset.
     // Return false to handle deleted datasets outsid ethe synchronization callback.

     return callback(true);

  },

  onDatasetsMerged: function(dataset, datasetNames, callback) {

     // Return true to continue the synchronization process.
     // Return false to handle dataset merges outside the synchroniziation callback.

     return callback(false);

  }

});

Change Log

v1.0.0:

  • Initial release. Developer preview.

amazon-cognito-js's People

Contributors

fanbeatsman avatar hyandell avatar jackie-scholl avatar jotto avatar jpeddicord avatar justinlatimer avatar mikemurry avatar nuclearcookie avatar pchuri avatar timmattison avatar tingletech avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

amazon-cognito-js's Issues

CognitoSyncDataset.get(key, callback) returns "undefined" value.

After logging in and getting authenticated credentials for a user I want to create/read datasets for the user in cognito identity pool. I am able to create and read datasets from identity pool after which the records are getting stored in the browser's localStorage. But using 'get' and 'put' methods of "CognitoSyncDataset" in 'amazon-cognito-js' sdk, I am getting values for 'put' but getting "undefined" for get even though it is there in the localStorage. Here's my code:

var syncClient = new AWS.CognitoSyncManager();
syncClient.openOrCreateDataset("myDataset", function(err, dataset) {
              dataset.get("testk1", function(err, value) {
                if(err) console.log(err);
                else{
                  console.log("Record got:\n");
                  console.log(value);
                }
              });
              dataset.synchronize({
                onSuccess: function(dataset, newRecords) {
                  console.log('Successfully synchronized ' + newRecords.length + ' new records.');
                },
                onFailure: function(err) {
                  console.log('Synchronization failed.');
                  console.log(err);
                },
                onConflict: function(dataset, conflicts, callback) {
                  var resolved = [];
                  for (var i=0; i<conflicts.length; i++) {
                    // Take remote version.
                    // resolved.push(conflicts[i].resolveWithRemoteRecord());
                    // Or... take local version.
                    resolved.push(conflicts[i].resolveWithLocalRecord());

                    // Or... use custom logic.
                    // var newValue = conflicts[i].getRemoteRecord().getValue() + conflicts[i].getLocalRecord().getValue();
                    // resolved.push(conflicts[i].resovleWithValue(newValue);
                  }
                  dataset.resolve(resolved, function() {
                    return callback(true);
                  });
                  // Or... callback false to stop the synchronization process.
                  // return callback(false);
                }  
              });
            });

Chrome crashes with around 700 records in a dataset

i guess its happening because of huge stack in "CognitoSyncLocalStorage.prototype.putRecords". adding a "setTimeout(request, 0)" instead of "request()" inside the inner "request" method seems to fix it and does not crash even with 1000 records.

same problem in "CognitoSyncLocalStorage.prototype.putAllValues". using "function(){setTimeout(request,0)}" for callback of putValue call fixed it.

no error when jwt/session is expired

If the jwt is not refreshed (and becomes expired), and a dataset is synchronized, the onSuccess callback is called. The logs look like this:

syncing myTestDataset
console.js:26 Starting synchronization... (retries: 3)
console.js:26 Checking for locally merged datasets... found 0.
console.js:26 Detecting last sync count... 43
console.js:26 Fetching remote updates... found 0.
console.js:26 Checking for remote merged datasets... found 0.
console.js:26 Checking for remote updates since last sync count... found 0.
console.js:26 Nothing updated remotely. Pushing local changes to remote.
console.js:26 Sync successful.

Is this expected behavior? I would have expected onFailure to be called, otherwise how would we know whether an empty local dataset is truly empty or not? (we'd get onSuccess, and all get's would return undefined.)

If it is expected behavior, what is a best practice?

By the way, I actually discovered this problem through an official email from AWS:

Recently, we saw that most of your calls to federate Cognito user Pool users into AWS with federated identities are failing because your code is sending expired Cognito User Pools ID Token to the federated identity service.

(as opposed to an error being thrown in the amazon-cognito-js code)

"logging" instead of "logger"

I've got a strange error "Uncaught TypeError: c.logging is not a function". I was looking for the file "CognitoSyncDataset.js". There is root.logging instead of root.logger. It seems like an error.

283 root.logging('Deferring to .onDatasetsMerged.');
340 root.logging('Dataset should be deleted. Deferring to .onDatasetDeleted.');
343 root.logging('.onDatasetDeleted returned true, purging dataset locally.');
349 root.logging('.onDatasetDeleted returned false, cancelling sync.');

Question: Dataset deleted and created manually trough AWS Console. How to handle this case?

Hi,
I am not sure If I understand how to handle subject. Right now I am always getting exception undefined is not a function inside aws-sdk,js at https://github.com/aws/aws-sdk-js/blob/master/dist/aws-sdk.js#L2857
My code:

AWS.config.credentials.get(function () {
        AWS.config.credentials.getId(function (err, data) {
            var syncClient = new AWS.CognitoSyncManager();
            syncClient.openOrCreateDataset('jobs', function (err, dataset) {
                $interval(function () {
                    dataset.synchronize({
                        onFailure: function (err) {
                            console.log(err);
                        },
                        onSuccess: function (data, newRecords) {
                            dataset.getAll(function (err, records) {
                                var _filtered = _.filter(_.values(records), function (v) {
                                    return !_.isEmpty(v);
                                });
                                $scope.items = _.map(_filtered, function (r) {
                                    return JSON.parse(r);
                                });
                                $scope.$apply();
                            });
                        },
                        onDatasetDeleted: function (dataset, datasetName, callback) {
                            console.log('dataset deleted!');
                            var res = callback(true);
                            console.log(res);
                            return res;
                        }
                    });
                }, 5000);
            });
            $scope.id = data;
            $scope.$apply();
        });
    });

The exception happens inside onDatasetDeleted handler when I call callback(true)

Please, advise.

Maintenance and future

We are testing and considering using Cognito for our production apps @TechnologyAdvice. I had a couple questions about this project.

  1. Is this project still maintained? There are some old issues without responses.
  2. Are there plans to add tests?
  3. Are there plans for distributing this on npm/bower/cdn?

If there are plans to maintain, add tests, and distribute this project we'd be more inclined to use it. Also, in that case we may have some resources to help with those things if needed.

Sync unauthenticated user data with just authenticated user

My app allows user add data while unauthenticated with cognito sync. I want a situation where when a user logs in, it takes data it saved while user was unauthenticated and merges it with the data owned by the just authenticated user. How do I achieve this?

Property 'get' does not exist on type 'Credentials | CredentialsOptions'.

Hi, I am importing this library via npm and used Angular2 Cognito Quickstart for reference but I also need to use cognitosync library which get called immediately after login. Below is the code I am trying for which I am facing many issues

Property 'get' does not exist on type 'Credentials | CredentialsOptions'.
Property 'identityId' does not exist on type 'Credentials | CredentialsOptions'.
Property 'CognitoSyncManager' does not exist on type 'typeof ".../node_modules/aws-sdk/global"'.

---------cognito.service.ts---------
` import {
AuthenticationDetails,
CognitoIdentityServiceProvider,
CognitoUser,
CognitoUserAttribute,
CognitoUserPool
} from "amazon-cognito-identity-js";
import * as AWS from "aws-sdk/global";
import * as STS from "aws-sdk/clients/sts";
import * as awsservice from "aws-sdk/lib/service";
import * as CognitoIdentity from "aws-sdk/clients/cognitoidentity";

buildCognitoCreds( idTokenJwt: string ) {
let url = 'cognito-idp.' + Environment.REGION.toLowerCase() + '.amazonaws.com/' + Environment.USER_POOL_ID;
if ( Environment.COGNITO_IDP_ENDPOINT ) {
url = Environment.COGNITO_IDP_ENDPOINT + '/' + Environment.USER_POOL_ID;
}
let logins: CognitoIdentity.LoginsMap = {};
logins[url] = idTokenJwt;
let params = {
IdentityPoolId: Environment.IDENTITY_POOL_ID,
Logins: logins
};
let serviceConfigs: awsservice.ServiceConfigurationOptions = {};
if ( Environment.COGNITO_IDENTITY_ENDPOINT ) {
serviceConfigs.endpoint = Environment.COGNITO_IDENTITY_ENDPOINT;
}
let creds = new AWS.CognitoIdentityCredentials( params, serviceConfigs );
this.setCognitoCreds( creds );
return creds;
}

authenticate( username: string, password: string ): Promise {

let authenticationData = {
	Username: username,
	Password: password,
};
let authenticationDetails = new AuthenticationDetails( authenticationData );

let userData = {
	Username: username,
	Pool: this.getUserPool()
};
let cognitoUser = new CognitoUser( userData );
var self = this;
return new Promise(
	( resolve, reject ) => {
		cognitoUser.authenticateUser( authenticationDetails, {
			onSuccess: function( result ) {
				let creds = self.buildCognitoCreds( result.getIdToken().getJwtToken() );
				console.log(creds);
				AWS.config.credentials = creds;
				let clientParams: any = {};
				if ( Environment.STS_ENDPOINT ) {
					clientParams.endpoint = Environment.STS_ENDPOINT;
				}
				let sts = new STS( clientParams );
				sts.getCallerIdentity( function( err, data ) {
					console.log( "CognitoService: Successfully set the AWS credentials", data );
					self.getUserAttributes()
						.then( results => {
							console.log('user attributes==>', results);
							resolve( result );
						} )
						.catch( error => { } );
				} );

			},
			onFailure: function( error ) {
				reject( error );
			}
		} );
	} );

}`

---------cognito-sync.service---------
`import * as AWS from "aws-sdk/global";
import * as CognitoSync from "aws-sdk/clients/cognitosync";
import { CognitoSyncManager } from 'amazon-cognito-js';

initSync(): void {
this.cognitosync = new CognitoSync( { correctClockSkew: true } );
this.cognitoSyncManager = new AWS.CognitoSyncManager(); // 3rd issue
}

getAllDatasets(): Promise<DataSets> {
    return new Promise(
        ( resolve, reject ) => {
            let promise = AWS.config.credentials.getPromise(); // **1st issue**
            promise.then(() => {
            console.log(AWS.config.credentials);
                let identityID = AWS.config.credentials.identityId; // **2nd Issue**
                let params = {
                    IdentityId: identityID,
                    IdentityPoolId: Environment.IDENTITY_POOL_ID
                };
                this.cognitosync.listDatasets( params, ( error, data ) => {
                    if ( error ) {
                        console.error( error );
                        reject( error );
                    }
                    else {
                        resolve( data );
                    }
                } );
            } ).catch( error => {
                console.error( error );
            } );
        } );
}`

Please help.

Data Synchronisation not working

When I call synchronise(), it syncs data but it shows 0 records synced even if there are new records. Only when I call getAllRecords after that do I get to see new records.

Also, I'd like if I can listen on sync event and sync happens automatically using some some of push/pull mechanism.

Please include un-minified distribution file

Even with sourcemaps, debugging the minified dist/amazon-cognito.min.js file during development can be a real pain.

Please include an un-minified version in the dist/ directory.

deleted records can not be added again

I'm attempting to create a dictionary of values in a dataset, when I add a key to the dataset and synchronize everything works fine. If I delete that key by calling dataset.remove and synchronize everything works fine here too.

The problem is when I try to add that same key back in after it's been removed previously and synchronize. My local dataset shows the value, and when I call dataset.synchronize none of my callbacks are being fired ... but I can see the request in Chrome's network log, as well as in the Cognito Sync Event trigger that is being called.

I enabled logging on the sync manager, and during a successful sync (adding or removing the item for the first time), I get a sync successful message ... however, when trying to add the item back in and sync, the last message I get is Nothing updated remotely. Pushing local changes to remote.

Synchronize function does not works everytime.

Test Case:

Step 1) In chrome, I update the record of dataset then do synchronize() which gives Success
Step 2) Go to firefox and synchronize() there also Success is called.

Now in firefox I have the latest record that was updated in step (1).

On repeating the above steps multiple time, step(2) stops getting latest record updated in step (1) even when onSuccess is still called for firefox step(2).

Note: To resolve conflict I use deviceLastModifiedDate. Whichever is latest I use that.

`
bnUserPreferencesDataset.synchronize({onSuccess: function () {

                contents.fillDatasetMap();
            }, onConflict: function (dataset, conflicts, callback) {
                var resolved = [];
                var i = 0;
                while (i < conflicts.length) {
                    if (conflicts[i].localRecord.deviceLastModifiedDate > conflicts[i].remoteRecord.deviceLastModifiedDate) {
                        resolved.push(conflicts[i].resolveWithLocalRecord());
                    } else {
                        resolved.push(conflicts[i].resolveWithRemoteRecord());
                    }
                    i += 1;
                }
                if (resolved.length) {
                    dataset.resolve(resolved, function (err) {
                        if (err) {
                            return callback(false);
                        }
                        return callback(true);
                    });
                }
            }, onFailure: function (err) {
                console.log(err);
            }});`

Request: React native support

Because aws-sdk has nodejs dependencies, to integrate with my react-native project, I have to change a line of code in node_modules/dist/amazon-cognito.min.js from require("aws-sdk") to require("aws-sdk/dist/aws-sdk-react-native").

This of course isn't ideal for my project, since it makes me worry that if amazon-cognito-js updates, my code might break.

Would it be possible to release a branch of this project for react-native users containing this small change, or offer a more dynamic require system? Thanks!

Unable to retrieve values from dataSet if the app starts in offline mode

I'm trying to make my web app work offline. I have done the registration and login using aws cognito. I created a CognitoSyncManager and then a DataSet ( basically following the examples ), and i was able to save things and retrieve them. My problem is i can't get values from the dataSet if i reload my app been offline. I'm getting "network error" ( while authenticating ) because i'm not online. I tried to access the dataset, i can ask it for a value, but they are all "undefined". So, is it possible to access it been offline since the app starts?

final bundle size is quite large

Feel free to close this out if things are working as intended, but in a fresh app created with create-react-app requiring this library adds almost 2 MBs of code to the final bundle size. To contrast, adding the amazon-cognito-identity-js library adds only 0.08 MBs.

I would imagine the scope of what each library does is drastically different, but I'm wondering if there is something else that can be done to cut back on the final bundle size. Possibly moving some of the more barebones methods to their own module that we can include directly.

Having trouble getting data to be distinct per user

I'm using UserPools and have followed your example code here but when i have 2 users the data is shared between them. Obviously not what I want! For now I'm not using sync, just logging the users in and out and getting / putting.

  • In the example in the README you say make sure the identity pool should allow unauthenticated access. Surely that is just for the demo code? I do not want unauthenticated access.
  • Shouldn't I use the Identity pool configured to work the the UserPool? If I do that I get 400 Bad request
  • I'm assuming that the sync code pulls the tokens and identity out of the AWS config as no examples so it being shared explicitly
  • I'm always seeing 'null.MyDataSet' in local storage as well as those for the 2 identies
  • Is there some further config I need that I have not discovered yet?

My code is
https://github.com/OpenDirective/brian/blob/master/src/js/drivers/providers/aws/sync-aws-cognito.js
https://github.com/OpenDirective/brian/blob/master/src/js/drivers/providers/aws/sync-aws-cognito.js

thanks

Push-Sync for JavaScript

Do you guys have any plans of building Congnito-Push-Sync for JavaScript? Perhaps something on top of WebSockets similar to the IoT stuff? That would be extremely helpful.

Error: CognitoSyncManager is not a constructor

I'm

working on an Ionic App with Angular 4 and TypeScript 2.3.4


import { CognitoUserPool, } from 'amazon-cognito-identity-js';
import * as AmazonCognitoSync from 'amazon-cognito-js';
import * as AWS from 'aws-sdk';

        let client = new AmazonCognitoSync.CognitoSyncManager();
        console.log(client);

Error:
ERROR TypeError: __WEBPACK_IMPORTED_MODULE_3_amazon_cognito_js__.CognitoSyncManager is not a constructor.

Can you rename to amazon-cognito-sync-js

That's consistent with amazon-cognito-identity-js and more clearly identifies it's scope.

Could do with examples of using that repo, especially with User Pools

conflict on dataset synchronization

Hi,

I need some help using Cognito Sync Manager synchronize feature.
The context : I want to store 2 values (key and user) in a cognito dataset. The key value change very often (at each connection) when the user is initialized once and then remains the same.

As it is shown in the documentation, I have called my credentials, instantiated a new CognitoSyncManager, opened/created my dataset, put data in it and finaly synchronized my dataset.

//retrieve credentials
AWS.config.credentials.get(function(error){
  if(error) { console.log(error); }
  //instantiate CognitoSyncManager
  var syncManager = new AWS.CognitoSyncManager();
  syncManager.openOrCreateDataset('data', function(erro, dataset) {
    if(erro) { console.log(erro); }
    dataset.put('key', myKey, function(err) {
      if(err){ console.log(err); }
      dataset.put('user', myUser, function(er) {
        if(er) { console.log(er); }
        //synchronize all changes
        return synchronize(dataset, function(res){
          console.log(res);
        });
      });
    });
  });
});

At the first synchronization (when dataset is created) there is no problem, but at the second it begins to fail (409 Conflict error).
Message returned by cognito : "{"message":"Current SyncCount for: user is: 1 not: 0"}".

It seems that synchronizing a dataset where some values change, but one or more kept the same values cause synchronization conflict that leads to failure after 4 attempts.
My synchronization function :

function synchronize(dataset, callback) {
  dataset.synchronize({
    onSuccess: function(dataset, newRecords) {
      console.log("Dataset has been synchronized !");
      return;
    },
    onFailure: function(err) {
      console.error("Unable to synchronize dataset.")
      console.log(err);
      return;
    },
    onConflict: function(dataset, conflicts, callback) {
      var resolved = [];
      for(var i = 0; i < conflicts.length; i++) 
      {
        resolved.push(conflicts[i].resolveWithLocalRecord()); 
      }   
      dataset.resolve(resolved, function(err, data) {
        if(err) { console.log(err); return callback(false); }
        console.log("Conflict resolved with local record.");
        return callback(true);
      });
    },
    onDatasetDeleted: function(dataset, datasetName, callback) {
      console.log("Dataset deleted.");
      return callback(true);
    },
    onDatasetMerged: function(dataset, datasetNames) {
      console.log("Dataset merged.");
      return callback(false);
    }
  });
}

Is this an issue with the cognitoSyncManager or did I do something wrong ?

Thank you in advance for you help.
With best regards,
Michael

"new AWS.CognitoIdentityCredentials" resets IdentityId to null when there is no connection (offline)

While connected to internet everything works fine. Problem appears when there is no connection.

AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: COGNITO_IDENTITY_POOL_ID
    });

This line of code resets identityId to null, so openOrCreateDataset is unable to open dataset. After that, when internet connection is available again, new identityId is assigned, so openOrCreateDataset creates new dataset instead of opening existing dataset, which was created with old identityId.

Is this a bug? if so, it looks like a critical one - whole offline functionality becomes unusable, because it is not possible to open existing dataset without having identityId (also when online new identityId makes old dataset not accessible).

Could anyone help me solve this problem?

"Synchronized failed: exceeded maximum retry count" when you attempt to store numbers

This took me a little while to figure out. When I attempted to store a numeric value I kept getting this error on synchronization:

Synchronized failed: exceeded maximum retry count

Yes, 'synchronized' failed but that's beside the point. And the error wouldn't go away until I manually cleared local storage.

Workaround: force values to be strings. Numbers, arrays and objects all suffer the same fate.

To reproduce:

...
dataset.put('ten', 10, function (err, record) {
  dataset.synchronize({
    onSuccess: function (data, newRecords) {
      console.log('sync.onSuccess()');
    },
    onConflict: function(dataset, conflicts, conflictCallback) {
      var resolved = [];
      for (var i=0; i<conflicts.length; i++) {
        resolved.push(conflicts[i].resolveWithLocalRecord());
      }
      dataset.resolve(resolved, function() {
        return conflictCallback(true);
      });
    },
    onFailure: function (err) {
      console.log('sync.onFailure()', err);
    }
  });
});
...

Amazon cognito js 404

Im having a error trying to login or register in amazon cognito. The functions was working one month before and now through an 404 error, with this url: https://cognito-idp.us-east-2.amazonaws.com/
and this description code: {"code":"BadRequest","message":"The server did not understand the operation that was requested.","type":"client"}

Note: The working implementation of a month before has not being changed. It just stop working.

Could be something about the version of aws-sdk?

Thanks a lot for the help.

Best regards, Jorge

Error: Synchronize failed: exceeded maximum retry count.

I'm receiving this error after I set onDatasetsMerged callback to return true, and according to README.md it should continue the synchronization process:

dataset.synchronize({
  // ...

  onDatasetsMerged: (dataset, datasetNames, callback) => {
    return callback(true);
  }
});

Can someone help me understand how onDatasetsMerged method works, should I write the logic to merge datasets or it's merged automatically ?

A basic code snippet would be much appreciated :)

Thanks!

Need clarification on CognitoIdentityCredentials, and issue with AWS.config.region?

(1) From the README here:

AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    AccountId: 'YOUR AWS ACCOUNT ID',
    IdentityPoolId: 'YOUR IDENTITY POOL ID',
    RoleArn: 'YOUR UNAUTHENTICATED ROLE ARN'
});

... contradicts with ...

(2) Documentation: http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-configuring.html

AWS.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: 'YOUR IDENTITY POOL ID',
  Logins: { // optional tokens, used for authenticated login
    'graph.facebook.com': 'FBTOKEN',
    'www.amazon.com': 'AMAZONTOKEN',
    'accounts.google.com': 'GOOGLETOKEN'
  }
});

I think I go it working with (2). However, as Cognito is only available in us-east-1 and not us-west-2, with my resources in us-west-2, I define AWS.config.region = 'us-west-2' for other calls, I then get the error:
OPTIONS https://cognito-identity.us-west-2.amazonaws.com/ net::ERR_NAME_NOT_RESOLVED

Is the README here outdated?
Should Cognito not rely on AWS.config.region?

How should I go about communicating with Cognito in us-east-1, while making other AWS API calls to us-west-2?

Using CognitoSyncManager in a browser

The docs seem to indicate that all I need to do is the following, but I receive an error:

  1. Include AWS SDK
  2. Include amazon-cognito-js via <script> tag
  3. Call the AWS.CognitoSyncManager() constructor

My test HTML file looks like this:

<!DOCTYPE html>
<html>
  <head>
    <script src="/js/aws-sdk-full-dev-2.7.20.js"></script>
    <script src="/js/amazon-cognito.min.js"></script>
    <script>
      var syncClient = new AWS.CognitoSyncManager();
    </script>
  </head>
</html>

The error in the dev console is:

amazon-cognito.min.js:35
Uncaught ReferenceError: require is not defined
    at amazon-cognito.min.js:35
    at amazon-cognito.min.js:13
    at amazon-cognito.min.js:15
(anonymous) @ amazon-cognito.min.js:35
(anonymous) @ amazon-cognito.min.js:13
(anonymous) @ amazon-cognito.min.js:15
test.html:7
Uncaught TypeError: AWS.CognitoSyncManager is not a constructor
    at test.html:7

If I add require.js to my list of includes, then the first error about "require is not defined" goes away, but the 2nd error about AWS.CognitoSyncManager remains.

Record removals are not synchronized

I'm using Cognito Events to trigger a Lambda function which validates and removes invalid records in the dataset (as described here).

When the Lambda function removes a record from the data store, the sychronize() response from the Cognito server looks correct - the record isn't returned... But the record is never removed from the local dataset.

How am I supposed to synchronize record removals?

Using amazon-cognito-js in Lambda Function

I uploaded zip file containing the module in Lambda function.

After doing AWS Cognito Logins map I get AWS Keys from sts, that works fine.

The issue is when I instantiate the Cognito Sync manager with:

var client = new AWS.CognitoSyncManager();

I get the following error:

screen shot 2017-09-07 at 11 30 05 am

It seems that this package will only work in browser? How can I use this package in Lambda Function?

Private/Incognito mode errors

The sync manager should fail gracefully if running in a private/incognito browser window and not try to use localStorage.

reducing system time by 10 mins causes ListDataset call to fail

ListDataset call is failing with following error when machine time is reduced by 10 mins:

{"message":"Signature expired: 20160615T060713Z is now earlier than 20160615T061234Z (20160615T061734Z - 5 min.)"}

our server will get the token using "get_open_id_token_for_developer_identity" (in ruby). from error we can infer that ListDataset call is actually comparing server time at which the token was created with the client time at which the ListDataset was called.

we are using "AWS SDK for JavaScript v2.0.27" and cognito-sync-js latest from https://github.com/aws/amazon-cognito-js.

how can we get around this OR will amazon fix it?

Non-minified export

Currently, the default export is minified, complicating development. Users importing your library from NPM are likely to have a build system with its own minifier. You should at least provide a non-minified version, and ideally make it default.

ReferenceError: window is not defined

On plain JS (not Browser) environment (ex. unit test), CognitoSyncManager don't work properly.

ReferenceError: window is not defined
    at new a (src/_lib/amazon-cognito.min.js:35:23975)
    at new a (src/_lib/amazon-cognito.min.js:35:13090)
    at new AWS.CognitoSyncManager (src/_lib/amazon-cognito.min.js:35:377)
    at server/server_test.js:43:28
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)

code is below.

      aws.config.credentials.get(() => {
        const syncClient = new aws.CognitoSyncManager();
        syncClient.openOrCreateDataset('myDataset', (err, dataset) => {
          dataset.put('myKey', 'myValue', (err, record) => {
            dataset.synchronize({
              onSuccess: (data, newRecords) => {
                // Your handler code here
                console.log();
              }
            });
          });
        });
      });

CognitoSync data set Records issue

Hi,

when requesting data from a data set (dataSet.get) we receive a correct response containing Records array which is not empty. Problem is, when we do this call the second time, Records array is empty.

This is a problem for us as we do this dataSet.get call after user log in to fetch user-related data. Then when the user logs out and logs in again, we do the same call (it might be for another user) but the response's Records is empty (even though the data are stored in Cognito).

Is there something that we are missing?

Thanks!

Syncronizing with integers in datasets causes errors

I realize that integers probably don't belong in datasets but the fact that put and get accepts them and the error only shows up when you synchronize was a little frustrating. Then tracing down the issue was difficult because the error in the console said "Error: Synchronized failed: exceeded maximum retry count.". So there was no indication of why it had failed.

dataset.put('newRecord', 12, function(err, record) {
    console.log(record);
    // Synchronize at some point... EXPLOSION!
});

edit: styling js

Question: What to do if sync fails?

On Sync sometime I start getting

{"message":"Current SyncCount for: bn_lastEdt is: 8006 not: 8001"}

What to do in this case?

Also, synchronize does not work all the time. Even onSucces latest data is not received from the remote.

Is there any way I can force get all records from CognitoSync remote ?

Error: Remote and local keys do not match.

I am able to add and delete records with no issue after clearing localStorage. However, after a short period of time, I get this error.

Error: Remote and local keys do not match.

I have manually compared the remote and local keys. They appear to match. Incidentally, the keys are integers and the values are strings.

It is possible login in Cognito without connection????

I have a doubt about Cognito and offline.
The question is simple yet complex: You can log in to Cognito offline? Or is it only possible to save data locally (with DataSet) to allow operation of the application offline?

I ask this because I would use my application especially in offline, so I have to make a login without a connection.

I hope that I have explained well.
Thansk for help

Offline access

Can we access the datasets while offline that is, We are not finding any code and Apis for the same.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.