Creating a website that allows metamask connection - metamask

I'm trying to create a website that can connect to metamask.
It should automatically open the metamask extension to allow the user to confirm the connection upon entering the site, however it just says "attempting to connect" and metamask never opens.
Here is my connectWallet code - there is also a button that runs connectWallet onclick
<script>
function connectWallet() {
// window.addEventListener('load', function () {
document.getElementById("demo").innerHTML = "ATTEMPTING TO CONNECT!";
if (window.ethereum) {
window.web3 = new Web3(ethereum);
ethereum.enable()
.then(() => {
console.log("Ethereum enabled");
web3.eth.getAccounts(function (err, acc) {
if (err != null) {
self.setStatus("There was an error fetching your accounts");
return;
}
if (acc.length > 0) {
console.log(acc);
walletID = acc[0]
document.getElementById("demo").innerHTML = "CONNECTED!";
getNFTsOfUser();
return;
}
});
})
.catch(() => {
console.warn('User didn\'t allow access to accounts.');
document.getElementById("demo").innerHTML = "CONNECTION REJECTED!";
waitLogin();
});
} else {
console.log("Non-Ethereum browser detected. You should consider installing MetaMask.");
document.getElementById("demo").innerHTML = "METAMASK NOT FOUND! PLEASE INSTALL OR USE A DAPP!";
}
// })
}

Related

how to connect to specific wifi in xamarin ios?

I want to connect to wifi....................................................................
Here is my code:
NEHotspotConfigurationManager wifiManager = new NEHotspotConfigurationManager();
var wifiConfig = new NEHotspotConfiguration(ssid, password, false) { JoinOnce = true };
wifiManager.RemoveConfiguration(ssid);
wifiManager.ApplyConfigurationAsync(wifiConfig);
wifiManager.ApplyConfiguration(wifiConfig, (error) =>
{
if (error != null)
{
Console.WriteLine($"Error while connecting to WiFi network {ssid}: {error.Description}");
}
});
return true;
Just like #cole-xia-msft mentioned the link for the configuration work, the C# code would look like this.
var configuration = new NetworkExtension.NEHotspotConfiguration("SSID", "Password", false);
configuration.JoinOnce = true;
NetworkExtension.NEHotspotConfigurationManager.SharedManager.ApplyConfiguration(configuration, (NSError error) =>
{
if (error != null) {
if (error?.LocalizedDescription == "already associated.")
Console.WriteLine("Connected");
else
Console.WriteLine("No Connected");
}
else
Console.WriteLine("Connected");
});
If your function enclosing the ApplyConfiguration call is asynchronous, you should consider using ApplyConfigurationAsync instead

issue with single sign on Azure active directory javascript library

We have single sign on enabled for our MS Dynamics 365 CRM instance to make a calls to an API hosted in Azure. On launch of CRM we have the following JavaScript that executes. This works most of the time, but on occasion we get "Invalid argument" popup. I am relatively new to using Adal.js and have no idea what is causing this. Any trouble shooting tips appreciated. Thanks in advance.
config = {
ApiUrl: configData["ApiUrl"],
SubscriptionKey: configData["SubscriptionKey"],
trace: configData["trace"],
AcceptHeader: configData["AcceptHeader"],
ContentTypeHeader: configData["ContentTypeHeader"],
tenant: configData["tenant"],
clientId: configData["clientId"],
tokenStoreUrl: configData["tokenStoreUrl"],
cacheLocation: configData["cacheLocation"],
GraphApi: configData["GraphApi"]
};
// Check For & Handle Redirect From AAD After Login
authContext = new window.AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
if (isCallback) {
authContext.handleWindowCallback();
}
var loginError = authContext.getLoginError();
if (loginError) {
console.log('ERROR:\n\n' + loginError);
}
authContext.popUp = true;
if (isCallback && !loginError) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
var user = authContext.getCachedUser();
if (!user) {
authContext.clearCache();
sessionStorage["adal.login.request"] = "";
authContext.login();
}
window.parent.authContext = authContext;
It has been a while since I last looked at this, however I managed to get it resolved at the time. I implemented a locking mechanism, to ensure the login completes before trying to obtain a token.
Here is the updated code:
config = {
ApiUrl: configData["ApiUrl"],
SubscriptionKey: configData["SubscriptionKey"],
trace: configData["trace"],
AcceptHeader: configData["AcceptHeader"],
ContentTypeHeader: configData["ContentTypeHeader"],
tenant: configData["tenant"],
clientId: configData["clientId"],
tokenStoreUrl: configData["tokenStoreUrl"],
cacheLocation: configData["cacheLocation"],
GraphApi: configData["GraphApi"],
loadFrameTimeout: 10000
};
// Check For & Handle Redirect From AAD After Login
authContext = new window.AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
if (isCallback) {
authContext.handleWindowCallback();
}
var loginError = authContext.getLoginError();
if (loginError) {
// TODO: Handle errors signing in and getting tokens
console.log('ERROR:\n\n' + loginError);
}
authContext.popUp = true;
if (isCallback && !loginError) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
var user = authContext.getCachedUser();
if (!user) {
authContext.clearCache();
sessionStorage["adal.login.request"] = "";
authContext.callback = function (error, token, msg) {
// remove lock
window.top.loginLock = null;
if (!!token) {
getGraphApiTokenAndUpdateUser(authContext);
}
else {
console.log('ERROR:\n\n' + error);
}
};
if (typeof (window.top.loginLock) == "undefined" || window.top.loginLock == null) {
// Create lock
window.top.loginLock = true;
authContext.login();
}
}
window.parent.authContext = authContext;

