Can't get facebook user's email using facebook javascript sdk - javascript

I'm using facebook authentication on my website using javascript sdk. I can get my email and name but I can't get their email, if they're loging in, only their name (it's my fb developer app).
It asks for the login, in case no one is logged in on facebook yet but get nothing happens. If I put an alert where it's supposed to login to my app and it indeed returns the name, just not the email. But if it's me I get both. Why's that?
Here's my code:
<%-- Facebook conection script--%>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script> FB.init({
appId: '334351783684824',
cookie: true,
xfbml: true,
version: 'v2.8'
});
function fbAuthUser() {
FB.login(checkLoginStatus);;
}
function checkLoginStatus(response) {
if (response.status === 'connected') {
FB.api('/me', 'GET', { fields: 'email,name' }, function (response) {
alert(response.email + "; " + response.name);
Ajax(response.email, response.name);
});
}
}
function Ajax(expressao1, expressao2) {
var request = { email: expressao1, nome: expressao2 }
$.ajax({
url: 'login.aspx/LoginExterno',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(request),
dataType: 'json',
success: function (resp) {
window.location.href = resp.d;
},
error: function () { }
})
}
</script>
It's supposed to login and, after getting the data, use that ajax function to access a code behind c# function that redirects the user to the index, if he/she already has an account or to the registry if he/she doesn't have one. It doesn't even go in the Ajax function, because the email parameter is undefined, probably. But when both are present it does.
So, how can I get the email?

Ok, I finally got it. On on FB.Login function, I need to add the scope and the user has to give permission. On my code, it would be like:
FB.login(checkLoginStatus,{scope: 'email'});;

Related

CORS error when trying to post message

