getting stuck ,Log in with facebook with firebase - javascript

i try to login with facebook in firebase using java script and html. i also create a facebook application and set app secret and app id in firebase dashbord.
and all the other setting in facebook app that firebase said in their doc
but im getting this.
<html>
<head>
<script src='https://cdn.firebase.com/js/client/2.0.4/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
</head>
<body>
<div id='messagesDiv'></div>
<input type='text' id='nameInput' placeholder='Name'>
<input type='text' id='messageInput' placeholder='Message'>
<script>
var myDataRef = new Firebase('https://fiery-inferno-9432.firebaseio.com/');
myDataRef.authWithOAuthPopup("facebook", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
myDataRef.authWithOAuthRedirect("facebook", function(error, authData) {
if (error) {
console.log("Ridi Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#nameInput').val();
var text = $('#messageInput').val();
myDataRef.push({name: name, text: text});
$('#messageInput').val('');
}
});
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text);
});
function displayChatMessage(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>
</body>
</html>
im getting
Login Failed! Error: There are no login transports available for the requested method.code: "TRANSPORT_UNAVAILABLE"message: "There are no login transports available for the requested method."stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }proto: dconstructor: function Error() { [native code] }message: ""name: "Error"toString: function toString() { [native code] }proto: Object

i found the problem. i must run the html file by running a file server
simply by this on cmd
python -m SimpleHTTPServer
and then run html by
http://localhost/test.html

From https://www.firebase.com/docs/web/guide/user-auth.html:
Note: Browser popups and redirects are not available on all platforms
or browser environments. Popups are not available in Chrome for iOS,
iOS Preview Panes, or local, file:// URLs.
Also, when authenticating via popup on PhoneGap / Cordova apps, including cordova.js and the InAppBrowser plugin in the scope of the page are both required.

I solved it by running my page via server on localhost instead of running the file directly from file system.

Related

"can't access property "getAuthInstance", gapi.auth2 is undefined" error while trying to use YouTube data API

so I'm kinda new to API and stuffs like this. Recently I've got a task to list videos from a specific Youtube channel. So the workaround I got is to first collect the id of uploads playlist, then get all videos from that playlist to show them. But the thing is I couldn't go so far, I first got the code from Googles API documentation, did some edits (my api key and stuff like this) and when I run I get this error:
Uncaught TypeError: can't access property "getAuthInstance", gapi.auth2 is undefined
here's the code i'm using (i'll delete my API Key, so don't think its the error):
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for youtube.channels.list
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({
scope: "https://www.googleapis.com/auth/youtube.readonly"
})
.then(function() {
console.log("Sign-in successful");
},
function(err) {
console.error("Error signing in", err);
});
}
function loadClient() {
gapi.client.setApiKey("my API key was here");
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() {
console.log("GAPI client loaded for API");
},
function(err) {
console.error("Error loading GAPI client for API", err);
});
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.youtube.channels.list({
"part": [
"contentDetails"
],
"id": [
"My Channel ID was here"
]
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) {
console.error("Execute error", err);
});
}
/*gapi.load("client:auth2", function() {
gapi.auth2.init({
client_id: "YOUR_CLIENT_ID"
});
});*/
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
from the looks of the error it seea ms to me that there's problem with api.js library or maybe there supposed to be another function I need to execute before calling getAuthInstance. I don't have any idea what is happening so hopefully someone can explain to me what is happening, thanks
I don't know much about this stuff myself so I went to the docs and found this section for you:
https://developers.google.com/identity/sign-in/web/reference#gapiauth2getauthinstance
Turns out you need to initialise auth first - the bit you've commented out at the bottom of your code:
/*gapi.load("client:auth2", function() {
gapi.auth2.init({
client_id: "YOUR_CLIENT_ID"
});
});*/
Give that a test and see what you get :D

Log minified JavaScript errors in production code

I am running a back-end app with a React JS frontend on our intranet. I don't want to use services like Sentry or Rollbar to keep track of minified code in production because I don't want to upload our source-maps externally.
Are there any self-hosted solutions for tracking & logging errors in JS source-maps?
We are using a combination of JSNLog and Stacktrace. This is what goes into the <head> of your index.html:
<script src="~/js/jsnlog.min.js"></script>
<script src="~/js/stacktrace.min.js"></script>
<script src="~/js/stacktraceConfig.js"></script>
And below the contents of stacktraceConfig.js:
window.onerror = function (msg, file, line, col, error) {
var callback = function (stackframes) {
var stringifiedStack = stackframes.map(function (sf) {
return sf.toString();
}).join('\n');
JL('serverLog').fatalException({
msg: 'Exception! ' + stringifiedStack,
1: '--------------------------------------------------------------',
errorMsg: msg,
url: stackframes[0].fileName + ":" + stackframes[0].lineNumber,
functionName: stackframes[0].functionName,
lineNumber: stackframes[0].lineNumber,
column: stackframes[0].column,
x: '--------------------------------------------------------------',
}, error);
};
var errback = function (err) { console.log(err.message); };
StackTrace.fromError(error).then(callback).catch(errback);
// Tell browser to run its own error handler as well
return false;
};
You will have to configure JSNLog yourself to have it send the errors by mail.

