Unable to getCurrentUser for AWS Cognito - amazon-web-services

Newbie to JS and getting the below error with AWS Cognito. I am not able to work out why it is not able to recognize AmazonCognitoIdentity even i have mentioned it explicitly in import statement...
ReferenceError: AmazonCognitoIdentity is not defined
<script type="text/javascript" src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js" ></script>
import * as AmazonCognitoIdentity from 'amazon-cognito-identity-js';
userAuth();
function userAuth() {
var data = {
UserPoolId: 'us-east-1_*****',
ClientId: '********'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
var cognitoUser = userPool.getCurrentUser();
if (cognitoUser != null) {
console.log("Success");
}
else {
console.log("Failure");
}
Any help will be appreciated!

Related

Cognito User Pools is returning null user object

Folks, I am getting similar error where my getCurrentUser is returning null. I think, I partially know the reason for the same.
<script type="text/javascript" src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js" ></script>
<script type="text/javascript" src="/web/amazon-cognito-identity.js"></script>
<script type="text/javascript" src="/web/aws-cognito-sdk.js"></script>
import * as AWSCognito from 'amazon-cognito-identity';
const region = 'us-east-1';
const docClient = createDynamoDbClient();
function createDynamoDbClient() {
AWS.config.update({
region: "us-east-1", endpoint: 'https://dynamodb.us-east-1.amazonaws.com'});
userAuth();
return new AWS.DynamoDB();
}
function userAuth() {
var data = {
UserPoolId: '***********',
ClientId: '************'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data);
var cognitoUser = userPool.getCurrentUser();
try {
if (cognitoUser != null)
{
cognitoUser.getSession(function(err, session)
{
if (err) {
console.log(err);
return;
}
AWS.config.region = 'us-east-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials(
{
IdentityPoolId : 'us-east-1:********',
Logins : {
"cognito-idp.us-east-1.amazonaws.com/us-east-1_*******": session.getIdToken().getJwtToken()
}
});
AWS.config.credentials.get(function(err) {
if (!err)
{
console.log("In try block 4");
var id = AWS.config.credentials.identityId;
console.log('Cognito Identity ID '+ id);
var docClient = new AWS.DynamoDB.DocumentClient(
{
region: AWS.config.region
}
);
var params =
{
TableName: 'VideoInfo',
Item:{
keyName:kN,
technicalMetadata:tM
}
};
docClient.put(
params,
function(err, data) {
if (err){
console.error(err);
}else
{
console.log(data);
}
}
);
}
});
});
}
else {
console.log(cognitoUser);
return;
}
} catch (e) {
console.log(e);
return;
}
}
I am getting the below error essentially which is causing the complete issue.
TypeError: root.AWSCognito is undefined
ReferenceError: AmazonCognitoIdentity is not defined
Possible, it means I am not getting AWSCognito object itself using which I can get the correct UserPool and ending up with null user.
Spent a lot of time on this today and really appreciate if someone can help on the same!
enter image description here

Local storage is missing an ID Token, Please authenticate error while changing password Cognito AWS

I am building an application. In that Sign up, Signin and other operations are working fine. But, when I try to change password using following code, it says
"Local storage is missing an ID Token, Please authenticate"
Code is:
changePassword(mail: any) {
var that = this;
var userPool = new CognitoUserPool(this.poolData);
var userData: any = {
Username: mail,
Pool: userPool
};
var cognitoUser = new CognitoUser(userData);
// To get the session
cognitoUser.getSession(function (err, session) {
if (err) {
alert(err);
return;
}
var userPool = new CognitoUserPool(that.poolData);
var userData: any = {
Username: mail,
Pool: userPool
};
var cognitoUser = new CognitoUser(userData);
var oldp = prompt('Please input old password ', '');
var newp = prompt('Please input new password ', '');
cognitoUser.changePassword(oldp, newp, function (err, result) {
if (err) {
alert(err.message || JSON.stringify(err));
return;
}
alert("Password successfully changed...");
});
});
}
I am not sure what is wrong in this. Please help me solve this.
Thank you...
After so much of struggle, I figured out that I was creating new Cognito user every time using
poolData = {
UserPoolId: "XXXXXXXXXXXXXXXXX",
ClientId: "XXXXXXXXXXXXXXXXXXXXXXXX"
};
userPool: CognitoUserPool = new CognitoUserPool(this.poolData);
So, whenever I call this, a new cognito-user is created. So, change-password on this was not working.
When I created a common function to access cognitoUser and using the same everywhere worked for me.
Thank you...

AWS S3 JS SDK to upload multiple files from a browser

I want to use the AWS S3 JS SDK to upload multiple files from a browser. I can get one file just fine, but can't get multiple. When I select mulitple files, the last file is the only one to get uploaded. Here's the code:
//head
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.213.1.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
//body
<input type="file" id="file-chooser" multiple />
<button id="upload-button">Upload to S3</button>
<div id="results"></div>
<script type="text/javascript">
AWS.config.region = 'us-east-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: '###'
});
AWS.config.credentials.get(function(err) {
if (err) alert(err);
console.log(AWS.config.credentials);
});
var bucketName = 'c2networkingfiles'; // Enter your bucket name
var bucket = new AWS.S3({
params: {
Bucket: bucketName
}
});
var fileChooser = document.getElementById('file-chooser');
var button = document.getElementById('upload-button');
var results = document.getElementById('results');
button.addEventListener('click', function() {
var fileArr = fileChooser.files;
if (fileArr[0]) {
for (k=0; k<fileArr.length; k++) {
var file = fileArr[k];
var fileName = file.name;
// test to see if file already exists
var objKey2 = 'testing/' + file.name;
var objE = new AWS.S3();
var params2 = {
Bucket: bucketName,
Key: objKey2
};
objE.headObject(params2, function(err, data) {
if (data) {
results.innerHTML = 'File is present. Uploaded on ' + data.LastModified;
//console.log(data);
} else {
//results.innerHTML = '';
var objKey = 'testing/' + file.name;
var params = {
Key: objKey,
ContentType: file.type,
Body: file,
ACL: 'public-read'
};
bucket.putObject(params, function(err, data) {
if (err) {
results.innerHTML = 'ERROR: ' + err;
} else {
//listObjs();
results.append('SUCCESS! ' + fileName + ' uploaded. <br />');
}
});
}
});
}
} else {
results.append('Nothing to upload.');
}
}, false);
</script>
The original code example didn't have the loop and I'm wondering if this isn't working right because there isn't a mechanism to wait until the first file has finished before the loop starts the next upload.
If this is the answer, is there a way to check the upload status and wait until the first file is complete before the loop is allowed to continue?
If this isn't the answer, what else could be happening?

