I'm trying to get my first dapp working; I know I'm close, but keep running into a problem with web3.
I am working on Windows 10, running a testrpc node via PowerShell. I used truffle to set up my folders & sample files, then compile and migrate.
I don't think I changed anything from the app.js file built by truffle... here is that code:
var accounts;
var account;
function setStatus(message) {
var status = document.getElementById("status");
status.innerHTML = message;
};
function refreshBalance() {
var meta = MetaCoin.deployed();
meta.getBalance.call(account, {from: account}).then(function(value) {
var balance_element = document.getElementById("balance");
balance_element.innerHTML = value.valueOf();
}).catch(function(e) {
console.log(e);
setStatus("Error getting balance; see log.");
});
};
function calcPremium() {
var premium = parseInt(document.getElementById("benefit").value)/10000;
document.getElementById("monthlyPremium").innerHTML = " Monthly Premium: $"+premium.toFixed(2);
};
function sendCoin() {
var meta = MetaCoin.deployed();
var amount = parseInt(document.getElementById("monthlyPremium").value);
var receiver = document.getElementById("receiver").value;
setStatus("Initiating transaction... (please wait)");
meta.sendCoin(receiver, amount, {from: account}).then(function() {
setStatus("Transaction complete!");
refreshBalance();
}).catch(function(e) {
console.log(e);
setStatus("Error sending coin; see log.");
});
};
window.onload = function() {
web3.eth.getAccounts(function(err, accs) {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
accounts = accs;
account = accounts[0];
refreshBalance();
});
}
I'm able to open the html file in a Chrome browser, with the MetaMask plugin enabled. However, it seems I'm unable to interact with the contracts in any way, due to the web3 error issue. The exact message is this post's subject line.
Thanks in advance for any help or guidance!
Could you please try it and see . I think the onload is giving the issue.
$(window).load function() {
web3.eth.getAccounts(function(err,accs) {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
accounts = accs;
account = accounts[0];
refreshBalance();
});
}
Related
I have created a Python Azure Function and calling it via JS code hosted as an App Service on Azure.
I need to setup azure active directory authentication on this function.
I have configured azure active directory authentication in azure function app and azure app service and enabled CORS on both but still facing CORS issue
Access to XMLHttpRequest at 'https://login.windows.net' redirected from 'azure-function-url' from origin 'app-service-url' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Basically I want authentication for azure python function so that I can call it from AJAX request without exposing a token in app service?
Am I doing anything wrong?
Also is there a way I could return the logged in user's email-id with an azure function while using azure active directory authentication for that azure function? I can find a code sample in c#, below it is.
laimsPrincipal cp = ClaimsPrincipal.Current;
string welcome = string.Format("Welcome, {0} {1}!",
cp.FindFirst(ClaimTypes.GivenName).Value, `cp.FindFirst(ClaimTypes.Surname).Value);`
Now the issue is, I need to use Python to do this and I can't find a sample online. Can anyone please point me in the right direction? or maybe help translate this code.
This is a simple demo that calling an Azure function from html/JS code.
Step1: You should register an Azure AD application as your client so that you can use this app to login users and get tokens:
in this case , it will need Microsoft Graph API read user permission:
**Step2:**Create a python function with code below to test:
import logging
import base64
import azure.functions as func
import json
def main(req: func.HttpRequest) -> func.HttpResponse:
accessTokenPayLoad = req.headers.get("Authorization").replace("Bearer ","").split(".")[1]
data = base64.b64decode(accessTokenPayLoad + '==')
jsonObj = json.loads(data)
upn = jsonObj['upn']
return func.HttpResponse("hello, " + upn)
Basically, this function just read user's upn from access token to read user's email-id.
Step3 After you have created the function app, please enable CORS so that it could accept requests from static HTML:
Step4 The code below is the HTML/JS code sample that login users and get tokens to call the function:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Azure Function test</title>
<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.4.4/js/msal.min.js"></script>
</head>
<body>
<div >
<button id="SignIn" onclick="signIn()">Sign in</button><br/>
<div id="WelcomeMessage"></div><br/>
<div id="functionResult"></div>
</div>
</body>
<script>
var clientAppID = "<your client app id>"
var tenantID = "<your tenant name/id>"
var functionURL = "<your function url>";
var demoScops = {
scopes:["user.read"]
}
var msalConfig = {
auth: {
clientId: clientAppID,
authority: "https://login.microsoftonline.com/" + tenantID
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
var myMSALObj = new Msal.UserAgentApplication(msalConfig);
myMSALObj.handleRedirectCallback(authRedirectCallBack);
function signIn() {
myMSALObj.loginPopup(demoScops).then(function (loginResponse) {
console.log(loginResponse);
initPage();
}).catch(function (error) {
console.log(error);
});
}
function initPage(){
showWelcomeMessage();
getGraphAccessTokenToCallFunction()
}
function callFunction(accessToken){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
document.getElementById('functionResult').innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", functionURL, true);
xmlHttp.setRequestHeader("Authorization", "Bearer " + accessToken);
xmlHttp.send(null);
}
function getGraphAccessTokenToCallFunction(){
myMSALObj.acquireTokenSilent(demoScops).then(function (tokenResponse) {
console.log(tokenResponse.accessToken);
callFunction(tokenResponse.accessToken);
}).catch(function (error) {
console.log(error);
})
}
function showWelcomeMessage() {
var divWelcome = document.getElementById('WelcomeMessage');
divWelcome.innerHTML = 'welcome! ' + myMSALObj.account.name ;
var loginbutton = document.getElementById('SignIn');
loginbutton.innerHTML = 'sign out';
loginbutton.setAttribute('onclick', 'signOut();');
}
function authRedirectCallBack(error, response) {
if (error) {
console.log(error);
}
else {
if (response.tokenType === "access_token") {
callMSGraph(graphConfig.graphEndpoint, response.accessToken, graphAPICallback);
} else {
console.log("token type is:" + response.tokenType);
}
}
}
function requiresInteraction(errorCode) {
if (!errorCode || !errorCode.length) {
return false;
}
return errorCode === "consent_required" ||
errorCode === "interaction_required" ||
errorCode === "login_required";
}
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
var msie11 = ua.indexOf('Trident/');
var msedge = ua.indexOf('Edge/');
var isIE = msie > 0 || msie11 > 0;
var isEdge = msedge > 0;
var loginType = isIE ? "REDIRECT" : "POPUP";
if (loginType === 'POPUP') {
if (myMSALObj.getAccount()) {
initPage()
}
}
else if (loginType === 'REDIRECT') {
document.getElementById("SignIn").onclick = function () {
myMSALObj.loginRedirect(requestObj);
};
if (myMSALObj.getAccount() && !myMSALObj.isCallback(window.location.hash)) {
initPage()
}
} else {
console.error('Please set a valid login type');
}
function signOut() {
window.localStorage.clear();
myMSALObj.logout();
}
</script>
</html>
Result:
I'm trying to register a background task on my Windows Phone 8.1 to receive and handle push notifications.At the moment everything is working when the app is opened (foreground+background), but a background task that is defined in the app.js does not work when app is closed.
This is defined in the package.phone.appxmanifest:
<Extension Category="windows.backgroundTasks" StartPage="js/lib/backgroundTask.js">
<BackgroundTasks>
<Task Type="pushNotification" />
</BackgroundTasks>
</Extension>
backgroundTask.js
(function () {
//var backgroundTask = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current,
//taskName = backgroundTask.task.name;
Windows.Storage.ApplicationData.current.localSettings.values["hello"] = "world";
close();
})();
this is what my app.js does:
var taskName = "mySuperFancyBgTaskName";
var registerBackgroundTask = function() {
var btr = Windows.ApplicationModel.Background.BackgroundTaskRegistration;
var iter = btr.allTasks.first();
var taskRegistered = false;
while (iter.hasCurrent){
var ta = iter.current.value;
if (ta.name == taskName){
taskRegistered = true;
break;
}
iter.moveNext();
}
if (!taskRegistered){
var builder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
var trigger = new Windows.ApplicationModel.Background.PushNotificationTrigger();
builder.setTrigger( trigger );
builder.taskEntryPoint = "js\\lib\\backgroundTask.js";
builder.name = taskName;
try{
var task = builder.register();
//task.addEventListener("completed", onPushNotification);
}
catch (e){
console.error(e);
}
}
}
var channel;
var pushNotificationManager = Windows.Networking.PushNotifications.PushNotificationChannelManager;
var channelOperation = pushNotificationManager.createPushNotificationChannelForApplicationAsync();
channelOperation.then(function (newChannel) {
channel = newChannel;
saveChannelUriInSettings(channel.uri);
console.log("opened push notification channel with uri: " + channel.uri);
registerBackgroundTask();
},
function (error) {
console.log("Channel could not be retreived. " + error.number)
}
);
It seems that backgroundTask.js is never started,because there is nothing written in the localsettings. Tried to do some stuff there, but of course not able to debug there.
If I do
var onPushNotification = function (e) { ...}
channel.addEventListener("pushnotificationreceived", onPushNotification);
receiving raw push notifications works fine. So how do I get backgroundtask to work, so that it can save incoming push notifications? If it is working there is no need to define a event listener in the app to catch push notifications, right?
Any help is appreciated - thanks in advance!
I am stuck with Social login (Facebook, Google and twitter) through Phonegap.
I have googled and found so many solutions, but they don't work on either platform (i.e: android or iOS).
Does any one have implemented social login in his/her app using phonegap?
If any one could provide me the running code, that would be appreciated.
Thanks,
Sabir
I know it's probably late to answer your particular question but I have had the same issue - all of the current (September 2016) scripts, snippets and libraries for social login in PhoneGap/Cordova that I have tried did not work so I made some simple functions from scratch which may still be useful to people ending up here. You can use them to log the user in with LinkedIn, Facebook and Google(+). I have also made some simple functions that retrieve some basic user information from the access token that is returned by logging the user in with the given network. You can examine the functions but they usually save the token or/and the user data to localStorage for later usage. They have been tested in September 2016 and work perfectly. I hope that this would help other people who also land on failing snippets around the web.
You can just insert the code and use the functions whenever you want. It requires jQuery and PhoneGap's InAppBrowser (besides having made apps/clients in the social media in order to fill the app id and app secret).
As a side note, it is not the best move to store the client secret directly in the PhoneGap application as the source can be viewed by malevolent people.
The code can be refactored at many places, so feel free to do that, but it does the trick. You may also have to handle cases where the user cancels the login process.
var facebookLogin = function(appId, appSecret, successCb,errCb) {
/*$.get("https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&client_secret=" +appSecret + "&grant_type=client_credentials", function(res) {
if (res.indexOf("access_token=") !== -1) {
successCb(res.replace("access_token=", "").trim());
}
else {
errCb(res);
}
})
*/
var ref = window.open("https://www.facebook.com/dialog/oauth?display=popup&response_type=token&client_id="+appId+"&redirect_uri="+"http://anyurlhere.com", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("#access_token") !== -1) {
localStorage.fbToken = evt.url.split("#access_token=")[1];
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.fbToken);
})
}
}
})
}
var linkedinLogin = function(appId,appSecret,successCb,errCb) {
var ref = window.open("https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id="+appId+"&redirect_uri="+(encodeURI("http://anyurlhere.com"))+"&state=987654321&scope=r_basicprofile", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("code=") !== -1) {
var code = evt.url.split("code=")[1];
code = code.split("&")[0];
//TODO: get actual token to access user profile
$.post("https://www.linkedin.com/oauth/v2/accessToken", {"grant_type": "authorization_code", "code": code, "redirect_uri":encodeURI("http://anyurlhere.com"), "client_id":appId,"client_secret":appSecret}, function(data) {
for (key in data) {
if (key == 'access_token') {
localStorage.linkedinToken = data[key];
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.linkedinToken);
})
}
}
})
}
}
})
}
var googleLogin = function(appId, appSecret, successCb, errCb) {
var ref = window.open("https://accounts.google.com/o/oauth2/v2/auth?response_type=token&client_id=" + appId + "&redirect_uri="+encodeURI("http://anyurlhere.com")+"&scope="+encodeURIComponent("email profile")+"&state=profile", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("access_token=") !== -1) {
var accessToken = evt.url.split("access_token=")[1];
accessToken = accessToken.split("&")[0];
localStorage.gToken = accessToken;
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.gToken);
})
}
}
})
}
var getGoogleInfo = function(successCb, errCb) {
//get basic user profile
$.get("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + localStorage.gToken, function(userInfo) {
successCb(userInfo);
})
}
var getFacebookInfo = function(successCb, errCb) {
//get basic user profile-name
$.get("https://graph.facebook.com/me?fields=email,name,picture&access_token=" + localStorage.fbToken, function(userInfo) {
var myInfo = {};
if (userInfo.name) {
myInfo.name = userInfo.name;
}
if (userInfo.email) {
myInfo.email = userinfo.email;
}
if (userInfo.picture) {
myInfo.picture = userInfo.picture.data.url;
}
localStorage.myInfo = JSON.stringify(myInfo);
successCb(myInfo);
// localStorage.myInfo = myInfo;
})
}
//get basic data for linked in
var getLinkedinInfo = function(successCb, errCb) {
$.ajax({
url: "https://api.linkedin.com/v1/people/~?format=json",
headers: {
"Authorization": "Bearer " + localStorage.linkedinToken
},
success: function(userInfo) {
var myInfo = {};
if (userInfo.firstName && userInfo.lastName) {
myInfo.name = userInfo.firstName + " " + userInfo.lastName;
}
if (userInfo.headline) {
myInfo.linkedinHeadline = userInfo.headline;
}
localStorage.myInfo = JSON.stringify(myInfo);
successCb(myInfo);
},
fail: function(err) {
alert(err);
for (key in err) {
alert(key);
alert(err[key]);
}
}
})
}
//example of logging in the user with Google + and getting his/her data
googleLogin("93-54932-423-fkfew.apps.googleusercontent.com", "", function(accessToken) {
getGoogleInfo(function(userInfo) {
var myInfo = {};
alert(userInfo.name);
if (userInfo.email) {
myInfo.email = userInfo.email;
}
if (userInfo.name) {
myInfo.name = userInfo.name;
}
if (userInfo.given_name) {
myInfo.firstName = userInfo.given_name;
}
if (userInfo.familyName) {
myInfo.familyName = userInfo.family_name;
}
if (userInfo.picture) {
myInfo.picture = userInfo.picture;
}
I'm having an issue where my call to $.ajax is completing successfully and returning content with a response of 200OK as reported by firebug, but the success,complete and error callbacks do not execute. This is only happening in firefox, in chrome it works fine (i am running firefox22).
$.ajax(site_url+url+'/fetch_salt',{type:'POST',data:data,success:check_salt});
var group = '';
function check_salt(d)
{
console.log(d);
The actual response for the request as reported by firebug is:
choose_login:{"admin":"Admin Zone"}
And response type:
Content-Type text/html
I have tried forcing settings like dataType and contentType in case jquery is assuming json or something and I have tried anonymous functions for the error, success and complete callbacks, but nothing works.
Am posting full function code, just in case its some kind of syntax error quirk:
function prep_login_form(elem,url,challenge)
{
function show_error(msg)
{
$(elem).find('.ecms-error-for-password .ecms-error-text').html(msg).closest('.ecms-error-container').removeClass('ecms-error-hidden');
}
function submit()
{
var data = {email:$(elem).find('input[name="email"]').val()};
data[csfr_token_name] = csfr_hash;
$.ajax({type:'POST',url:site_url+url+'/attempt_login',data:data,success:check_salt});
var group = '';
function check_salt(d)
{
console.log(d);
if (d=='no_email')
{
show_error('Invalid Email address');
}
else if (d=='account_disabled')
{
show_error('This account has been disabled, please contact your administrator');
}
else if (d.substr(0,12)=='choose_login')
{
var cl;
eval('cl = '+d.substr(13));
var cou = 0;
for (p in cl)
{
cou++;
}
if (cou==1)
{
group = p;
var mydata = $.extend(data,{group:p});
$.ajax(site_url+url+'/fetch_salt',{type:'POST',data:mydata,success:check_salt})
}
else
{
var str = '<div class="login-selection-popup"><p>We have detected that your email address is linked to more than one account.<br />Please select which zone you would like to login to.</p><ul class="choose-login-popup">';
for (p in cl)
{
str+='<li><a rel="'+p+'">'+cl[p]+'</a></li>';
}
str+='</ul></div>';
open_modal({heading:'Choose Account',content:str,buttons:function(close_modal)
{
$(this).find('.choose-login-popup').on('click','a',function()
{
group = $(this).attr('rel');
var mydata = $.extend(data,{group:$(this).attr('rel')});
$.ajax(site_url+url+'/fetch_salt',{type:'POST',data:mydata,success:check_salt})
close_modal();
});
}});
}
}
else
{
var salt = d;
var pw = $(elem).find('input[name="password"]').val();
data.password = hex_md5(challenge+hex_md5(salt+pw));
data.group = group;
$.ajax(site_url+url+'/attempt_login',{type:'POST',data:data,success:function(d)
{
if (d=='no_email')
{
show_error('Invalid username or password');//Invalid Email address
}
else if (d=='account_disabled')
{
show_error('This account has been disabled, please contact your administrator');
}
else if (d=='invalid_login')
{
show_error('Invalid username or password');//Email or Password did not match
}
else
{
window.location.href = d;
}
}});
}
}
}
$(elem).on('keyup','input',function(e)
{
if (e.keyCode=='13')
{
submit();
}
});
$(elem).find('.login-submit').on('click',function()
{
submit();
});
}
Sorry for all the trouble guys I recently had addware on my PC and battled to get rid of it. I think that it had damaged/hijacked my firefox. After re-installing firefox the problem has gone away, the callbacks now execute.
I have a tracking app built with Node that is accessed by other sites in our network. They will access the app thru the head of their html files like so:
<title>Test</title>
<meta name="generator" content="TextMate http://macromates.com/">
<script src="http://mynetwork.com:1337/tracker.js?pid=publisher1&ps=home"></script>
</head>
<body>
The tracker.js file uses socket.io to connect to app.js which stores some data in MongoDB. For some reason when start socket.io then load a page that references that Tracker.js scripts I get an error "Uncaught SyntaxError: Unexpected identifier" on line 1 which is actually the “Welcome to socket.io." message and not the javascript thats in the file.
Here is what Tracker.js looks like:
(function(document, onload){
var io = document.createElement('script');
io.src = "//cdn.socket.io/stable/socket.io.js";
io.setAttribute('async', 'true');
if ( typeof onload === 'function') {
io.onloadDone = false;
io.onload = function() {
io.onloadDone = true;
onload();
};
io.onreadystatechange = function() {
if ( "loaded" === io.readyState && !io.onloadDone ) {
io.onloadDone = true;
io.onload();
}
};
}
(document.getElementsByTagName('head') || document.getElementsByTagName('body'))[0].appendChild(io);
});
(document, function(){
var socket = io.connect('http://mynetwork.com:1337');
socket.emit('adTracker',
{ adServer: 'datalunk', adZone : 'top_home', referingURL : 'site.com' }
);
socket.on('entrance', function(){
console.log('Response is:' + data.message);
});
});
The app.js file looks like this:
var io = require('socket.io');
var tracker = io.listen(1337);
tracker.configure(function () {
tracker.set('authorization', function (handshakeData, callback) {
if (handshakeData.xdomain) {
callback('Cross-domain connections are not allowed');
} else {
callback(null, true);
}
});
});
tracker.sockets.on('connection', function (socket) {
socket.on('entrance', {message: 'connection has been made to app.js'});
socket.on('adTracker', function (data) {
var adRequestData = data;
var pass = ["bigbooks"];
var databaseUrl = "user:pass#linus.mongohq.com:10006/node-test";
var collections = ["mads"]
var db = require("mongojs").connect(databaseUrl, collections);
db.cmnads.insert({adRequest : adRequestData}, {$set: {password: pass}}, function(err, updated) {
if( err || !updated ) console.log("User not updated");
else console.log("User updated");
});
});
});
Can anyone tell me why I would be getting the socket.io welcome message & error on line 1 and how do I resolve it?
(function(document, onload){
var io = document.createElement('script');
// rest of code
});
(document, function(){
// rest of code
});
});
should be
(function(document, onload){
var io = document.createElement('script');
// rest of code
})(document, function(){
// rest of code
});
});
You use an anonymous function that you should call (and you don't do it).
the correct syntax is (for a more simple example):
(function(a) {console.log(a)})('Hello World');
However you do:
(function(a) {console.log(a)});
('Hello World');
Make sure that the server has the latest stable version of Node installed. According to the official web site, it is currently v0.8.16.
Also, if socket.io server is running on http://mynetwork.com:1337/ then I believe you should be able to include the socket.io.js from http://mynetwork.com:1337/socket.io/socket.io.js
The fastest way to check if maybe the Node version is the source of problem is to install Node Version Manager, then v0.8.16 and finally run the socket.io server again
wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh
nvm install v0.8.16
nvm use 0.8.16
node yourSocketIOserver.js