I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins within Yammer.
Whenever I try to post a message, however, I get the following error:
The strange thing is when it does the preflight it seems OK but as the error states I can't figure out why it isn't coming back in the CORS header as I have it registered within the Yammer Client area.
Here is the code for posting:
$scope.YammerPost = function (Yammer) {
var _token = Yammer.access_token.token;
var config = {
headers: {
'Authorization': 'Bearer ' + _token
}
};
$http.post('https://api.yammer.com/api/v1/messages.json', { body: 'blah blah', group_id: XXXXXXX }, config);
}
I call that scope variable in the view via a button click.
Here is the logic I use to sign the user in:
function checkYammerLogin() {
$scope.Yammer = {};
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response); //print user information to the console
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response);
}
});
}
}
);
}
I ended up finding the issue.
For some odd reason, every time I would try to use an $http post it would include an Auth token from AD (app using Azure AD for authentication).
I ended up using jQuery inside of my Angular scope function on the button click and it works as I can control the headers for the request.
$.ajax({
url: 'https://api.yammer.com/api/v1/messages.json',
type: 'post',
data: {
body: 'this is a test from jQuery using AngularJS',
group_id: <group_id>
},
headers: {
'Authorization': _token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Fixed the issue and I can now post.
If anyone sees any issues with this practice please let me know, still a little new to angular

Cakephp Ajax Login is loggin in even with wrong data

I have a simple html form to login outside my cake structure, I send the login data via jquery to my login function:
public function login() {
if ($this->request->is('ajax')) {
$this->request->data['Appuser']['password'] = Security::hash($this->request->data['password']);
$this->request->data['Appuser']['name'] = $this->request->data['name'];
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl(array('action' => 'returnUserData')));
}else{
$this->response->body(json_encode('Login failed!'));
}
}elseif($this->request->is('post')){
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}else{
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
The very strange thing is:
the login via post from /view/users/login.ctp form works perfectly!
When I try to login from "outside" via ajax, I am always logged in even with wrong access details and get the data from function 'returnUserData'
$('#login').click(function() {
$.ajax({
type: "POST",
url: '/api/login',
data: {
name: $("#username").val(),
password: $("#password").val()
},
success: function(data)
{
alert(data);
}
});
});
When I set a debug(); after if ($this->request->is('ajax')) I can see it, so the script seems to go into the right if section. But I don't get it, why the $this->Auth->login always return true...?

how to call web service rest based using ajax + jquery

I am calling web service on this url .
here is my code .
http://jsfiddle.net/LsKbJ/8/
$(document).ready(function () {
//event handler for submit button
$("#btnSubmit").click(function () {
//collect userName and password entered by users
var userName = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(userName, password);
});
});
//authenticate function to make ajax call
function authenticate(userName, password) {
$.ajax({
//the url where you want to sent the userName and password to
url: "",
type: "POST",
// dataType: 'jsonp',
async: false,
crossDomain: true,
contentType: 'application/json',
//json object to sent to the authentication url
data: JSON.stringify({
Ticket: 'Some ticket',
Data: {
Password: "1",
Username:"aa"
}
}),
success: function (t) {
alert(t+"df")
},
error:function(data){
alert(data+"dfdfd")
}
})
}
Response
**
**
It mean that I first call this method then call login method ?
Perhaps the message means that during development, while you are writing and testing the code, use the URL:
http://isuite.c-entron.de/CentronServiceAppleDemoIndia/REST/GetNewAuthentifikationTicket
rather than:
http://isuite.c-entron.de/CentronService/REST/Login
Because you don't need the application id for the development method. You can see from the error message that you are missing the application (gu)id
The guid '61136208-742B-44E4-B00D-C32ED26775A3' is no valid application guid
Your javascript needs to be updated to use new url http://isuite.c-entron.de/CentronServiceAppleDemoIndia/GetNewAuthentifikationTicket as per the backend sode team.
Also, even if you do this, your will not be able to get reply correctly since service requires cross domain configuration entries in web.config. You have to use this reference:http://encosia.com/using-cors-to-access-asp-net-services-across-domains/ and configure server's web.config in a way so that you can call it from cross domain.

Post Photo to Facebook Page not associated with User

I am building a website that will allow any authenticated Facebook user to post photos to a specific album associated with a Facebook page. I am using the JavaScript SDK for this task. This is the code I have so far:
window.fbAsyncInit = function () {
FB.init({
appId: "492414284132122",
status: true,
cookie: true,
xfbml: true,
channelUrl: "http://wineoclock.dev.mag/ClockMoments/channel.html"
});
};
function uploadPhoto() {
console.log("called uploadPhoto()...");
FB.login(function (response) {
if (response.authResponse) {
document.getElementById("access_token").value = FB.getAuthResponse()["accessToken'];
var form = document.getElementById("fbPhotoUpload");
var formData = new FormData(form);
// indicate to user that upload is in progress
document.getElementById("btnUpload").value = "Posting...";
document.getElementById("btnUpload").disabled = true;
// post photo to Facebook
$.ajax({
type: "POST",
// post to "Timeline Photos" album
url: "https://graph.facebook.com/283773431737369/photos",
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function (response, status, jqXHR) {
console.log("Status: " + status);
if (!response || response.error) {
alert("Error occured:" + response.error.message);
}
else {
document.getElementById("fbPhotoUpload").reset();
$("#ThanksModal").reveal();
}
document.getElementById("btnUpload").value = "Post Photo";
document.getElementById("btnUpload").disabled = false;
},
error: function (jqXHR, status, errorThrown) {
console.log("AJAX call error. " + status);
console.log("errorThrown: " + errorThrown);
},
complete: function (jqXHR, status) {
console.log("AJAX call complete. " + status);
}
});
}
else {
alert("Login failed: " + response.error);
}
});
}
Running the code above, I discovered that the selected image gets uploaded, but it is uploaded to Facebook account that is logged in. This is not what I wanted. I wanted to upload it to the target fan page (designated in the AJAX POST request), instead of the logged in user.
I have read on the Internet that I need to request a page access token, instead of a user access token. To do so I would need to log in as the target page, as described in the Facebook doc here.
Is there a way to retrieve the page access token without having to login as the administrator of the Facebook page? If required, can the login be done behind-the-scenes?
EDIT:
I think i misunderstood You; the process described at link i posted results in getting access token for ANY user, you only have to do this once.
I do strongly believe that this is not possible; if it would be doable, practically any app could post at any fanpage.
According to solution from here:Extending Facebook Page Access Token, You need have administrator privileges to convert your short-lived page access token to a long-lived (2 months actually instead of couple of hours). The whole process is well described at the link.

Fb.api post to user wall only on login

I would like to use fb.api to post on logged user, but just once. If I put this
var params = {};
params['message'] = 'gegeegeggegall! Check out www.facebook.com/trashcandyrock for more info.';
params['name'] = 'gegeggeeg - gegegege';
params['description'] = 'Check out Tegegegeg! Win merch by playing and reccomending to your friends.';
params['link'] = 'http://www.bblblba.com';
params['picture'] = 'http://summer-mourning.zoocha.com/uploads/thumb.png';
params['caption'] = 'Tgegegegeeg';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Published to stream - you might want to delete it now!');
}
});
It posts to users wall everytime he refreshes the site?
What to do?
What is triggering the FB.api call? If it's just code within a tag then it's going to run as soon as the browser gets to that point.
You could possibly store some sort of cookie value or something after the FB.api call then check it on page load, but that seems like more work than is probably needed.
Do you want him to post it only once, ever?
If so, you're going to need to create a "state". In order to do this, you could do it client sided (with cookies), or server sided (with a database).
Create a boolean variable named "posted", and store it in a cookie or in a database (since you're using javascript, it's probably easier to use a cookie).
var posted=getCookie("posted");
if(!posted)
{
//call the FB.api();
setCookie("posted", true, duration);
}
Definition of setCookie and getCookie: http://www.w3schools.com/JS/js_cookies.asp
You could run a FQL query and check to see if the message has already been posted by querying the stream table with your app id. Something like:
<!DOCTYPE html>
<html>
<body>
<div id="fb-root"></div>
Post To Wall
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({ appId : '**yourAppID**', status : true, cookie : true, xfbml : true });
function postToWall() {
FB.login(function(response) {
if (response.session) {
FB.api(
{
method: 'fql.query',
query: 'SELECT post_id, message from stream where app_id = **yourAppID** and source_id = me()'
},
function(response) {
if(response.length == 0){
FB.ui(
{
method: 'feed',
name: 'Facebook Dialogs',
link: 'https://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
caption: 'Reference Documentation',
description: 'Dialogs provide a simple, consistent interface for applications to interface with users.',
message: 'Facebook Dialogs are easy!'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
}
else {
alert('User already posted this message');
}
}
);
}
} , {perms:''});
}
</script>
</body>
</html>

Categories

Resources