Keycloak login returns 404 using JavaScript adapter

I'm using Keycloak's bower package to create a very basic demo HTML/JS app. I have Keycloak running locally and keycloak.init() seems to work (no error triggered). However when I call keycloak.login() a 404 is returned. Might the login URL be wrongly created by the adapter?
The URL returned by keycloak.createLoginUrl() is
https://<keycloak url>/realms/<realm>/protocol/openid-connect/auth?client_id=account&redirect_uri=file%3A%2F%2F%2FUsers%2Fjgallaso%2FProjects%2Fdemos%2Fkeycloak-simple-web-client%2Findex.html&state=b167dc0b-3e5b-4c67-87f7-fd5289fb7b8f&nonce=1e2cb386-51db-496a-8943-efcf4ef5d5e1&response_mode=fragment&response_type=code&scope=openid
And this is my entire code:
<head>
<script src="bower_components/keycloak/dist/keycloak.min.js"></script>
</head>
<body>
<button id="login">Login</button>
</body>
<script>
var keycloak = Keycloak({
url: 'https://keycloak-keycloak.192.168.37.1.nip.io',
realm: 'demo',
clientId: 'account'
});
keycloak.init()
.success(authenticated => {
document.getElementById("login")
.addEventListener("click", () => { keycloak.login(); });
}).error(err => {
console.log("init, error: " + err);
});
</script>
</head>
Response is a plain:
ERROR 404: Not Found
You have 2 posibilities :
invoque login automatically in init method
login manually after call init without params
1)
<head>
<script src="bower_components/keycloak/dist/keycloak.min.js"></script>
</head>
<body>
<button id="login">Login</button>
</body>
<script>
var keycloak = Keycloak({
url: 'https://keycloak-keycloak.192.168.37.1.nip.io',
realm: 'demo',
clientId: 'account'
});
keycloak.init('login-required')
.success(function(authenticated) => {
}).error(err => {
console.log("init, error: " + err);
});
</script>
</head>
2)
keycloak.init().success(function(authenticated) {
if(authenticated == true){
alert('usuario logeado');
}else{
alert('usuario no logeado');
keycloak.login();
}
}).error(function() {
alert('failed to initialize');
});
I had trouble trying directly from the management.
file://c:/example.html
To do a better test you should leave your index.html on a local test server.
What I did was install the web server plugin for chrome and it worked for me.
I hope it'll help you.
regards

Twitter authentication in Codebird JS

