Authentication Error when trying to retrieve Youtube Chanel Information - javascript

I am trying authenticate the user and then retrieve youtube channel list.
Below is the function to authenticate:
function authenticate() {
showNewLoader('show');
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
.then(function(response) {
console.log( response);
youtubeAuthResponse['token_details'] = response.tc;
youtubeAuthResponse['google_email'] = '';
youtubeAuthResponse['google_id'] = '';
showNewLoader('hide');
},
function(err) { console.error("Error signing in", err); showNewLoader('hide');});
}
Loading client:
function loadClient() {
showNewLoader('show');
gapi.client.setApiKey("XXXXXX");
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() { execute();},
function(err) { console.error("Error loading GAPI client for API", err);showNewLoader('hide');});
}
/*Make sure the client is loaded and sign-in is complete before calling this method.*/
function execute() {
return gapi.client.youtube.channels.list({
"part": [
"snippet",
"statistics"
],
"mine": true
})
.then(function(response) {
/*Handle the results here (response.result has the parsed body).*/
youtubeChannelResponse = response.result;
storeYoutubeData();
},
function(err) { console.error("Execute error", err); showNewLoader('hide') }).then(function(){
});
}
User logs in successfully but I am unable to get the channel info:
Any assistance on this issue is greatly appreciated. #DalmTo

Related

Unable to broadcast multiple messages on socket io

I'm writing a program where I want to broadcast messages using socket IO. This is for a chat interface.
Here is my code
socket.on('send-chatMessage', message => {
var gotNewMsg = false;
sendChatMessage(message, chatMessagesJSON, function (resp, err) {
console.log('resp from send chat --->');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
gotNewMsg = true;
socket.broadcast.emit('chat-message', {
message: message,
name: users[socket.id]
});
if (gotNewMsg) {
buildChatResponse(chatMessagesJSON, function (resp, err) {
console.log('resp from send chat');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
socket.broadcast.emit('chat-message', {
message: JSON.stringify(resp.messages[0].type),
name: 'Agent'
});
});
}
})
});
Here My first
socket.broadcast.emit('chat-message', {
message: message,
name: users[socket.id]
});
is working fine but my second one
if (gotNewMsg) {
buildChatResponse(chatMessagesJSON, function (resp, err) {
console.log('resp from send chat');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
socket.broadcast.emit('chat-message', {
message: JSON.stringify(resp.messages[0].type),
name: 'Agent'
});
});
}
is not working as expected. I'm able to enter the if and also print the result. The only thing failing is broadcasting.
Here is my broadcast handlers.
socket.on('chat-message', data => {
appendMessage(`${data.name}: ${data.message}`);
})
function appendMessage(message) {
const messageElement = document.createElement('div');
messageElement.innerText = message;
messageContainer.append(messageElement);
};
please let me know where am I going wrong.

file.id undefined during creation folder in google drive with api rest

I receive undefined during creation of a folder by api rest google:
Folder Id: undefined
Below my code:
var fileMetadata = {
'name': nameProduct,
'mimeType': 'application/vnd.google-apps.folder',
parents: XXXXXXXXXXXXXXXX
};
drive.files.create({
auth: jwToken,
resource: fileMetadata,
fields: 'id'
}, function (err, file) {
if (err) {
console.error(err);
} else {
console.log('Folder Id: ', file.id);
}
});
console.log("end creation folder");
How can I print the file.id? Thanks
// Make sure the client is loaded and sign-in is complete before calling
gapi.client.drive.files.create({
"resource": {}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) {
// handle error here.
console.error("Execute error", err); });
}
First you have to create a request then wait the response inside the "then".

Firebase client doesnt recieve message