"Missing credentials in config" Returned From Amazon S3 JavaScript SDK Server

I've been following the boilerplate code at http://aws.amazon.com/developers/getting-started/browser/ to get CORS uploading to work with my S3 account.
I've created a Facebook App, changed the CORS configuration XML for my S3 bucket, and filled in the appropriate variables in the JavaScript code. But when I try to upload a file through my webpage, I get the Error: Missing credentials in config response.
Can someone point me in the right direction to debugging this?
My JS:
var appId = '999943416325248';
var roleArn = 'arn:aws:iam::458182047307:role/s3-test';
var bucketName = 'my-bucket';
var fbUserId;
var bucket = new AWS.S3({
params: {
Bucket: bucketName
}
});
var fileChooser = document.getElementById('video-file-input');
var button = document.getElementById('submit-button');
var results = document.getElementById('results');
button.addEventListener('click', function () {
var file = fileChooser.files[0];
if(file){
results.innerHTML = '';
//Object key will be facebook-USERID#/FILE_NAME
var objKey = 'facebook-' + fbUserId + '/' + file.name;
var params = {
Key: objKey,
ContentType: file.type,
Body: file,
ACL: 'public-read'
};
bucket.putObject(params, function (err, data) {
if(err){
results.innerHTML = 'ERROR: ' + err;
}
else{
listObjs();
}
});
}
else{
results.innerHTML = 'Nothing to upload.';
}
}, false);
function listObjs() {
var prefix = 'facebook-' + fbUserId;
bucket.listObjects({
Prefix: prefix
}, function (err, data) {
if(err){
results.innerHTML = 'ERROR: ' + err;
}
else{
var objKeys = "";
data.Contents.forEach(function (obj) {
objKeys += obj.Key + "<br>";
});
results.innerHTML = objKeys;
}
});
}
/*!
* Login to your application using Facebook.
* Uses the Facebook SDK for JavaScript available here:
* https://developers.facebook.com/docs/javascript/gettingstarted/
*/
window.fbAsyncInit = function () {
FB.init({
appId: appId
});
FB.login(function (response) {
bucket.config.credentials = new AWS.WebIdentityCredentials({
ProviderId: 'graph.facebook.com',
RoleArn: roleArn,
WebIdentityToken: response.authResponse.accessToken
});
fbUserId = response.authResponse.userID;
button.style.display = 'block';
});
};
// Load the Facebook SDK asynchronously
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if(d.getElementById(id)){
return;
}
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Turns out Chrome was blocking pop-ups on my domain so Facebook authentication couldn't process. Once I allowed pop-ups from the domain, everything worked as expected

