How to get Access Token with JavaScript API dynamically - facebook-graph-api

I'm trying to publish an action for the Facebook Grahp in order to get my App approval..
Error:
Publish Actions
You must publish at least one action to your Timeline using this action type.
So I created a simple page to publish the action (I got the code form: Graph API) and it's this one:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="de-DE" xmlns:fb="https://www.facebook.com/2008/fbml">
<head prefix="og: http://ogp.me/ns# fashion_econtest: http://ogp.me/ns/apps/fashion_econtest#">
<title>Fashion</title>
<meta property="fb:app_id" content="MyAppId" />
<meta property="og:type" content="fashion:contest" />
<meta property="og:title" content="eContest" />
<meta property="og:image" content="The Image" />
<meta property="og:description" content="Registrati e vinci cli accessori più fashion dell'anno!" />
<meta property="og:url" content="MyURL">
<script type="text/javascript">
function postSubscribe(){
FB.api(
'/me/fashion:subscribe',
'post',
{share:'MyUrl'},
function(response){
if(!response){
alert('Error');
}else if(response.error) {
alert(response.error.message);
}else{
alert('Subscribe was successful! Action ID: ' + response.id);
}
});
}
</script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function(){
FB.init({
appId : 'MyAppId', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/it_IT/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<h3>Fashion</h3>
<p>
<img title="Vinci i premi più Fashion!" src="http://xxxxxx.de/img/yyyyyy.jpg" width="550"/>
</p>
<br>
<form>
<input type="button" value="Subscribe" onclick="postSubscribe();" />
</form>
</body>
But once I send the Request, I get the follwonig Error:
An active access token must be used to query information about the current user.
How can I get the Access Token with Java Script FB-API dynamically and make this working?
Many Thanks for your help!!
Amin

Facebook exchanges access_tokens automatically based on your application Id. I think you are looking for getting the currently active access_token using FB API methods.
Try FB.getLoginStatus API call. For more details see...
http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

Call FB.login first, and ask for the appropriate permission (publish_actions).
(Or just do the whole things using the Graph API explorer instead of writing a script for something you’ll only need once.)

Related

How can i send a post request using vue to django without getting a 403 error?

Im trying to send information using a post request of Vue, but every time i try i get an error 403 58
my django service is ok , i think that the problem is for the csrf token but i dont know how to send it with vue
var vue = new Vue({
el:"#app",
data: {
nombre:"",
apellido:"",
password:""
},
methods:{
enviar:function () {
data = {
"nombre":this.nombre,
"apelldio":this.apelldio,
"password":this.password
};
this.$http.post("http://localhost:8000/usuarios\\",data).then(function (data, status, request) {
if(status ==200){
console.log(data);
}
},function () {
console.log("Error");
});
}
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
</head>
<body>
<h1>Insertar un nuevo usuario </h1>
<table id = "app">
<tr><td>Nombre:</td><td><input type="texte" class="form-control" v-model="nombre"></td></tr>
<tr><td>Apellido:</td><td><input type="texte" class="form-control" v-model = "apellido"></td></tr>
<tr><td>Password:</td><td><input type="texte" class="form-control" v-model="password"></td></tr>
<tr> <td> <button type="button" id = "enviar" class="btn btn-info" #click="enviar">Enviar</button></td></tr>
</table>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script>
{% csrf_token %}
<!-- here goes the scripts of vue and vue resource!>
You could use a method that involves fetching the csrf token with javascript and then passing it to the POST request as a header as mentioned here in Django documentation. In that link there is also examples about fetching the csrf token value.
Also, if the endpoint does not require this kind of protection you can disable it like in this example.
You can use something like this:
{% csrf_token %}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script>
<script>
var csrf = document.querySelector('[name="csrfmiddlewaretoken"]').value;
Vue.http.interceptors.push(function (request, next) {
request.headers['X-CSRF-TOKEN'] = csrf;
next();
});
// Or maybe
Vue.http.headers.common['X-CSRF-TOKEN'] = csrf;
</script>
You can also use it like this, for example:
<script>
var csrf = '{{ csrf_token }}';
Vue.http.headers.common['X-CSRF-TOKEN'] = csrf;
// Or other way
// Vue.http.interceptors.push(...);
</script>
Note: I'm no django developer but gave you the basic idea, so check the doc for more info.

springMVC+thymleaf can not parse Message Expressions when use templateResolver to send email

the application.properties is
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
# set to false for hot refresh, should be set to true in deployment
spring.thymeleaf.cache=false
get template content is like this:
#Autowired
private ITemplateResolver templateResolver;
private String getMailContent(EmailDTO email, EmailType type) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
Context context = new Context(email.getLocale());
context.setVariable("email", email.getAddress());
return templateEngine.process("email/resetcontent", context);
}
the template is :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>SIM : Reset Password</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>
<body>
<span th:text="#{reset.password.title}">Reset Password</span>
<span th:text="${email}"></span>
</body>
</html>
th:text="${email}" can be parse but the th:text="#{reset.password.title}" is ??reset.password.title_en_US??
Project Structure
who can tell me why? thank you very much
if your using spring boot the default message resolver wil try to find the code "reset" for a "password" bean which have a "title" field.
you should use this code:
<span th:text="#{resetPasswordTitle}">Reset Password</span>

ember-auth sends OPTIONS requests instead of POST on my development machine

I have a Sinatra-based server which provides RESTful API for the service I'm working on. On my development machine in runs on localhost:9393.
At the same time my client application (built with ember.js) which uses ember-auth for user authentication runs on another port: localhost:9000.
Previously I set up both server and client on the same host:port and returned client app as static files. Authentication worked pretty well. According to the official docs on SignIn I get POST request on the route I provided (/signin). But now I recieve OPTIONS request with no params whatsoever.
Some code from client (client is generated via Yeoman's ember-generator):
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Ember Starter Kit</title>
<!-- build:css styles/main.css -->
<link rel="stylesheet" href="styles/normalize.css">
<link rel="stylesheet" href="styles/bootstrap.css">
<link rel="stylesheet" href="styles/bootstrap-responsive.css">
<link rel="stylesheet" href="styles/style.css">
<!-- endbuild -->
</head>
<body>
<!-- build:js scripts/components.js -->
<script src="components/jquery/jquery.js"></script>
<script src="components/handlebars/handlebars.runtime.js"></script>
<script src="components/ember/ember.js"></script>
<script src="components/ember-data/ember-data-latest.js"></script>
<script src="components/ember-auth/ember-auth.js"></script>
<!-- endbuild -->
<!-- build:js scripts/main.js -->
<script src="scripts/app.js"></script>
<script src="scripts/models/user.js"></script>
<script src="scripts/views/auth.js"></script>
<!-- endbuild -->
<!-- build:js(.tmp) scripts/templates.js -->
<script src="scripts/compiled-templates.js"></script>
<!-- endbuild -->
</body>
</html>
app.js
var App = window.App = Ember.Application.create();
App.Store = DS.Store.extend({
revision: 12,
adapter:'DS.RESTAdapter'
});
App.Router.map(function() {
// I have no routes so far,
// as I don't need them to test authentication itself
});
App.Auth = Ember.Auth.create({
signInEndPoint: '/signin',
signOutEndPoint: '/signout',
tokenKey: 'auth_token',
baseUrl: 'http://localhost:9393',
tokenIdKey: 'user_id',
userModel: 'App.User',
sessionAdapter: 'cookie',
modules: [
'emberData', 'rememberable'
],
rememberable: {
tokenKey: 'remember_token',
period: 7,
autoRecall: true
}
});
user.js
App.User = DS.Model.extend({
email: DS.attr('string'),
param: DS.attr('string')
});
auth.js
App.AuthView = Ember.View.extend({
templateName: 'auth'
});
App.AuthSignInView = Ember.View.extend({
templateName: 'signin',
email: null,
password: null,
remember: true,
submit: function(event, view){
event.preventDefault();
event.stopPropagation();
App.Auth.signIn({
data:{
email: this.get('email'),
password: this.get('password'),
remember: this.get('remember')
}
})
}
});
App.AuthSignOutView = Ember.View.extend({
templateName: 'signout',
submit: function(event, view){
event.preventDefault();
event.stopPropagation();
App.Auth.signOut();
}
});
application.hbs
<div class="container">
<div class="row">
<div class="span3">
{{view App.AuthView}}
</div>
<div class="span9">
{{outlet}}
</div>
</div>
</div>
auth.hbs
{{#if App.Auth.signedIn}}
{{view App.AuthSignOutView}}
{{else}}
{{view App.AuthSignInView}}
{{/if}}
signin.hbs
<form>
<label>Email</label>
{{view Ember.TextField valueBinding="view.email"}}
<label>Password</label>
{{view Ember.TextField type='password' valueBinding="view.password"}}
{{view Ember.Checkbox checkedBinding="view.remember"}}
<label>Remember me?</label>
<hr />
<button type="submit">Sign In</button>
</form>
Your REST API and client app are served from different origins; the protocol, host and port must be identical to follow same-origin policy. Your browser is making a preflight OPTIONS request to determine if your server will allow cross-origin resource sharing (CORS) from your client domain.
To get CORS working with your Sinatra server, you might want to check out rack-cors which will allow you to add middleware for setting the requisite access control headers. Once that is set up correctly, the expected POST request will be issued following the successful OPTIONS request.
For more on CORS, here are some resources I've found useful:
http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
http://remysharp.com/2011/04/21/getting-cors-working/
http://www.bennadel.com/blog/2327-Cross-Origin-Resource-Sharing-CORS-AJAX-Requests-Between-jQuery-And-Node-js.htm

Facebook Admin Link Missing

I recently created a facebook application for integrating a domain's webpages with facebook.
But I can't figure out why the Admin Link will not show on the webpage whilst logged into fb as the admin.
Reading the developer documentation can be a little confusing since there seem to be various methods of implementing the code required on each webpage. It is difficult to determine which namespace matches with which way to load the SDK and with which markup method.
I am attempting to do this for HTML5.
<!DOCTYPE HTML>
<!-- Whilst I have found many html namespace modifications for XFBML methods I did not see any requirements for html5 an d the following method -->
<html>
<!-- The head og namespace is taken from the fb developers app > open graph > object types > get code link -->
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# video: http://ogp.me/ns/video#">
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- The meta properties are also taken from the fb developers app > open graph > object types > get code link -->
<meta property="fb:app_id" content="APP ID NUMBER"/>
<meta property="og:type" content="video.movie" />
<meta property="og:url" content="http://www.domain.com/page.html"/>
<meta property="og:title" content="TITLE"/>
<meta property="og:description" content="DESCRIPTION."/>
<meta property="og:image" content="http://www.domain.com/og_thumb.jpg" />
<!-- The meta property here was not included with the above but is required according to https://developers.facebook.com/docs/reference/plugins/like/ -->
<meta property="og:site_name" content="SITE NAME" />
</head>
<body>
<!-- The following is the code given when using the "like" code generator from this page https://developers.facebook.com/docs/reference/plugins/like/ and selecting the "HTML5" option -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=APP ID NUMBER";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="http://www.domain.com/page.html" data-send="true" data-layout="button_count" data-width="0" data-show-faces="false" data-font="arial"></div>
</body>
</html>
Whilst logged in as the admin user of the fb app I am able to visit the admin for the page by looking up the page name/id and append them to a url like so:
http://www.facebook.com/pages/TITLE-OF-PAGE/GRAPH-ID-NUMBER
I noticed this bug that seems related:
https://developers.facebook.com/bugs/178579068908181/
I understand that when using fb:admins the admin must "like" a page before being able to see the Admin Link.
However I am assuming that when using fb:app_id that it should not be necessary to "like" the page.
What am I missing to enable the Admin Link for the webpage ?
You should use both fb:app_id and fb:admins in the OG Markup. Don't forget to use the debug tool to scrape the page again so facebook knows that the details have changes. The admin link will only show if you have the fb:admins on the page.
You don't have to like the page, you could always wait for a user to like the page. Facebook will then create the associated page once it has enough likes and the admin link will appear correctly.

Google Maps not working in Django template on App Engine development server

When I add this script to a plain HTML file's HEAD section
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
and I run this script on the body onload,
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
then I see the Google map just fine.
However, the same does not work when in a Django template. (Yes, I am new to Django :)
I get all the code in the initialize function to run, but no map shows up. Page stays blank.
I assume it has something to do with Django, and the GAE dev server, and how the Google Maps js API is referenced, but I don't know how to fix.
Thanx much.
Edit:
My Django template looks like this (There are no Django specific tags or anything yet.)
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
dir="ltr"
xml:lang="en"
lang="en">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="/site_media/css/reset.css" />
<link rel="stylesheet" type="text/css" href="/site_media/css/main.css" />
<script src="/site_media/js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
$(document).ready(function(event) {
initialize();
});
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
</script>
</head>
<body>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<center>
<div id="map_canvas" style="width:60%; height:70%;">Why the heck is the map not showing?</div>
</center>
</body>
</html>
And the rendered HTML source of that template from the browser looks like this:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
dir="ltr"
xml:lang="en"
lang="en">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title></title>
<link rel="stylesheet" type="text/css" href="/site_media/css/reset.css" />
<link rel="stylesheet" type="text/css" href="/site_media/css/main.css" />
<script src="/site_media/js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
$(document).ready(function(event) {
initialize();
});
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
</script>
</head>
<body>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<center>
<div id="map_canvas" style="width:60%; height:70%;">Why the heck is the map not showing?</div>
</center>
</body>
</html>
Your DOCTYPE is causing the problem. If I remove that from your code, then the map displays.
There are some threads on the Google Maps JavaScript API v3 Group that discuss this problem.
I don't think your problem is (directly) related to the GAE development server or Django - it looks like your page's HTML is loading just fine.
I suspect your problem may be the jQuery reference. Perhaps jQuery is not being loaded, and thus your script stops executing when it tries to access $(document) but fails because a ReferenceError is thrown.
I would check that your link to load the jQuery library is working by manually accessing it in your browser (i.e., browse to http://localhost:8080/site_media/js/jquery.min.js (or wherever you are running your development server) and make sure it works). If not, then fix your app.yaml file so that it is properly setup to serve /site_media/js/jquery.min.js.
I've had this I think and I fixed it by just doing the Google Maps initialize from google's own method:
google.setOnLoadCallback(initialize);
I know I tried to do this (by default) in jQuery's ready but that didn't work for some reason.