How to use Promise in angular2 with firebase to transform login to service - firebase

I'm learning how to code. I'm struggling with promise, and how to use them.
I want to accomplish login using Facebook with Firebase.
The code works perfectly when I don't use this as service
authWithFacebook(){
this.usersRef.authWithOAuthPopup("facebook", (error) => {
if (error) {
console.log(error);
}else if (this.isLoggedIn && this.newUser) {
this.usersRef.child(this.authData.uid).set({
NomComplet: this.authData.facebook.displayName,
ProfileCached: this.authData.facebook.cachedUserProfile,
Nom : this.authData.facebook.cachedUserProfile.last_name,
Prenom : this.authData.facebook.cachedUserProfile.first_name,
ProfileImg: this.authData.facebook.profileImageURL,
Agemoyen : this.authData.facebook.cachedUserProfile.age_range,
Localite : this.authData.facebook.cachedUserProfile.locale,
});
}
});
console.log("je suis connecté" + " " + this.authData.facebook.displayName )
}
I attemped to transform my code into a service, which can be used in the entire app. But it doesn't work:
authWithOAuth(){
return new Promise(function(resolve, reject){
this.usersRef.authWithOAuthPopup("facebook", (error) => {
if (error) {
console.log(error);
reject(error);
}else {
resolve();
}
})
})
}
Can anyone can help me with this or tell me which doc to read to fully understand this?

You need to refactor your code like this:
authWithFacebook(){
this.authService.authWithOAuth().then(
() => {
this.usersRef.child(this.authData.uid).set({
NomComplet: this.authData.facebook.displayName,
ProfileCached: this.authData.facebook.cachedUserProfile,
Nom : this.authData.facebook.cachedUserProfile.last_name,
Prenom : this.authData.facebook.cachedUserProfile.first_name,
ProfileImg: this.authData.facebook.profileImageURL,
Agemoyen : this.authData.facebook.cachedUserProfile.age_range,
Localite : this.authData.facebook.cachedUserProfile.locale,
});
},
(err) => {
console.log(error);
}
);
}
to use the then method of promises.

Related

push notification FCM - 401 INVALID_KEY or MismatchSenderId postman

Code to generate keys : Ps validPublicKey is a firebase code p256dh.
I don´t know where is the problem. If is in the generate code, or the send notification.
I need to put it in php code yet.
navigator.serviceWorker.ready
.then(function(swreg) {
reg = swreg;
console.log(swreg.pushManager.getSubscription());
console.log(JSON.stringify(swreg.pushManager.getSubscription()));
return swreg.pushManager.getSubscription();
})
.then(function(sub) {
if (sub === null) {
console.log('criando a chave');
var validPublicKey = 'BIG2EEduGTIoAYMFC3zpq2lksUw-OLRUrq_abhLs1Y2Zbo_xDUGwlozyezbSKqNkYylNN2yWKV5adB0819nQ1y0';
var convertValidPublicKey = urlBase64ToUint8Array(validPublicKey);
return reg.pushManager.subscribe({
userVisibleOnly:true,
applicationServerKey:convertValidPublicKey
});
} else {
//we have
}
}).then(function(newSub) {
return fetch('https://???????.firebaseio.com/subscriptions.json', {
method:'POST',
headers: {
'Content-Type':'application/json',
'Accept':'application/json'
},
body:JSON.stringify(newSub)
})
}).then(function(res) {
if (res.ok) {
displayConfirmNotification();
}
}).catch(function(err) {
console.log(err);
});
}

alexa sdk: can't get persitentAttributes

