How to use jwt token after connect with metamask - javascript

I am working with PHP and JavaScript. I integrated metamask with PHP, so for this I am using "Ajax", but I want to know that how we can use "jwt token" (create) if we successfully connected with Metamask?
Here is my current code
<script>
const ethereumButton = document.querySelector('.enableEthereumButton');
const showAccount = document.querySelector('.showAccount');
ethereumButton.addEventListener('click', () => {
getAccount();
});
async function getAccount() {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const account = accounts[0];
$('#cst_account_var').val(account);
var bla = $('#cst_account_var').val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>/admin/add_wallet",
data: {wallet: bla},
dataType: "text",
cache:false,
success:
function(data){
window.location.replace("<?php echo base_url(); ?>profile");
}
});
}
</script>

Related

Can't find uncaught type error in JS file

I'm trying to put form data in object and send it to php page to check if user exists. But Illegal invocation error is on display in console and it implies that there is uncaught type error in JS file. But I just can't find it. Here is JS file:
function postViaAjax(fileName, specificFunction, data = null) {
$.ajax({
url: "models/" + fileName + ".php",
method: "post",
data: data,
dataType: "json",
success: function(jsonData) {
specificFunction(jsonData);
},
error: function(xhr) {
console.error(xhr);
}
});
}
$("#signIn").click(function() {
let username = $("#username").val();
let password = $("#password").val();
let data = new FormData();
data.append("username", username);
data.append("password", password);
postViaAjax("signingIn", signingIn, data);
});
function signingIn(jsonData) {
if (jsonData.message == "User have the initial password!") {
alert("Successfull signing in!");
let newPassword = prompt("Now you have to change initial password. Enter your new password in the field bellow:");
let data = new FormData();
data.append("newPassword", newPassword);
postViaAjax("changingPassword", changingPassword, data);
} else {
alert(jsonData.message);
}
}
function changingPassword(jsonData) {
alert(jsonData.message);
}
I just have found out the solution! Ajax call must have contentType:false and processData: false if FormData got to be sent through it.
You forgot to include the Jquery script in your code.
function postViaAjax(fileName, specificFunction, data = null) {
$.ajax({
url: "models/" + fileName + ".php",
method: "POST",
data: data,
dataType: "json",
success: function(jsonData) {
specificFunction(jsonData);
},
error: function(xhr) {
console.error(xhr);
}
});
}
$("#signIn").click(function() {
let username = $("#username").val();
let password = $("#password").val();
let data = new FormData();
data.append("username", username);
data.append("password", password);
postViaAjax("signingIn", signingIn, data);
});
function signingIn(jsonData) {
if (jsonData.message == "User have the initial password!") {
alert("Successfull signing in!");
let newPassword = prompt("Now you have to change initial password. Enter your new password in the field bellow:");
let data = new FormData();
data.append("newPassword", newPassword);
postViaAjax("changingPassword", changingPassword, data);
} else {
alert(jsonData.message);
}
}
function changingPassword(jsonData) {
alert(jsonData.message);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

VanillaJS vs JQuery - wait handler until two async requests are done

I have used JQuery since a long time and i am familar with the AJAX-Calls in it. I often had the situation where i had to wait until multiple requests have been finished and continue after that with the results.
The JQuery syntax was the following:
$.when(
$.ajax({
type: "POST",
url: '/Services/Service.asmx/GetResults1',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
...
},
error: function (e) {
console.log('ERROR! ' + e.responseText);
}
}),
$.ajax({
type: "POST",
url: '/Services/Service.asmx/GetResults2',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
...
});
},
error: function (e) {
console.log('ERROR! ' + e.responseText);
}
})
).done(function (result1, result2) {
// Do s.th. with result1 and result2 what is already
// available here
updateUI();
...
});
How can you do this in VanillaJS?
Here is an example using the new vanilla JS fetch API
fetch('URL', {
method: "POST/PUT/GET/DELETE",
body: JSON.stringify({
name: Name,
otherData : otherData
}),`enter code here`
headers: {"content-type": "application/json"}
})
.then(res => res.json())
.then(response => {
//do what you want with the response here
})
For a GET request you can opt-out the body in fetch like
fetch('URL', {
method: "GET",
headers: {"content-type": "application/json"}
})
.then(res => res.json())
.then(response => {
//do what you want with the response here
})
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
document.getElementById("userID").innerHTML = json.userId;
document.getElementById("title").innerHTML = json.title;
document.getElementById("completed").innerHTML= json.completed;
})
<div>The User ID is : </div>
<div id="userID">
</div>
<div>The Title is : </div>
<div id="title">
</div>
<div>Completed : </div>
<div id="completed">
</div>
Compare this one with your AJAX request:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
receivedJSON = JSON.parse(xhttp.responseText);
//Your success: function here...
}else{
//Your error: function here...
}
};
xhttp.open("POST","/Services/Service.asmx/GetResults1",true);
xhttp.send(/**Your JSON Data**/);

Identity.IsAuthenticated return false in an ASP.Net Web API

