Code below:
//set permissions for graph api
var permissions = ['user_friends','user_birthday','user_photos','basic_info'];
var facebookModule = facebookHelper.FacebookConnection(permissions);
//event handler to listen to user when they have logged in
facebookModule.addEventListener('login', function(e){
if(e.success){
//before setting model we want to see if data exists already in database
alert('You were Logged in');
//get me data upon success
facebookModule.requestWithGraphPath('me', {}, 'GET', function(e) {
if (e.success) {
console.log(e.result);
} else if (e.error) {
alert(e.error);
} else {
alert('Unknown response');
}
});
It is returning an incomplete JSON object.
This will be because you have not granted the user_birthday permission while testing.
You check the list of permissions you've granted to your app here.
If you have not. just delete the app from here or logout of the app; and then login again and give the permissions.
Related
I am trying to build a password manager extension for Google Chrome. I want my background script to check for URLs matching with the login URLs of different websites and when it does match, I want to send the credentials of the user to the content script which will autofill the username and password fields. But I am getting the "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist." error
I have seen similar questions and the major answer was to disable the other extensions and try again. I disabled all the extensions and tried, but still getting the same error. I also saw that long-lived connections solve this error, but I don't want to use a long-lived connection as this is a one time message
background.js
/*Listen for changes in URL */
chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
if(changeInfo.url){
console.log(changeInfo.url);
chrome.storage.local.get(null,function(ans){
console.log("local storage",ans);
});
chrome.storage.local.get(['loggedIn'],function(answer){
console.log('logged in answer is',answer);
console.log('logged in answer is',answer.loggedIn);
if(answer.loggedIn===true){
console.log("user logged in")
/* Check whether the user is logged in and the url is in the user credential urls*/
chrome.storage.local.get(['urls'],function(result){
console.log("stored urls",result.urls,"current url",changeInfo.url);
if(result.urls.includes(changeInfo.url)){
console.log("matching url");
console.log("matching url",changeInfo.url);
var urlIndex = result.urls.indexOf(changeInfo.url);
console.log('index',urlIndex);
console.log("main tab id is",tabId)
console.log("tab is",tab);
chrome.storage.local.get(['credentials'],function(result){
console.log(result);
var username = result.credentials[urlIndex].username;
var password = result.credentials[urlIndex].password;
console.log('username',username,password)
var msg = {
username : username,
password : password
}
/* Get the credentials for that site and send it to the content script autoFill.js */
chrome.tabs.sendMessage(tabId,{args: msg},function(response) {
console.log(tabId,tab.url);
console.log(response);
});
});
}
});
}
else{
console.log("user not logged in");
}
});
}
})
content_script.js
console.log("content script is running");
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log("message recieved");
console.log(request.args);
var args=request.args;
console.log('args',args);
var forms = document.getElementsByTagName("form");
console.log(forms);
for(let form of forms){
console.log(form);
for (let index = 0; index < form.length; index++) {
const element = form.elements[index];
//console.log(element);
if(element.type==='password'){
element.value=args.password;
console.log(element.value);
for (let reverseIndex = index-1; reverseIndex >= 0; reverseIndex--) {
const element = form.elements[reverseIndex];
if(element.type==='text'){
element.value=args.username;
break;
}
}
}
else{
continue;
}
}
}
sendResponse("success");
return true;
});
I am expecting the content script to receive the message and make the parameters available in the current tab. So any help about how to fix this error is much appreciated.
Thanks
I have just started with firebase for my webapp and here is my code and problem beneath.
<script src="https://www.gstatic.com/firebasejs/4.1.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.1.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.1.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.1.1/firebase-database.js"></script>
<script>
// Initialize Firebase
var config = {
...
};
firebase.initializeApp(config);
</script>
<script>
function handleSignUp() {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
function initApp() {
document.getElementById('quickstart-sign-up').addEventListener('click', handleSignUp, false);
}
window.onload = function() {
initApp();
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log('yes');
I want data persistence in firebase database at this step.
} else {
console.log('no');
}
});
};
</script>
Problem is whenever I am refreshing my page, as the user is authenticated, console returns Yes (when I am adding the database push logic, data is being saved again and again whenever I am refreshing the page. I have tried moving the console.log OR database push to .onAuthStateChange to my initApp() and handleSignUp() functions as well. But to no avail.
As per firebase docs, I tried the below as well:
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
However, this almost always returns a console.log as No. I am thinking that since it takes some time for the authentication to happen, the user check is skipping authentication and appearing as if No user is authenticated.
The ask is I want the user to be signed up (and automatically logged in which happens anyway with firebase) and user details (along with additional details which I am asking the user to fill in at Sign Up) to be saved in firebase database one time only. Any pointer would be appreciated here.
Think I got it. The use of then (promises):
firebase.auth().createUserWithEmailAndPassword(email, password).then(function() {
var user = firebase.auth().currentUser;
console.log(user.email);
}).catch(function(error)
As soon as user is created, the function will act (will do the data persistence in the database) and since it is not dependent on user auth'ed or not, along with unique emails, this step would never be repeated, hence single time data save in database. Had gone through the docs multiple times, somehow missed it. Apologies guys.
I am trying to make google plus login working for my website using gapi auth2 api.
The flow is like this:
User clicks on google+ button -> pop up to choose google account appears -> permission window (user allows/denies the permission to access account) -> I call my custom auth service using access_token provided by google -> login happens.
Everything else is working fine except for when user chooses the google account and then instead of allowing he clicks on 'Deny' button on permission window. In this case, I get the below exception:
I was expecting that when user denies the permission I will get a callback to my code from gapi but instead it fails.
Here is the code I wrote to do google+ login
gapi.client.setApiKey(config.apiKey);
var auth2 = gapi.auth2.getAuthInstance();
if (auth2 == undefined) {
auth2 = gapi.auth2.init({
client_id: config.clientId,
scope: config.scopes,
immediate: false
});
}
auth2.then(function() {
var options = new gapi.auth2.SigninOptionsBuilder();
options.setScope(config.scopes); // Set scopes
options.setPrompt('select_account consent'); // Get authorization from the user to access profile info
var signIn = gapi.auth2.getAuthInstance().signIn(options);
signIn.then(function() {
gapi.client.load('plus', 'v1', function() {
console.log("google plus api loaded.");
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
console.log(resp.displayName);
});
});
var authResult = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse();
if (authResult && !authResult.error) {
console.log("google auth success");
console.log(authResult.access_token);
var authService = new authServiceModel.authServiceResp({});
var formvalues = {};
formvalues.Method = 3;
formvalues.Source = 5;
formvalues.GoogleToken = authResult.access_token;
authService.fetch(formvalues);
} else {
if (authResult && authResult.error) {
console.error('Unable to sign in:', authResult.error);
}
console.log("google auth failed");
}
});
});
Here are the screenshots:
2.
3.
Click Deny.
Please look into the code and suggest what should I do to get a proper callback when 'Deny' button is clicked.
Thanks.
I have a phonegap app on iOS using firebase for authentication. Logging in is done like so:
var afterLogin = function(error, authData) {
if (error) {
console.log(error);
messenger.error(error.message);
return;
}
$scope.loggedIn = $auth.check();
$scope.$apply();
$sync.sync();
messenger.success('Logged in');
};
$scope.doLogin = function() {
mixpanel.track('login');
if (!$scope.loginForm.email && !$scope.loginForm.password) {
messenger.error('Enter email and password then tap login');
return;
} else if (!$scope.loginForm.email) {
messenger.error('Enter your email then tap login');
return;
} else if (!$scope.loginForm.password) {
messenger.error('Enter your password then tap login');
return;
}
ref.authWithPassword({
email : $scope.loginForm.email,
password : $scope.loginForm.password
}, afterLogin);
}
I check a user's status like this:
check: function() {
var authData = ref.getAuth();
if (authData) {
mixpanel.identify(authData.uid);
mixpanel.people.set({
"$email": authData.password.email
});
}
return !!authData;
}
It works fine initially, but users get signed out and have to log in again after 12-24 hours of not using the app. Perhaps when the app is shunted out of memory? Obviously this is pretty frustrating, not sure what's causing this. The session length is set to 24 weeks, still having the problem.
Firebase version: 2.1.2
Angular: 1.3.6
Log of localStorage after authenticating with username and password:
Coming back a day later after being logged out:
Contents of the cookie (same logged in or not, no firebase stuff in there):
It's a parameter in Firebase.
Go on the Dashboard of the Firebase.
Click on "Login & Auth".
Then in the first paragraph, there is an input and select for the Session Length. You can choose how many hours/weekks, etc you want.
I have the following JS code.
The code's purpose is to first get the users facebook id, and then using FQL check that id against my page ID and make sure the user is a fan.
The problem I am running into is that the only time the code actually works is if i login with my own personal facebook profile. I think its because my profile and the FB.init appid are somehow linked?
Can someone take a look at this code and show me where I am going wrong?
My goal again is to use JS to first get the users id (thus their thumbnail image), and then cross reference that against my own facebook page to check and see if they are a fan. If they are a facebook fan, then I will probably give them a coupon or something.
Thanks in advance.
<script src="http://connect.facebook.net/en_US/all.js"></script>
//Connect to facebook with my app id..
FB.init({
appId:'135445813195028',
cookie:false,
status:true,
xfbml:true
});
//Check to see if user is actually CONNECTED???
FB.getLoginStatus(function(response) {
if (response.session) {
// USER IS CONNECTED
FB.api('/me', function(user) {
if (user != null) {
var image = document.getElementById('imagez');
image.src = 'http://graph.facebook.com/' + user.id + '/picture?type=large';
var name = document.getElementById('name');
name.innerHTML = user.name;
FBID = user.id;
console.log('Facebook ID:' + FBID);
//assemble an FQL query to see if the guy is a fan of our page...
myquery = 'SELECT uid FROM page_fan WHERE page_id = 126923080686340 AND uid = ' + FBID;
console.log('query = ' + myquery);
///Run FQL Query to see if user is a fan
FB.api({
method: 'fql.query',
query: myquery
}, function(resp) {
if (resp.length) {
var IsFan = true;
alert('You are A fan!')
console.log('Visitor is a fan');
//show coupon code...
} else {
alert('Signed into facebook, but Not a fan!');
var IsFan = false;
console.log('Visitor is not a fan');
//show like button...
//once like is clicked then refresh the page...
}
});
//END Run FQL Query to see if user is a fan
}
});
//Figure out if they are a fan...
} else {
// USER IS NOT CONNECTED
alert('NO USER session, user is not logged into facebook!!!');
}
});
The FB.getLoginStatus check to see if the user is connected to your application .. not to facebook.
But when the user is not connected to your application, the .status property can tell you the reason of the fail (if the user is not logged-in at all, or just to your app).
So the structure you should use is
FB.getLoginStatus(function(response) {
if(response.session) {
alert('connected to Application');
} else {
// no user session available, someone you dont know
if(response.status == "notConnected") {
// But user is logged into facebook
alert("Not connected to Application, but is logged in to Facebook");
} else {
// User is not logged into facebook
alert('Not logged in to facebook');
}
}
});
But you cannot access the ID of a user that has not authorized your Application.
Not through Javascript API.