i'm trying to add persistent attributes to my lambda function.
i created a dynamoDB table and added it to the triggers of my lambda function.
i copied a sample code from github, but when i try to launch the skill i get an error. The console log shows:
{
"errorMessage": "Could not read item (amzn1.ask.account.AGIIYNRXWDLBD6XEPW72QS2BHGXNP7NWYBEWSH2XLSXZP64X3NCYEMVK233VFDWH77ZB6DAK6YJ53SZLNUFVQ56CYOVCILS7QFZI4CIRDWC3PAHS4QG27YUY5PTT6QEIK46YFNTJT54YAKNGOWV2UO66XZACFDQ5SEXKJYOBNFNIZNUXKNTIAAYZG4R5ZU4FMLPDZZN64KLINNA) from table (Spiele): The provided key element does not match the schema",
"errorType": "AskSdk.DynamoDbPersistenceAdapter Error",
"stackTrace": [
"Object.createAskSdkError (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/utils/AskSdkUtils.js:22:17)",
"DynamoDbPersistenceAdapter.<anonymous> (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:123:49)",
"step (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:44:23)",
"Object.throw (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:25:53)",
"rejected (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:17:65)",
"<anonymous>",
"process._tickDomainCallback (internal/process/next_tick.js:228:7)"
]
}
the table contains a primary key "name" and sort key "UserId". is that wrong?
here is my index.js:
const Alexa = require('ask-sdk');
// Define the skill features
let skill;
/**
* If this is the first start of the skill, grab the user's data from Dynamo and
* set the session attributes to the persistent data.
*/
const GetUserDataInterceptor = {
process(handlerInput) {
let attributes = handlerInput.attributesManager.getSessionAttributes();
if (handlerInput.requestEnvelope.request.type === 'LaunchRequest' && !attributes['isInitialized']) {
return new Promise((resolve, reject) => {
handlerInput.attributesManager.getPersistentAttributes()
.then((attributes) => {
attributes['isInitialized'] = true;
saveUser(handlerInput, attributes, 'session');
resolve();
})
.catch((error) => {
reject(error);
})
});
}
}
};
function saveUser(handlerInput, attributes, mode) {
if(mode === 'session'){
handlerInput.attributesManager.setSessionAttributes(attributes);
} else if(mode === 'persistent') {
console.info("Saving to Dynamo: ",attributes);
return new Promise((resolve, reject) => {
handlerInput.attributesManager.getPersistentAttributes()
.then((persistent) => {
delete attributes['isInitialized'];
handlerInput.attributesManager.setPersistentAttributes(attributes);
resolve(handlerInput.attributesManager.savePersistentAttributes());
})
.catch((error) => {
reject(error);
});
});
}
}
const LaunchHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'LaunchRequest';
},
handle(handlerInput) {
console.info("LaunchRequest");
let attributes = handlerInput.attributesManager.getSessionAttributes();
console.info("Test the load: " + attributes['isInitialized']);
attributes['FOO'] = "BAR";
saveUser(handlerInput, attributes, 'persistent');
return handlerInput.responseBuilder
.speak('Hello')
.reprompt('Hello')
.getResponse();
}
}
exports.handler = Alexa.SkillBuilders.standard()
.addRequestHandlers(
LaunchHandler
)
.addRequestInterceptors(GetUserDataInterceptor)
.withTableName('Spiele')
.withAutoCreateTable(true)
.withDynamoDbClient()
.lambda();
can anyone tell me what i'm doing wrong?
please confirm the partition key is 'userId' not 'UserId' (notice the uppercase U).
Also I would suggest using 'this' object.
Let me know if that helps.
Cheers
Below code is for python lambda function
from ask_sdk_core.skill_builder import CustomSkillBuilder
from ask_sdk_dynamodb.adapter import DynamoDbAdapter
sb = SkillBuilder()
sb = CustomSkillBuilder(persistence_adapter = dynamodb_adapter)

meteor update method not working

this is my colletion:
{
"_id" : "Kan6btPXwNiF84j8e",
"title" : "Chapter Title 1",
"businessId" : "qmWJ3HtZrpka8dpbM",
"createdBy" : "GfdPfoPTiSwLv8TBR",
"sections" : [
{
"id" : "T5KAfTcCb7pCudT3a",
"type" : "TEXT",
"data" : {
"text" : "<h1>2</h1><h1>asd</h1>"
},
"createdAt" : ISODate("2016-12-03T10:35:59.023Z"),
"updatedAt" : ISODate("2016-12-03T10:35:59.023Z")
}
],
"createdAt" : ISODate("2016-12-02T12:15:16.577Z"),
"updatedAt" : ISODate("2016-12-03T12:54:50.591Z")
}
this is the meteor method I am calling from client side
deleteSection: function (section_id, chapter_id) {
chaptersCollection.update(
{$and: [{_id: chapter_id}, {'sections.id': section_id}]},
{$pull: {'sections': {'id': section_id}}},
function (err, numAffected) {
if (err) {
console.log(err);
return err;
}else{
console.log(numAffected);
}
});
return 'Section Successfully Deleted';
}
in callback function of meteor method, it returns 1 as affected rows. But on server document is not updating.
Any suggestion where am I wrong?
Do you really need $and?
deleteSection: function (section_id, chapter_id) {
chaptersCollection.update(
{_id: chapter_id, 'sections.id': section_id},
{$pull: {'sections': {'id': section_id}}},
function (err) {
if (err) {
console.log(err);
return err;
}else{
console.log('success');
return 'success';
}
});
}
I had a similar issue when I tried to use pull in a project. So instead of using $pull, I handled the array outside of the database and then set the array as the one I handled outside. So maybe you can try something like that as an alternative way
deleteSection: function (section_id, chapter_id){
const oldArray = chaptersCollection.findOne(chapter_id).sections;
const newArray = oldArray.filter(function(section) {
return section.id !== section_id
});
chaptersCollection.update({_id: chapter_id},
{$set: {sections: newArray}},
function (err, numAffected) {
if (err) {
console.log(err);
return err;
}else{
console.log(numAffected);
}
});
return 'Section Successfully Deleted';
}

