Polymer.js + OAuth2 - ajax

Is there an example out there which describes how to implement an OAuth2 authentication in the frontend based on Polymer.js?
I just found some examples that describe the procedure for AJAX, which is also part of the Polymer element set. So how to go on ahead?

I found a git repo here which have demo. So you can take a look.
<oauth-user></oauth-user>
<polymer-element name="oauth-user">
<template>
<oauth-authenticator id="authenticator" client_id="282331888208-06mufq54k942624lv803nlm6kvlq76fr.apps.googleusercontent.com" scopes="https://www.googleapis.com/auth/userinfo.profile" on-authenticated="{{authenticated}}"></oauth-authenticator>
<core-ajax auto id="ajax" url="{{url}}" headers="{{headers}}" handleAs="json" on-core-response="{{ajaxResponse}}"></core-ajax>
<p>{{greeting}}</p>
</template>
<script>
Polymer({
url: '',
greeting: '...',
authenticated: function(event){
var token = event.detail.token;
this.headers = {'Authorization': 'Bearer ' + token};
this.url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json";
},
ajaxResponse: function(event, response) {
this.greeting = 'Hello ' + response.response.name + '!';
}
});
</script>
</polymer-element>
You can see there're event handler so you can redirect user or update screen. There're also a url to get user info.

Related

broadcast to others and dont broadcast to current user are not working

In my TaskList.vue I have the code below:
<template>
<div>
<ul>
<li v-for="task in tasks" v-text="task"></li>
</ul>
<input type="text" v-model="newTask" #blur="addTask">
</div>
</template>
<script>
export default {
data(){
return{
tasks: [],
newTask: ''
}
},
created(){
axios.get('tasks')
.then(
response => (this.tasks = response.data)
);
Echo.channel('task').listen('TaskCreated', (data) => {
this.tasks.push(data.task.body);
});
},
methods:{
addTask(){
axios.post('tasks', { body: this.newTask })
this.tasks.push(this.newTask);
this.newTask = '';
}
}
}
</script>
When I hit the axios.post('tasks') end point, I got duplicate result in my current tab that i input the value and the another tab got only 1 value which is correct.
To avoid this, I tried to use
broadcast(new TaskCreated($task))->toOthers();
OR
I put $this->dontBroadcastToCurrentUser() in the construct of my TaskCreated.php
However, both methods are not working. Any idea why?
The image below is from network tab of mine. One of it is pending, is that what caused the problem?
https://ibb.co/jpnsnx (sorry I couldn't post image as it needs more reputation)
I solved this issue on my Laravel Spark project by manually sending the X-Socket-Id with the axios post.
The documentation says the header is added automatically if you're using vue and axios, but for me (because of spark?) it was not.
Below is an example to show how I manually added the X-Socket-Id header to an axios post using the active socketId from Laravel Echo:
axios({
method: 'post',
url: '/api/post/' + this.post.id + '/comment',
data: {
body: this.body
},
headers: {
"X-Socket-Id": Echo.socketId(),
}
})
Laravel looks for the header X-Socket-ID when using $this->dontBroadcastToCurrentUser(); Through this ID, Laravel identifies which user (current user) to exclude from the event.
You can add an interceptor for requests in which you can add the id of your socket instance to the headers of each of your requests:
/**
* Register an Axios HTTP interceptor to add the X-Socket-ID header.
*/
Axios.interceptors.request.use((config) => {
config.headers['X-Socket-ID'] = window.Echo.socketId() // Echo instance
// the function socketId () returns the id of the socket connection
return config
})
window.axios.defaults.headers.common['X-Socket-Id'] = window.Echo.socketId();
this one work for me..!!

Instagram API with more than 20 images