Installing one application by another

I am trying to check with my application if one application is installed on specific fan page and if it is not installed I want to install it..
for some reason i am unable to get the page access tokens.
I am able to get the user access tokens and user id, but the page access token returns "Exception" "Unknown fields: access_token".
What is wrong here?
I am using this resources:
http://developers.facebook.com/docs/reference/api/page/#tabs
https://developers.facebook.com/docs/authentication/
<html>
<head>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '188474844587139',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var userAccessToken = response.authResponse.accessToken;
console.log("User Access Token: "+userAccessToken);
console.log("User ID: "+uid);
// get page access token
FB.api('https://graph.facebook.com/'+uid+'/accounts?access_token='+userAccessToken, function(response) {
console.log(response);
var pageAccessToken = 'Need to get from the response...';
// get information if user got this app
FB.api("https://graph.facebook.com/102561956524622/tabs/353470634682630?access_token="+pageAccessToken,
function(data) {
console.log(data);
});
// install the app
var params = {};
params['app_id'] = '353470634682630';
FB.api('https://graph.facebook.com/102561956524622/tabs'+pageAccessToken, 'post', params, function(response) {
if (!response || response.error) {
console.log("Error: "+response);
} else {
console.log("Ok: "+response);
}
});
});
} else if (response.status === 'not_authorized') {
console.log("the user is logged in to Facebook, but not connected to the app.");
} else {
console.log("the user isn't even logged in to Facebook.");
}
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
</body>
</html>
I managed to solve this issue if any one care this is the code
One of reasons it didn't work was because I used the full address "http://graph.facebook.com..." and as you can see in the code I am using the
FB.api function which is adding this address automatically.
Another reason is that I used the user access token to get information about the application instead of the page access token.
I was also having problem to install the application because I needed to send the page access token as well.
P.S: Don't forget that you need manage_pages permission.
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '188474844587139',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
console.log(response.authResponse);
var userAccessToken = response.authResponse.accessToken;
var pageId = '102561956524622';
var appId = '353470634682630';
console.log("User Access Token: "+userAccessToken);
console.log("User ID: "+uid);
// get page access token
FB.api('/'+pageId+'?fields=access_token='+userAccessToken, function(response) {
var pageAccessToken = response.access_token;
// get information if user got this app
FB.api('/'+pageId+'/tabs/'+appId+'?access_token='+pageAccessToken,
function(data) {
if (data.data.length < 1) {
console.log("Not installed, Installing...");
// install the app
var params = {};
params['app_id'] = appId;
FB.api('/'+pageId+'/tabs?access_token='+pageAccessToken, 'post', params, function(response) {
if (!response || response.error) {
console.log("Error Installing:");
console.log(response);
} else {
console.log("Installed :)");
console.log(response);
}
});
}
else {
console.log("Already installed.");
}
});
});
} else if (response.status === 'not_authorized') {
console.log("the user is logged in to Facebook, but not connected to the app.");
} else {
console.log("the user isn't even logged in to Facebook.");
}
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));