Good pic by Tim Rosenberg that shows exactly how OAUTH2 work's:
I'm kind a lazy to even start looking on this 2 files and test
so I searched for easyest way to
1.get token
2.access with that token
with help of gwt-oauth2
put it into index.php head :
<script type="text/javascript" src="gwt-oauth2.js"></script>
and this in body
<script type="text/javascript">
(function() {
var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
var GOOGLE_CLIENT_ID = "CLIENT_ID";
//var PLUS_ME_SCOPE = "https://www.googleapis.com/auth/plus.me";
//var FusionTable_SCOPE = "https://www.googleapis.com/auth/fusiontables";
var button = document.createElement("button");
button.innerText = "Authenticate with Google";
button.onclick = function() {
var req = {
'authUrl' : GOOGLE_AUTH_URL,
'clientId' : GOOGLE_CLIENT_ID,
'scopes': ['https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/fusiontables'
],
};
oauth2.login(req, function(token) {
alert('Got an OAuth token:\n'+ token +'\n'+ 'Token expires in '+ oauth2.expiresIn(req) +' ms\n');
}, function(error) {
alert("Error:\n" + error);
});
};
var dv = document.getElementById('admin-content');
dv.appendChild(button);
var clearTokens = document.createElement('button');
clearTokens.innerText = 'Clear all tokens'
clearTokens.onclick = oauth2.clearAllTokens;
dv.appendChild(clearTokens);
})();
</script>
OK,
Now you can see connection and redirection to oauthWindow.html in new window without errors. GET parameters now showing you access_token token_type expires_in. Check the access_token HERE
As you see access_token working great BUT
What you still don't get is first alert from that :
oauth2.login(req, function(token) {
alert('Got an OAuth token:\n' + token + '\n'
+ 'Token expires in ' + oauth2.expiresIn(req) + ' ms\n');
}, function(error) {
alert("Error:\n" + error);
});
Second alert works fine and when you try to Auth. again if oauthWindow.html still open it shows you an error alert(so it's working!)
Now let's add that little code to oauthWindow.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (window.opener && window.opener.oauth2 && window.opener.oauth2.__doLogin) {
window.opener.oauth2.__doLogin(location.hash);
} else {
document.body.innerText = "Your browser seems to be stopping this window from communicating with the main window.";
}
</script>
</head>
<body></body>
</html>
Perfect!
Now if you want to work with private tables all you need is to add an access_token to url.
Thanks for giving me the reason to answer myself!
Put this into oauthWindow.html file
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (window.opener && window.opener.oauth2 && window.opener.oauth2.__doLogin) {
window.opener.oauth2.__doLogin(location.hash);
} else {
document.body.innerText = "Your browser seems to be stopping this window from communicating with the main window.";
}
</script>
</head>
<body></body>
</html>
Related
I have arduino esp32 which i have sent data over mqtt to my cloudmqtt broker.
What it is sending is real time random numbers.
I can view these numbers on the cloudmqtt broker but i want it to be transferred to my webpage, so i researched and found some information on websockets.
This is the code i have currently:
<html>
<head>
<title>JavaScript MQTT WebSocket Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var mqtt;
var reconnectTimeout = 2000;
var host = "farmer.cloudmqtt.com"; //change this
var port = 37511;
var user = "foo";
var pass = "bar";
function MQTTconnect() {
console.log("connecting to " + host + " " + port);
mqtt = new Paho.MQTT.Client("farmer.cloudmqtt.com", 37511, "web_" + parseInt(Math.random() * 100, 10));
mqtt.onMessageArrived = onMessageArrived;
//document.write("connecting to "+ host);
var options = {
useSSL: true,
userName: "foo",
password: "bar",
onSuccess: onConnect,
onFailure: doFail
};
mqtt.connect(options); //connect
};
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("Connected ");
//mqtt.subscribe("sensor1");
message = new Paho.MQTT.Message("Hello world");
message.destinationName = "esp/test";
mqtt.send(message);
}
function doFail(e) {
console.log(e);
}
function onMessageArrived(message) {
console.log("onMessageArrived:" + message.payloadString);
}
</script>
</head>
<body>
<h1>Main Body</h1>
<script>
MQTTconnect();
</script>
</body>
</html>
But when i view my conosle it doesnt seem to work and gives error:
HTML1300: Navigation occurred.
webpage.html (1,1)
HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype: “”.
webpage.html (1,1)
connecting to farmer.cloudmqtt.com 37511
webpage.html (14,13)
0: Unspecified error.
mqttws31.min.js (28,16)
I am not sure why i get this error i dont see any errors in my code.
I am trying to create an API using a local server for testing. The ROUTES are working and I can add data to the OBJ using the URL from the browser. The issue is when I try to 'POST' the data through the HTML. I am getting back a 404 error. I developing using node.js and Express. What am I doing wrong?
JS on the server side
app.get('/add/:word/:score?', addWord);
//Function to request and send back the data
function addWord(request, response) {
var data = request.params;
var word = data.word;
var score = Number(data.score);
var reply;
if (!score) {
var reply = {
msg: 'Score is required'
}
response.send(reply);
} else {
words[word] = score;
// Transforms javascript object into raw data correctly idented with null, 2
var data = JSON.stringify(words, null, 2);
fs.writeFile('words.json', data, finished);
function finished(err) {
console.log('Writting');
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
}
POST method JS
$('#submit').on('click', function submitWord() {
var word = $('#fieldWord').val();
var score = $('#fieldScore').val();
$.ajax({
type: 'POST',
url: '/add/' + word + "/" + score,
success: function (newOrder) {
$list.append('<li>name: ' + newOrder.word + newOrder.score + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial API with node.js</title>
<script type="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p>
Word: <input type="text" id="fieldWord"><br/>
Score:<input type="text" id="fieldScore"><br/>
<button type="button" id ="submit">Submit</button>
<ul id="list">
</ul>
</p>
</body>
<script type="text/javascript" src="sketch.js"></script>
</html>
Thank you in advance.
I just signed up and want to test out the Websockets API to check on an address balance. Following the API docs, I was trying to see if I could get a proof of concept working, but I can't seem to get past the "success" message. Can someone take a look at this code and let me know what I'm doing wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Websocket Test</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script>
<script>
var connection = new WebSocket('wss://n.block.io/:443');
var message = {
"type": "account",
"api_key": "a40c-587d-e9a6-67d3",
"network": "BTC",
"type": "address",
"address": "13qUEUgSZRBqrXUyDghm1JhXMzJyrhA69h"
};
connection.onmessage = function(e){
var server_message = e.data;
console.log(server_message);
}
connection.onopen = function(){
connection.send(message);
}
</script>
</body>
</html>
https://block.io/docs/notifications
Sorry for the late reply but you need to JSON.stringify your message. Try something like this:
https://jsfiddle.net/bxw3v8c7/
<html>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var btcs = new WebSocket('wss://n.block.io/');
btcs.onopen = function()
{
var addrToMonitor = "1SomeBTCAddress";
btcs.send( JSON.stringify( {'type':'address','network':'BTC', 'address':addrToMonitor} ) );
};
btcs.onmessage = function(onmsg)
{
var response = JSON.parse(onmsg.data);
console.log(response); //for debugging
var amount = response.data.amount_received;
$('#messages').prepend("<p>" + amount + "</p>");
}
</script>
<body>
</body>
</html>
i have an html file called room.html.erb which has some js code.when i click on a link it has to load the above page.but the page is loading correctly except js code.when i refresh it working fine.
code in room.html.erb
<script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>
<script>
var apiKey = xxxxxx;//my apikey
var sessionId ="<%=#group.sessionId%>" ;
var token = "<%=#opentok_token%>";
var session;
OT.setLogLevel(OT.DEBUG);
session = OT.initSession(apiKey,sessionId);
session.on
({
streamCreated: function(event)
{
session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
}
});
session.connect(token,function(error){
if(error)
{
console.log(error.message);
}
else{
session.publish('myPublisherDiv',{width: 320,height: 240});
}
});
</script>
i couldn't able to figure it out why it is happening.
Wait until the DOM is loaded?
<script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
var apiKey = xxxxxx;//my apikey
var sessionId ="<%=#group.sessionId%>" ;
var token = "<%=#opentok_token%>";
var session;
OT.setLogLevel(OT.DEBUG);
session = OT.initSession(apiKey,sessionId);
session.on
({
streamCreated: function(event)
{
session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
}
});
session.connect(token,function(error){
if(error)
{
console.log(error.message);
}
else{
session.publish('myPublisherDiv',{width: 320,height: 240});
}
});
});
</script>
another method
add
<div id="myPublisherDiv"></div>
<div id="subscribersDiv"></div>
i have take google signin in my website :
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
//console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
//console.log('Image URL: ' + profile.getImageUrl());
//console.log('Name: ' + profile.getName());
//console.log('Email: ' + profile.getEmail());
var user_uname = profile.getName();
var user_email = profile.getEmail();
alert(user_uname);
}
</script>
and here is a button to login google:
<div class="g-signin2" data-onsuccess="onSignIn"></div>
i want to give user google signin but the problem is whenever page is load onSignIn() function is called automatically.
i want it only on button click. can anybody help me?
Best solution is to render sign-in button only when user is not signed in.
<html>
<head>
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID">
</head>
<body>
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var user_name = profile.getName();
alert(user_name);
}
function onLoad() {
gapi.load('auth2,signin2', function() {
var auth2 = gapi.auth2.init();
auth2.then(function() {
// Current values
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
if (!isSignedIn) {
// Rendering g-signin2 button.
gapi.signin2.render('google-signin-button', {
'onsuccess': 'onSignIn'
});
}
});
});
}
</script>
<div id="google-signin-button"></div>
<script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
</body>
</html>
I done it by declaring global js variable as false
var isFirstGoogle = 0;
Then to check this variable
if(isFirstGoogle)
{
//wont enter here first time
}
isFirstGoogle = 1;
So next time when I click on button the above method will be called as now isFirstGoogle = 1;
Hope this help!! It's a temporary thing I know but it's working for me.