I am very new to integrating social sites into a website. I somewhat managed to integrate Facebook, but I have no idea how to integrate Twitter.
I want to login through a Twitter account, then get the username and some other data from Twitter. I have a consumer key and consumer secret. I'm not sure how to proceed from here, and my Google searches haven't helped so far.
I am trying with codebird js:
$(function() {
$('#twitter').click(function(e) {
e.preventDefault();
var cb = new Codebird;
cb.setConsumerKey("redacted", "redacted");
cb.__call(
"oauth_requestToken",
{ oauth_callback: "http://127.0.0.1:49479/" },
function (reply, rate, err) {
if (err) {
console.log("error response or timeout exceeded" + err.error);
}
if (reply) {
// stores it
cb.setToken(reply.oauth_token, reply.oauth_token_secret);
// gets the authorize screen URL
cb.__call(
"oauth_authorize",
{},
function (auth_url) {
window.codebird_auth = window.open(auth_url);
}
);
}
}
);
cb.__call(
"account_verifyCredentials",
{},
function(reply) {
console.log(reply);
}
);
})
});
But I get
Your credentials do not allow access to this resource
How can I resolve this and get the user data? I am open to using an alternate Twitter implementation.
You cannot call cb._call( "account_verifyCredentials"... there.
The code only has a request token, NOT an access token, which you will only receive after the user authorizes your app (on the Twitter auth popup).
You are using the "callback URL without PIN" method, as documented on the README. So you'll need to implement that example code on your http://127.0.0.1:49479/ page.
Also, this essentially requires that you store the oauth credentials somewhere. In my example below, I've used localStorage.
$(function () {
$('#twitter').click(function (e) {
e.preventDefault();
var cb = new Codebird;
cb.setConsumerKey("CeDhZjVa0d8W02gWuflPWQmmo", "YO4RI2UoinJ95sonHGnxtYt4XFtlAhIEyt89oJ8ZajClOyZhka");
var oauth_token = localStorage.getItem("oauth_token");
var oauth_token_secret = localStorage.getItem("oauth_token_secret");
if (oauth_token && oauth_token_secret) {
cb.setToken(oauth_token, oauth_token_secret);
} else {
cb.__call(
"oauth_requestToken", {
oauth_callback: "http://127.0.0.1:49479/"
},
function (reply, rate, err) {
if (err) {
console.log("error response or timeout exceeded" + err.error);
}
if (reply) {
console.log("reply", reply)
// stores it
cb.setToken(reply.oauth_token, reply.oauth_token_secret);
// save the token for the redirect (after user authorizes)
// we'll want to compare these values
localStorage.setItem("oauth_token", reply.oauth_token);
localStorage.setItem("oauth_token_secret", reply.oauth_token_secret);
// gets the authorize screen URL
cb.__call(
"oauth_authorize", {},
function (auth_url) {
console.log("auth_url", auth_url);
// JSFiddle doesn't open windows:
// window.open(auth_url);
$("#authorize").attr("href", auth_url);
// after user authorizes, user will be redirected to
// http://127.0.0.1:49479/?oauth_token=[some_token]&oauth_verifier=[some_verifier]
// then follow this section for coding that page:
// https://github.com/jublonet/codebird-js#authenticating-using-a-callback-url-without-pin
});
}
});
}
})
});
Also made a JSFiddle

Using Facebook request dialog with Meteor

I'm trying to send an "app" invite to user friends using the Facebook JavaScript SDK.
Here is a template event when click the Facebook button:
"click #fb": function (e, tmp) {
Meteor.loginWithFacebook({
requestPermissions: ['user_likes',
'friends_about_me',
'user_birthday',
'email',
'user_location',
'user_work_history',
'read_friendlists',
'friends_groups',
'user_groups']
}, function (err) {
if (err) {
console.log("error when login with facebook " + err);
} else {
FB.api('/' + Meteor.user().services.facebook.id + '/friends', { fields: 'name,picture' }, function (response) {
if (response && response.data) {
friends = response.data;
friends_dep.changed();
}
});
}
});
}
after that i want the user to invite people to my app, my code looks like this (another template event):
FB.ui({method: 'apprequests',
message: 'My Great Request'
}, function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
And it's working. There is a Facebook dialog with all the user friends, but when trying to send the message, I get the response error = 'Post was not published.'
What am I doing wrong here?
Basically the user can build a group - and I want the user to be able to invite his facebook friends into that group. Is there anyway that when sending the request the reciver will just press "yes" and will be automatically added to the sender group?
note I'm using my local machine aka localhost:3000
Can you try removing the && response.post_id portion from the if statement?
According to the Facebook API docs for the Requests Dialog: https://developers.facebook.com/docs/reference/dialogs/requests/ the response will just have 'request' and 'to' data. It looks like you've copy and pasted your callback from an example they give for the Posts Dialog. If you still get an error after removing this then you aren't getting a response, I am unsure how the JS SDK handles responses. If you can get other API calls to work using js sdk then I'm really not sure.
I recently worked with the Facebook API and opted not to use the JS SDK because it seemed to be at odds with using the accounts-facebook package. I'm curious if you're using that too.
Some Facebook API calls like creating a Post (and possibly this one) do require a dialog box, I'll outline how I got around this without using the JS SDK in case it helps you or anyone else. I would just form the URL client side and open a popup window e.g. here's how I handled sending a post:
'click .send-message': function() {
var recipient = this.facebook_id;
var config = Accounts.loginServiceConfiguration.findOne({service: 'facebook'});
var url = "http://www.facebook.com/dialog/feed?app_id=" + config.appId +
"&display=popup&to=" + recipient + "&redirect_uri=" + Meteor.absoluteUrl('_fb?close');
window.open(url, "Create Post", "height=240,width=450,left=100,top=100");
}
Then to get the response server side:
WebApp.connectHandlers
.use(connect.query())
.use(function(req, res, next) {
if(typeof(Fiber)=="undefined") Fiber = Npm.require('fibers');
Fiber(function() {
try {
var barePath = req.url.substring(0, req.url.indexOf('?'));
var splitPath = barePath.split('/');
if (splitPath[1] !== '_fb') {
return next();
}
if (req.query.post_id) {
//process it here
}
res.writeHead(200, {'Content-Type': 'text/html'});
var content = '<html><head><script>window.close()</script></head></html>';
res.end(content, 'utf-8');
} catch (err) {
}
}).run();
});
This code is very similar to the code used in the oauth packages when opening the login popup and listening out for responses.

Categories

Resources