I have the following Node.js script:
var registrationToken = "Long Token";
var serviceAccount = require("./config/ServiceAccount.json");
var payload = {
data: {
score: "850",
time: "2:45"
}
};
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: fireBaseConfig.databaseURL
});
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
When running this I do get a success response:
Successfully sent message: { results: [ { messageId: '0:1502813815410638%e609af1cf9fd7ecd' } ],
canonicalRegistrationTokenCount: 0,
failureCount: 0,
successCount: 1,
multicastId: 5249778920849394000 }
Then i have my client:
firebase.initializeApp(config);
var messaging = firebase.messaging();
messaging.requestPermission()
.then(function () {
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
console.log('I am in here');
return messaging.getToken()
.then(function (currentToken) {
console.log(currentToken);
})
.catch(function (err) {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
}).catch(function (err) {
console.log('Error');
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
Now first I (as my client) go to the website then I get the token in the console I then use that token in my backend (Node.js) and send a message (while the tap where the client is, is still open) However nothing happens.
Can anyone tell me what I've done wrong?

Chrome not receiving fcm messages, but firefox does

I am using FCM to facilitate push messages in a custom service worker. I followed the FCM getting started but am running into issues where the javascript client isn't receiving the sent messages on chrome, but firefox is working as intended.
The messages are being sent from a hosted server, and the messages are sent with no failures and message id's associated with each registered client.
Below is the page script and below that will be relevant service worker code.
page html
<script>
// Initialize Firebase
var config = {
<CONFIG SETTINGS>
};
firebase.initializeApp(config);
var messaging = firebase.messaging();
</script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js').then(function (registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
messaging.useServiceWorker(registration);
resetUI();
}).catch(function (err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
const permissionDivId = 'permission_div';
messaging.onTokenRefresh(function () {
messaging.getToken()
.then(function (refreshedToken) {
console.log('Token refreshed.');
setTokenSentToServer(false);
sendTokenToServer(refreshedToken);
resetUI();
})
.catch(function (err) {
console.log('Unable to retrieve refreshed token ', err);
});
});
messaging.onMessage(function (payload) {
console.log("Message received. ", payload);
appendMessage(payload);
});
function resetUI() {
clearMessages();
messaging.getToken()
.then(function (currentToken) {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
console.log('No Instance ID token available. Request permission to generate one.');
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
})
.catch(function (err) {
console.log('An error occurred while retrieving token. ', err);
setTokenSentToServer(false);
});
}
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer()) {
console.log('Sending token to server...');
<TOKEN SENT TO SERVER AND STORED>
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won\'t send it again ' +
'unless it changes');
}
}
function isTokenSentToServer() {
if (window.localStorage.getItem('sentToServer') == 1) {
return true;
}
return false;
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? 1 : 0);
}
function showHideDiv(divId, show) {
const div = document.querySelector('#' + divId);
if (show) {
div.style = "display: visible";
} else {
div.style = "display: none";
}
}
function requestPermission() {
console.log('Requesting permission...');
messaging.requestPermission()
.then(function () {
console.log('Notification permission granted.');
resetUI();
})
.catch(function (err) {
console.log('Unable to get permission to notify.', err);
});
}
function deleteToken() {
messaging.getToken()
.then(function (currentToken) {
messaging.deleteToken(currentToken)
.then(function () {
console.log('Token deleted.');
setTokenSentToServer(false);
resetUI();
})
.catch(function (err) {
console.log('Unable to delete token. ', err);
});
})
.catch(function (err) {
console.log('Error retrieving Instance ID token. ', err);
});
}
// Add a message to the messages element.
function appendMessage(payload) {
const messagesElement = document.querySelector('#messages');
const dataHeaderELement = document.createElement('h5');
const dataElement = document.createElement('pre');
dataElement.style = 'overflow-x:hidden;'
dataHeaderELement.textContent = 'Received message:';
dataElement.textContent = JSON.stringify(payload, null, 2);
messagesElement.appendChild(dataHeaderELement);
messagesElement.appendChild(dataElement);
}
// Clear the messages element of all children.
function clearMessages() {
const messagesElement = document.querySelector('#messages');
while (messagesElement.hasChildNodes()) {
messagesElement.removeChild(messagesElement.lastChild);
}
}
function updateUIForPushEnabled(currentToken) {
showHideDiv(permissionDivId, false);
}
function updateUIForPushPermissionRequired() {
showHideDiv(permissionDivId, true);
}
</script>
sw.js
self.addEventListener('push', function (event) {
console.log('Service Worker recived a push message', event.data.text());
var notification = event.data.json().notification;
var title = notification.title;
event.waitUntil(
self.registration.showNotification(title, {
body: notification.body,
icon: notification.icon,
data: { url: notification.click_action }
}));
});
Thank you for any help you can give!

Cloud Functions for Firebase running into infinite loop

I have a custom logic to verify the users.
I have written a Cloud Function for Firebase and to verify the custom tokens.
The problem is the cloud function is not getting terminated and is being run into infinite loop, till Firebase kills the function
The cloud function runs into infinite in both matching and non-matching scenario.
Below is the code:
/* CLOUD FUNCTION */
exports.verifyToken = functions.https.onRequest((req, res) => {
var corsFn = cors();
corsFn(req, res, function () {
verifyTheUserToken(req, res);
});
});
function verifyTheUserToken(req, res) {
if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) {
console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.');
res.status(403).send('Unauthorized');
}
const firebaseToken = req.headers.authorization.split('Bearer ')[1];
const userId = req.body.uid;
const receievedToken = req.body.token;
return admin.auth().verifyIdToken(firebaseToken).then(decodedFirebaseToken => {
console.log('ID Token correctly decoded', decodedFirebaseToken);
console.log('req', req.body);
return 'sucess';
}).then(function (receivedValues) {
return admin.database().ref().child('userTokens').child(userId).child('token').once('value');
}).then(function (snapshot) {
if (!snapshot.val()) {
return Promise.reject('token is not set ');
}
if (snapshot.val() != receievedToken) {
return Promise.reject('token doesnt match');
}
return 'verified';
}).then(function (success) {
return admin.database().ref().child('users').child(userId).child('isVerified').set(true);
}).then(function (success) {
console.log('The user is verified');
return;
}).catch(function (error) {
console.log('Error', error);
return;
});
}
Client side I am doing a HTTP request to call the firebase cloud function.
/* CLIENT SIDE */
var currentUser = firebase.auth().currentUser.uid;
var firebaseUserToken = firebase.auth().currentUser.getToken();
firebase.auth().currentUser.getToken(/* forceRefresh */ true).then(function (firebaseUserToken) {
fetch('https://us-central1-MYAPP.cloudfunctions.net/verifyToken', {
'method': 'POST',
'headers': {
'Authorization': 'Bearer ' + firebaseUserToken,
'Content-Type': 'application/json'
},
'body': JSON.stringify({
'uid': currentUser,
'token': 1234,
})
}).then(function (response) {
console.log('successful response');
}).catch(function (error) {
console.error('Error in fetch', error);
});
}).catch(function (error) {
console.error('Error in getting firebase token', error);
});
I am unable to figure out the reason for the infinite loop.
I would really appreciate any help on this.
Thanks!
I had missed res.send() for the success case.
As per documentation:
Always end an HTTP function with send(), redirect(), or end(). Otherwise, your function might to continue to run and be forcibly terminated by the system.
https://firebase.google.com/docs/functions/http-events

Categories

Resources