I wanted to ask you, if there is any possibility to get more than 20 full-res images from Instagram, using the API.
<script type="text/javascript">
var feed = new Instafeed({
get: 'user',
userId: '2201292293',
clientId: 'MY_CLIENT_ID',
accessToken:`'MY_ACCESS_TOKEN',
limit: '364',
sortBy: 'most-liked',
template: '<img src="{{image}}">{{likes}}',
resolution: 'standard_resolution'
});
feed.run();
Thank you in advance, Laurenz Strauch
It may be caused by pagination.
Add
<button id="load-more">
Load more
</button>
to your html. Every time you click on the button, feed.next() will be called and fetches more images if they exist.
<script type="text/javascript">
var loadButton = document.getElementById('load-more');
var feed = new Instafeed({
get: 'user',
userId: '2201292293',
clientId: 'MY_CLIENT_ID',
accessToken:`'MY_ACCESS_TOKEN',
limit: '364',
sortBy: 'most-liked',
template: '<img src="{{image}}">{{likes}}',
resolution: 'standard_resolution'
// every time we load more, run this function
after: function() {
// disable button if no more results to load
if (!this.hasNext()) {
loadButton.setAttribute('disabled', 'disabled');
}
},
});
// bind the load more button
loadButton.addEventListener('click', function() {
feed.next();
});
// run our feed!
feed.run();
</script>
Try this code.

How to by pass authentication in google analytics script?

I would like to display a Google Analytics report in my web application. So far I have successfully Authenticated a user through OAuth with server side and I have successfully stored AccessToken and UserProfileId in my database Table.
Now I want to display Chart like Below:
Here is the script which I have taken from the source to display above chart: Embeded API demo
Script:
gapi.analytics.auth.authorize({
container: 'embed-api-auth-container',
clientid: 'REPLACE WITH YOUR CLIENT ID', // i dont want to authenticate here as i have already done authentication.instead use access token to by pass this
authentication
});
So is it possible to not authenticate user with this script and still display google analytics chart for login user??
I have search on internet and I found below link somewhat useful in which Philip Walton answer is saying that it is possible: Google Analytics Embed API authentication
So if anybody have done this then please do provide any solution.
I found this option Embed API - Component Reference from this link which solved my issue:
I just needed to set the access_token:
gapi.analytics.auth.authorize({
serverAuth: {
access_token: 'XXXXXX'
}
});
try this using JavaScript sdk
<!DOCTYPE html>
<html>
<head>
<title>Embed API Demo</title>
</head>
<body>
<!-- Step 1: Create the containing elements. -->
<section id="auth-button"></section>
<section id="view-selector"></section>
<section id="timeline"></section>
<hr/>
<section id="chart-1-container"></section>
<!-- Step 2: Load the library. -->
<script>
(function(w,d,s,g,js,fjs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));
</script>
<script>
gapi.analytics.ready(function() {
// Step 3: Authorize the user.
var CLIENT_ID = 'xxxxxxxxxxx-xxxx.apps.googleusercontent.com';
//gapi.analytics.auth.authorize({
// container: 'auth-button',
// clientid: CLIENT_ID,
//});
gapi.analytics.auth.authorize({
'serverAuth': {
'access_token': 'xx.xxxxx-xxxxxxxxxx_xxxxxxx'
}
});
// Step 4: Create the view selector.
var viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector'
});
// Step 5: Create the timeline chart.
var timeline = new gapi.analytics.googleCharts.DataChart({
reportType: 'ga',
query: {
'dimensions': 'ga:date',
'metrics': 'ga:users',
'start-date': '30daysAgo',
'end-date': 'yesterday',
},
chart: {
type: 'LINE',
container: 'timeline'
}
});
var dataChart1 = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': 'ga:xxxxxxxx', // <-- Replace with the ids value for your view.
'start-date': '30daysAgo',
'end-date': 'yesterday',
'metrics': 'ga:sessions,ga:users',
'dimensions': 'ga:date'
},
chart: {
'container': 'chart-1-container',
'type': 'LINE',
'options': {
'width': '100%'
}
}
});
dataChart1.execute();
// Step 6: Hook up the components to work together.
gapi.analytics.auth.on('success', function(response) {
viewSelector.execute();
});
viewSelector.on('change', function(ids) {
var newIds = {
query: {
ids: ids
}
}
timeline.set(newIds).execute();
});
});
</script>
</body>
</html>

How to use pagination for displaying circles from Google+