Reauthenticate Firebase User

I am working on a project with angularfire and I am trying to implement the method to update user password. Due the messed documentation about it, please help me to find a solution to re-authenticate an user. I've already read this stackoverflow question
account.js:
vm.updateUserPassword = function() {
if (vm.oldPassword && vm.newPassword && vm.confirmNewPassword) {
if (vm.newPassword === vm.confirmNewPassword) {
var currentCredential = firebaseAuth.EmailAuthProvider.credential(vm.currentAuth.email, vm.oldPassword);
vm.currentAuth.reauthenticate(currentCredential)
.then(function() {
Database.updateUserPassword(vm.newPassword);
}, function(error) {
console.error('[Account]', error);
});
} else {
toastr.error('A nova senha não confere');
}
} else {
toastr.error('Preencha todos os campos corretamente');
}
};
database.js service:
vm.updateUserPassword = function(newPassword) {
firebaseAuth.$updatePassword(newPassword)
.then(function() {
console.log('[Database] Password changed successfully!');
}).catch(function(error) {
switch (error.code) {
case 'auth/requires-recent-login':
vm.translationId = 'FIREBASE.AUTH.REQUIRES_RECENT_LOGIN.ERROR_MSG';
break;
default:
vm.translationId = error.message;
}
$translate(vm.translationId)
.then(function(translated) {
toastr.error(translated);
}, function(translationId) {
vm.translationId = translationId;
});
});
};
Console error:
TypeError: Cannot read property 'credential' of undefined
You can get credential using:
firebase.auth.EmailAuthProvider.credential(user.email, userProvidedPassword);
instead of:
firebase.auth().EmailAuthProvider.credential(user.email, userProvidedPassword);

Meteor Tracker autorun fires 2 times

This Meteor client code tries to make the Tracker.autorun to run once but as it appears to be that it has to run twice, once for setting and once for reactiveness.
Which is fine but it is firing 3 times. Once for setting and 2 for reacting even though the server only updated the user.profile.abc once.
To test it, I run this code in the mongodb console and the the iamge attached is what I got which confirms it fires twice.
How can I get it to run only once for responding to the changes in the users collection? Thanks
db.users.update({_id: Meteor.userId()},{$set: {'profile.ABC': ['a','b']}}).pretty()
//client
Meteor.call('cleanABC', (err) => {
if (!err) {
ABCListener();
}
});
ABCListener: () => {
Tracker.autorun(() => {
if (Meteor.userId()) {
console.log('auto run invoked');
if (Meteor.user().profile.ABC) {
const myArray = Meteor.user().profile.ABC;
//myFunction(myArray);
console.log('condition true');
} else {
console.log('condition false');
}
}
});
}
//server
'cleanABC': function() {
return Meteor.users.update({
_id: Meteor.userId()
}, {
$unset: {
'profile.ABC': ''
}
});
}
//and some where else in the code
Meteor.users.update({
_id: userId
}, {
$set: {
'profile.ABC': myArray
}
}, (err) => {
if (!err) {
console.log('just sent the array');
}
});
I think the problem is that you are just calling Tracker.autorun everytime you call the method.
I think if you change your client code to:
//client
ABCListener: () => {
Tracker.autorun(() => {
if (Meteor.userId()) {
console.log('auto run invoked');
if (Meteor.user().profile.ABC) {
const myArray = Meteor.user().profile.ABC;
//myFunction(myArray);
console.log('condition true');
} else {
console.log('condition false');
}
}
});
}
Meteor.call('cleanABC');
it should work.

Resources