Circular dependencies in Titanium/ RequireJs

I have some circular dependencies in my Titanium application like so:
index.js
var Auth = require('Auth')
Auth.js
var PopUp = require('PopUp');
function isLoggedIn() {
// some logic e.g. return userName !== null
};
function authorise() {
if (isLoggedIn()) {
return true;
} else {
return PopUp.authorise();
}
}
PopUp
var Auth = require("Auth");
function authorise() {
// some code asking user to login
}
function showSecurePopUp() {
if (Auth.isLoggedIn()) {
// show secure pop up
}
}
As you can see we have a circular dependency. Auth needs PopUp and PopUp needs Auth.
This creates a circular dependency and thus the following error message:
[ERROR] [iphone, 10.3.3, 192.168.0.64]
Type: RangeError
Message: Maximum call stack size exceeded.
File: /iphone/Auth.js.js
Line: 24
How can I solve the issue of circular dependencies in a Titanium Alloy app?
I think this could be the way, you do the following changes in you project and this should solve the problem.
Alloy.js
var Auth = require("Auth");
var PopUp = require('PopUp');
Index.js
Auth.authorise();
Auth.js
var isLoggedIn = function() {
// some logic e.g. return userName !== null
Ti.API.info('isLoggedIn');
return false;
};
exports.authorise = function() {
if (isLoggedIn()) {
Ti.API.info('authorize isloggedIn');
return true;
} else {
Ti.API.info('authorize not logged In');
return PopUp.authorise();
}
};
exports.isLoggedIn = isLoggedIn;
PopUp.js
exports.authorise =function () {
// some code asking user to login
Ti.API.info('authorize funcition popup ' + Auth.isLoggedIn());
};
function showSecurePopUp() {
if (Auth.isLoggedIn()) {
// show secure pop up
Ti.API.info('isLoggedIn show secure popup');
}
}
Let me know if this works fine and if this is what you wanted. Also if you have some other approach that solves the problem, then let me know that also.
Good Luck & Cheers
Ashish Sebastian

FireFox Add-on permissions

I am building an add-on as a project for Firefox using JPM and was wondering how I could enable indefinite permissions for the user?
e.g.
I have the below code which prompts the user for permission on every website:
function HTT(theBody,theIcon,theTitle) {
var options = {
body: theBody,
icon: theIcon
}
if (!("Notification" in window)) {
alert("This browser does not support HTT notifications");
}
else if (Notification.permission === "granted") {
var n = new Notification(theTitle,options);
Date.now() + 30000;
//setTimeout(n.close.bind(n), 4000);
}
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
if (permission === "granted") {
var n = new Notification(theTitle,options);
Date.now() + 30000;
//setTimeout(n.close.bind(n), 4000);
}
});
}
}
What I would like to do is ask for permission once ONLY. How could I achieve this as I have tried a number of different options?
FYI - The purpose of the add-on is the display a notification, but this is the permission side of the code.
Thanks

Prevent from route change in AngularJS

$rootScope.$on("$locationChangeStart", function(event, next, current) {
var partsOfUrl = next.split('/');
var isLogin = false;
if(partsOfUrl.indexOf("signin") > 0) {
isLogin = true;
}
var myDataPromise = loginService.getData();
myDataPromise.then(function(data) { // this is only run after $http completes
if(!isLogin) {
if(data.logout) {
$location.url("pages/signin");
event.preventDefault();
} else{}
} else {
if(data.logout) {
} else {
}
}
});
console.log(next);
});
This is the code i used to check user authentication and prevent the protected areas. But problem here is if a user try to access protected then immediately browser shows the secure page and then get back to login page instead of redirecting to login page first. I think that's because of user authentication process is done through an Ajax call so the program never holds for the response. What's the wrong here and how should i get rid of it ?
Try with httpInterceptor (from mean.io stack)
btw the server should response with a 401 status
'use strict';
angular.module('mean-factory-interceptor',[])
.factory('httpInterceptor', ['$q','$location',function ($q,$location) {
return {
'response': function(response) {
if (response.status === 401) {
$location.path('/signin');
return $q.reject(response);
}
return response || $q.when(response);
},
'responseError': function(rejection) {
if (rejection.status === 401) {
$location.url('/signin');
return $q.reject(rejection);
}
return $q.reject(rejection);
}
};
}
])
//Http Intercpetor to check auth failures for xhr requests
.config(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}]);

Resources