After a successful login, the returned value is always false. I'm using the default Authentication system that's provided by Microsoft.Identity ("Individual User Accounts" option) with no modifications. Any thoughts?
[HttpGet]
[Route("get-userId")]
public bool CurrentUserId()
{
return User.Identity.IsAuthenticated;
}
Client-side codes:
Login.html:
$(document).ready(function () {
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
username: $('#txtUsername').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
success: function (response) {
sessionStorage.setItem("accessToken", response.access_token);
window.location.href = "Momo.html";
},
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
});
Momo.html:
$(document).ready(function () {
if (sessionStorage.getItem('accessToken') == null) {
window.location.href = "Login.html";
}
$.ajax({
url: '/api/Account/get-userId',
method: 'GET',
success: function (response) {
console.log(response);
}
});
console.log(response) returns false.
You need to send the token to the server with each request. Add the following to your Ajax call:
headers: { "Authorization": 'Bearer ' + token }
You can rewrite your code like this:
$(document).ready(function () {
var token = sessionStorage.getItem('accessToken');
if (token == null) {
window.location.href = "Login.html";
}
$.ajax({
url: '/api/Account/get-userId',
method: 'GET',
headers: { "Authorization": 'Bearer ' + token },
success: function (response) {
console.log(response);
}
});

Implement clientside token-based authentication using plain Javascript/AJAX

Can anyone point me to an article that explains clientside token auth implementation using Javascript?
I found many articles on Angular but that is not what I'm looking for. That brings me to the question if it is possible to be done with Javascript.
Also how to handle scenarios when the auth server throws a 401. Is there a built in exception to detect that response? Or is a custom exception required to be implemented?
I have personally used JSON web tokens in one of my projects.
http://blog.slatepeak.com/creating-a-simple-node-express-api-authentication-system-with-passport-and-jwt is a tutorial on how to set up JSON web tokens on the server side.
Once you get the token as a response to the client side, you can store the token on window.localStorage.
var credentials = {
username : document.getElementById("username").value,
password : document.getElementById("password").value
};
var url = window.localStorage.getItem('appUrl');
$.ajax({
url: url + '/register',
type: 'POST',
data: { username: credentials.username, password: credentials.password },
success: function(Data) {
window.localStorage.setItem('token', Data.token);
},
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));},
error: function() {
alert('Error occured');
}
});
});
Then you can attach it in an AJAX call as a header while navigating to other pages.
$.ajax
({
type: "GET",
url: "index1.php",
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization',window.localStorage.getItem('token'));
},
success: function (){
alert('Thanks for your comment!');
}
});
This worked for me..
var token = gettoken();
function getDatatypes() {
if (isEmpty(token)) {
token = gettoken();
}
var request = getDatatypesFromApi();
request.success(function (data) {
alert('success!');
});
request.error(function (httpObj, textStatus) {
if (httpObj.status == 401)
gettoken();
});
}
function getDatatypesFromApi() {
var request = $.ajax
({
type: "GET",
url: "http://yoururl.com/",
data: '',
headers:{
'Authorization': 'Basic ' + token
},
dataType: "json",
timeout: 5000,
});
return request;
}
function gettoken() {
var credentials = {
username: "userid",
password: "PASS",
domain: "",
extensionsAppId:"{extAppId}"
};
var url = "http://thelinktoresource/"
$.ajax({
url: url,
type: 'GET',
data: { userId: credentials.username, password: credentials.password, domain: credentials.domain, extensionsAppId: credentials.extensionsAppId },
dataType: "json",
contentType: 'application/json; charset=UTF-8',
success: function (Data) {
console.log(Data);
token = Data.replace(/"/ig, '');
return token;
},
error: function () {
alert('Error occured');
return "undefined";
}
});
}
function isEmpty(strIn) {
if (strIn === undefined) {
return true;
}
else if (strIn == null) {
return true;
}
else if (strIn == "") {
return true;
}
else {
return false;
}
}

Clear Phonegap's InAppBrowser Cache

I am using Google authorization into my app. It works perfectly,
but the problem is cache not clear when someone logout from app.
I have tried adding clearcache=yes and clearsessioncache=yes, but they do not seem to do anything. Without clearing the cache when someone tries to log back in it validates the token with the previously signed in account.
Is there a way I can delete everything associated to the InAppBrowser ?
var googleapi = {
authorize: function (options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
var authWindow = window.open(authUrl,'_blank','location=no,toolbar=no,clearsessioncache=yes');
$(authWindow).on('loadstart', function (e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function (data) {
deferred.resolve(data);
$("#loginStatus").html('Name: ' + data.given_name);
}).fail(function (response) {
deferred.reject(response.responseJSON);
});
} else if (error) {
//The user denied access to the app
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
var UserData = null;
function callGoogle() {
googleapi.authorize({
client_id: 'client_id',
client_secret: 'client_secret-key',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function (data) {
accessToken = data.access_token;
getDataProfile();
});
}
function getDataProfile() {
var term = null;
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function (jqXHR, text_status, strError) {
},
success: function (data) {
var item;
var OAuthToken = accessToken;
var OAuthAccessToken = data.id;
var username = data.email;
var firstname = data.given_name;
var lastname = data.family_name;
var ExternalIdentifier = data.id;
var Email = data.email;
var ProviderSystemName = "ExternalAuth.Google";
ExternalResponseInsert(apiSecretKey, storeId, languageId, username, firstname, lastname, Email, ExternalIdentifier, OAuthToken, OAuthAccessToken, ProviderSystemName);
}
});
//disconnectUser();
}
function disconnectUser() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (nullResponse) {
accessToken = null;
console.log(JSON.stringify(nullResponse));
console.log("-----signed out..!!----" + accessToken);
},
error: function (e) {
// Handle the error
}
});
}

Categories

Resources