I have set maxResults to 10 and i want to know how to use view more circles with nextpageToken and by clicking View More button the next 10 circles have to display and goes on till the last circles in Google+. Please help me fix this issue.
Please see my code below :
<html>
<head>
<title>Google+ JavaScript Quickstart</title>
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
<!-- JavaScript specific to this application that is not related to API
calls -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" ></script>
</head>
<body>
<div id="gConnect">
<button class="g-signin"
data-scope="https://www.googleapis.com/auth/plus.login"
data-requestvisibleactions="http://schemas.google.com/AddActivity"
data-clientId="my client id"
data-callback="onSignInCallback"
data-theme="dark"
data-cookiepolicy="single_host_origin">
</button>
</div>
<div id="authOps" style="display:none">
<h2>User is now signed in to the app using Google+</h2>
<p>If the user chooses to disconnect, the app must delete all stored
information retrieved from Google for the given user.</p>
<button id="disconnect" >Disconnect your Google account from this app</button>
<h2>User's profile information</h2>
<div id="profile"></div>
<h2>User's friends that are visible to this app</h2>
<div id="visiblePeople"></div>
<p>View More</p>
<h2>Authentication Logs</h2>
<pre id="authResult"></pre>
</div>
</body>
<script type="text/javascript">
var helper = (function() {
var BASE_API_PATH = 'plus/v1/';
return {
/**
* Hides the sign in button and starts the post-authorization operations.
*
* #param {Object} authResult An Object which contains the access token and
* other authentication information.
*/
onSignInCallback: function(authResult) {
gapi.client.load('plus','v1', function(){
$('#authResult').html('Auth Result:<br/>');
for (var field in authResult) {
$('#authResult').append(' ' + field + ': ' +
authResult[field] + '<br/>');
}
if (authResult['access_token']) {
$('#authOps').show('slow');
$('#gConnect').hide();
helper.profile();
helper.people();
} else if (authResult['error']) {
// There was an error, which means the user is not signed in.
// As an example, you can handle by writing to the console:
console.log('There was an error: ' + authResult['error']);
$('#authResult').append('Logged out');
$('#authOps').hide('slow');
$('#gConnect').show();
}
console.log('authResult', authResult);
});
},
/**
* Calls the OAuth2 endpoint to disconnect the app for the user.
*/
disconnect: function() {
// Revoke the access token.
$.ajax({
type: 'GET',
url: 'https://accounts.google.com/o/oauth2/revoke?token=' +
gapi.auth.getToken().access_token,
async: false,
contentType: 'application/json',
dataType: 'jsonp',
success: function(result) {
console.log('revoke response: ' + result);
$('#authOps').hide();
$('#profile').empty();
$('#visiblePeople').empty();
$('#authResult').empty();
$('#gConnect').show();
},
error: function(e) {
console.log(e);
}
});
},
/**
* Gets and renders the list of people visible to this app.
*/
people: function() {
var request = gapi.client.plus.people.list({
'userId': 'me',
'collection': 'visible',
'selfLink':'http://localhost/Google+/trail+.html',
'maxResults':10,`enter code here`
'items[]' : 'list',
'nextPageToken': 'CAIQ0K3cq5DEtAIgAygB'
});
request.execute(function(people) {
$('#visiblePeople').empty();
$('#visiblePeople').append('Number of people visible to this app: ' +
people.totalItems + '<br/>');
for (var personIndex in people.items) {
person = people.items[personIndex];
$('#visiblePeople').append('<img src="' + person.image.url + '">');
$('#visiblePeople').append(''+ person.displayName + '</br>'+ '</br>');
}
});
},
/**
* Gets and renders the currently signed in user's profile data.
*/
profile: function(){
var request = gapi.client.plus.people.get( {'userId' : 'me'} );
request.execute( function(profile) {
$('#profile').empty();
if (profile.error) {
$('#profile').append(profile.error);
return;
}
$('#profile').append(
$('<p><img src=\"' + profile.image.url + '\"></p>'));
$('#profile').append(
$('<p>Hello ' + profile.displayName + '!<br />Tagline: ' +profile.tagline + '!<br />Email id: ' +profile.email +
+ '<br />About: ' + profile.aboutMe + '</p>'));
if (profile.cover && profile.coverPhoto) {
$('#profile').append(
$('<p><img src=\"' + profile.cover.coverPhoto.url + '\"></p>'));
}
});
}
};
})();
/**
* jQuery initialization
*/
$(document).ready(function() {
$('#disconnect').click(helper.disconnect);
if ($('[data-clientid="YOUR_CLIENT_ID"]').length > 0) {
alert('This sample requires your OAuth credentials (client ID) ' +
'from the Google APIs console:\n' +
' https://code.google.com/apis/console/#:access\n\n' +
'Find and replace YOUR_CLIENT_ID with your client ID.'
);
}
});
/**
* Calls the helper method that handles the authentication flow.
*
* #param {Object} authResult An Object which contains the access token and
* other authentication information.
*/
function onSignInCallback(authResult) {
helper.onSignInCallback(authResult);
}
function getMore()
{
helper.people();
}
</script>
</html>
It looks like there may be a couple of issues here. You seem to have at least some of the gist of how to use people.list, but you seem to be trying to add some of the response fields to the request field. See https://developers.google.com/+/api/latest/people/list for full details of the request parameters and the expected response.
On the first call, you only need to pass the userId and collection parameters. Since you want to limit the page size, you'll need to pass maxResults as well, so your call will look something like
var requestParams = {
'userId': 'me',
'collection': 'visible',
'maxResults': 10
};
gapi.client.plus.people.list( requestParams ).execute(peopleCallback);
The parameter passed to peopleCallback() will contain the results, including a nextPageToken, which you will need to pass on subsequent calls to get additional items. You can store this token in a global variable, or as an attribute in your helper object, and process the other fields you need. So it might look something like this:
peopleCallback: function(response){
nextPageToken = response.nextPageToken;
items.forEach(function(item){
$('#visiblePeople').append(''+person.displayName+'');
});
}
The next time the "List more" button is called, you need to include the nextPageToken as part of your request, so the call would look something more like this:
var requestParams = {
'userId': 'me',
'collection': 'visible',
'maxResults': 10,
'pageToken': nextPageToken
};
gapi.client.plus.people.list( requestParams ).execute(peopleCallback);
Subsequent calls will get a new nextPageToken which should be passed the next time you're making a call to continue getting the list.
I leave it as an exercise to determine the best way for you to handle the differences between these calls (passing a token vs not), initializing the visiblePeople list, and other issues specific to your code structure.
One important caveat on what you're trying to do, however. Your question title suggests that you're trying to get circles of a person - this will not give you that info. The people.list call will give you people, not circles, that a person is willing to publicly say are added to a circle. A user may choose to not provide this information, or may choose to only provide a subset of the information, and you will not know what specifically named circles a person may have been added to

Jquery Address Plugin Post issue

Hi I am learning to use the Jquery Address plugin, and am using the tutorial over
here
So here is the html
Test 1<br />
Test 2
Load Area: <br />
<div id="area"></div>
And here is the Jquery code
function loadURL(url) {
$("#area").load(url);
}
// Event handlers
$.address.init(function(event))
.change(function(event) {
$("#area").load($('[rel=address:' + event.value + ']').attr('href'));
})
$('a').click(function(){
loadURL($(this).attr('href'));
});
Now this works well. However I want to do a POST call on the back button. So I replace
$("#area").load($('[rel=address:' + event.value + ']').attr('href'));
with
var myhref = $('[rel=address:' + event.value + ']').attr('href');
$.post(myhref, function(data) {
$('#area').html(data);
});
This throws the console error "this.value is not a function".
Considering my very superficial knowledge of Jquery (& programming in general), what am I doing wrong here?
Aw man I wish someone could answer this. I've been trying to get this thing to POST for a day now.. It just wants to get everything it seems, but I am at a loss of how I would tweak it to post.
function loadURL(url) {
$.post(url, function(data){
$("#area").html(data);
})
}
// Event handlers
$(document).ready(function(){
$("a").click(function(e){
e.preventDefault();
$.address.value($(this).attr("href"));
$.post($(this).attr("href"), function(data){
$("#area").html(data);
})
return false;
})
})
$(document).ready(function(){
$.address.init(function(event) { // Initates the address plugin
}).externalChange(function(event) { //externalChange is browser back/fwd button/address bar
if(event.path != "/"){
loadURL(event.path);
}
})
})

Resources