API Integration with Axios - Username and Password PopUp Showing Up - javascript

I've been assigned a task to do with integrating APIs. I've been able to fetch information from the API, but there's a popup showing up, asking me to submit username and password. I have the username and password, but the idea is to log in without the necessity of that popup showing up.
Here's the code:
const getPlate = () => {
let licensePlate = document.getElementById('licensePlate');
let licensePlateNumber = licensePlate.value;
if (licensePlate.value === "") {
alert('¡Debe introducir el número de matrícula para poder avanzar!');
} else {
Axios.get( * URL GOES HERE * ).then((response) => {
let plate = response;
console.log(plate.data[i].make);
});
}
}
<div id="carDataContainer">
<div id="licensePlateContainer">
<input type="text" name="licensePlate" id="licensePlate" placeholder="Matrícula - ej. 001 BNDO"></input>
<button type="button" id="plateBtn" onClick={ getPlate }>Search</button>
</div>
</div>

You should provide the user/password to axios (looks like Basic auth is expected). Try adding that info to your request:
Axios.get( * URL GOES HERE *, {
auth: {
username: "your-username",
password: "your-pass",
}
} ).then((response) => {
let plate = response;
console.log(plate.data[i].make);
});
}

You need Basic Auth
see: https://stackoverflow.com/a/44239543/7662325
Also if this does not work you can use this: https://stackoverflow.com/a/53939140/7662325

Related

SvelteKit: cookies.set() In Form Action Not Working

I am trying to implement JWT-based user sessions with SvelteKit, and have mostly been following the explanation for form actions given on their website: https://kit.svelte.dev/docs/form-actions
+page.svelte
<form method="POST" action="?/signIn">
<input type="text" name="name" />
<input type="password" name="password" />
<button type="submit">Submit</button>
</form>
+page.server.svelte
import { fail, redirect } from "#sveltejs/kit";
import { signIn } from "$lib/server/database";
export const actions = {
signIn: async ({ cookies, request }) => {
const data = await request.formData();
const name = data.get("name");
const password = data.get("password");
if (!name || !password) {
return fail(400);
}
try {
cookies.set("jwt", await signIn(name, password));
} catch (error) {
return fail(400);
}
throw redirect(303, "/");
},
};
I have tested my signIn method which I import and use here, and it does return a token when called with the correct credentials. So far, so good. However, I noticed that I don't see any cookies in my developer tools. It seems like the cookies.set() call simply does nothing. I'd like to set the returned JWT as a cookie so that I can authenticate my users, so what am I doing wrong?
In case anybody else has this problem: While the cookie was set as it was supposed to when using Chrome, it wasn't in Safari. I solved this by setting the secure option to false, even though the SvelteKit docs state that this is done automatically on localhost.

How to setup AWS Cognito TOTP MFA?

I am trying to setup MFA authentication using AWS Cognito as a small proof of concept for a work project. I have managed to get username & password with a MFA code sent via SMS working fine.
Struggling to get the TOTP method which is shown in use case 27 working with my small login app - https://www.npmjs.com/package/amazon-cognito-identity-js
i have modified the associateSecretCode so that it should show me a the secret code to then enter into my authenticator app but this doesnt display when i attempt to login with a valid user.
What am i doing wrong?
Heres my code:
<body>
<form>
<ul class="form-style-1">
<li><label>UserID <span class="required">*</span></label><input type="text" name="username" class="field-divided" placeholder="UID" /></li>
<li><label>Password <span class="required">*</span></label><input type="password" name="password" class="field-divided" placeholder="Password" /></li>
<li>
<input type="submit" value="Submit" />
</li>
</ul>
</form>
<div id="results" class="form-style-1"></div>
</body>
</html>
<script type="text/javascript">
//var dataResult;
$(document).ready(function() {
$('form').submit(function(event) {
//-------------------user pool
AWSCognito.config.region = 'eu-west-2';
var poolData = {
UserPoolId : 'user pool id here',
ClientId : 'app client id here'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
//------------------Authentication-------------------------
var userData = {
Username : $('input[name=username]').val(), // your username here
Pool : userPool
};
var authenticationData = {
Username : $('input[name=username]').val(), // your username here
Password : $('input[name=password]').val(), // your password here
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
console.log('OnSuccess')
var accessToken = result.getAccessToken().getJwtToken();
cognitoUser.associateSoftwareToken(this);
},
onFailure: function(err) {
console.log('onFailure')
alert(err.message || JSON.stringify(err));
},
mfaSetup: function(challengeName, challengeParameters) {
console.log('mfaSetup')
cognitoUser.associateSoftwareToken(this);
},
associateSecretCode: async secretCode => {
console.log("SECRET CODE: ", secretCode);
$('#results').html(secretCode);
setTimeout(() => {
const challengeAnswer = prompt("Please input the TOTP code.", "");
cognitoUser.verifySoftwareToken(challengeAnswer, "My TOTP device", {
onSuccess: session => console.log("SUCCESS TOTP: ", session),
onFailure: err => console.error("ERROR TOTP: ", err)
});
}, 2000);
},
selectMFAType: function(challengeName, challengeParameters) {
console.log('selectMFAType')
var mfaType = prompt('Please select the MFA method.', ''); // valid values for mfaType is "SMS_MFA", "SOFTWARE_TOKEN_MFA"
cognitoUser.sendMFASelectionAnswer(mfaType, this);
},
totpRequired: function(secretCode) {
console.log('totpRequired')
var challengeAnswer = prompt('Please input the TOTP code.', '');
cognitoUser.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA');
},
mfaRequired: function(codeDeliveryDetails) {
console.log('mfaRequired')
var verificationCode = prompt('Please input verification code', '');
cognitoUser.sendMFACode(verificationCode, this);
}
});
});
});
</script>
The best solution I've found is to use Amplify UI components. You don't need to take all the rest of Amplify, you can just grab the two relevant JS libraries, import, configure, and then wrap the page you need in the withAuthenticator HOC. The default setup handles both registration and challenge with sofware and SMS TOTP, as well as forgot password and create account flows. All the error handling you'd expect is included, and even language/theme customization and localization. It's very comprehensive.
While it was painful to figure out, the steps are actually not at all complicated, assuming you already have a Cognito User Pool set up. (Note: Amplify requires a User Pool client which does not use a client secret.)
You can find sample code in my answer to a similar StackOverflow question.

injection - How user can pay custom value of ETH with metamask API?

I want to give user possibility to choose his own value of Ether. How to do this?
How efficiently change the network when pressing connect to metamask (for example when user will press this button metamask should change network to binance smart chain (ID 56)
here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/web3#latest/dist/web3.min.js"></script>
</head>
<body>
<div>
<button class="enableEthereumButton btn">Enable Ethereum</button>
<button class="sendEthButton btn">Send Eth</button>
<div id="status"></div>
</div>
<script type="text/javascript">
// Running on the page, in the browser
if (typeof window.ethereum !== 'undefined') {
console.log('MetaMask is installed!');
}
if (!ethereum || !ethereum.isMetaMask) {
throw new Error('Please install MetaMask.')
}
/*********************************************************/
/* Handle chain (network) and chainChanged, per EIP 1193 */
/*********************************************************/
// Do this:
ethereum.on('chainChanged', (chainId) => {
/* handle the chainId */
});
const ethereumButton = document.querySelector('.enableEthereumButton');
const sendEthButton = document.querySelector('.sendEthButton');
let accounts = [];
//Sending Ethereum to an address
sendEthButton.addEventListener('click', () => {
ethereum
.request({
method: 'eth_sendTransaction',
params: [
{
from: accounts[0],
to: '0x6adress.................',
value: '0x00',
gasPrice: '0x0000001F6EA08600',
gas: '0x0001ADB0',
},
],
})
.then((txHash) => console.log(txHash))
.catch((error) => console.error);
});
ethereumButton.addEventListener('click', () => {
getAccount();
});
async function getAccount() {
accounts = await ethereum.request({ method: 'eth_requestAccounts' });
}
</script>
</body>
</html>
Metamask screenshot
Add an input field for the value and pass it in to your params. This is basic html form + javascript interactions, not specific to web3, so for more info on how to do that I would look here https://www.w3schools.com/html/html_forms.asp
To read the network the user is connecting with in your app you can listen for a chain change event: https://docs.metamask.io/guide/ethereum-provider.html#events
Then if they are not connected to a network your app supports you should show the user a notice.

How to insert data into mysql using angular and nodejs - getting (NULL, NULL) upon insert - Problem solved

Good day,
I've been trying to learn a bit of angular and nodejs. I found a tutorial on a realtime chat app and made some few adjustment to some function of the code. But the one aspect that I cannot seem to get right is the ability for the user to post to a feed. The login process works, the user is already logged in but the user can't post. I would also like to be able to get all they data i insert from all the user to show up like a normal feedview will. Please assist.
Here are my files:
FROM MY CONTROLLER HERE IS THE CODE WHEN THE BUTTON IS PRESSED
$scope.postDatatoDd = () => {
appService.httpCall({
url: '/posts',
params: {
'posts': $scope.data.info,
'from_user_id': $scope.data.username
}
})
.then((response) => {
// $scope.$apply();
})
.catch((error) => {
alert(error.message);
});
}
and here is my route file:
this.app.post('/posts', async(request,response) => {
const reqResponse = {}
const data = {
posts : request.body.postDatatoDd,
from_user_id: request.body.username
};
if (data.posts === ''){
reqResponse.error = true;
reqResponse.message = `error, input`;
response.status(412).json(reqResponse);
} else {
const result = await helper.insertFeed(data);
if (result === null) {
reqResponse.error = true;
reqResponse.message = `they was an error.`;
response.status(417).json(reqResponse);
} else {
reqResponse.error = false;
reqResponse.userId = result.insertId;
reqResponse.message = `posted succesfully`;
response.status(200).json(reqResponse);
}
}});
and in my helper file there is this function to insert data:
async insertFeed(params){
try {
return await this.db.query(
`INSERT INTO posts (from_user_id,posts) values (?,?)`,
[params.from_user_id,params.postDatatoDd]
);
} catch (error) {
console.warn(error);
return null;
}
}
On the client side here is the button with :
<label for="postDatatoDd">Post</label>
<input type="text" id="postDatatoDd"
ng-model="data.postDatatoDd"
class="feed form-control"
placeholder="post your data here?"
/>
<button ng-click="postDatatoDd()" class="btn btn-primary">Post</button>
</div>
--- EDIT 1---
Data is being inserted now, but it is receiving the values as (NULL, NULL).
--- EDIT 2 ---
After closely looking at the code and fixing some naming variables the code works fine, the data is being inserted in mysql as it should.
Other than a lot of typos when it comes to the variables reference. The code seem to be fine.
Assuming that you using appservice class somewhere in your code and its functioned, then everything else will work.
You are getting the (NULL, NULL) because you are parsing parameters that are not being properly parsed out to your helper file, please close attention to that.
appService
.httpCall({
url: "/posts",
params: {
posts: $scope.data.postbuzz,
from_user_id: $scope.data.username,
},
})
.then((response) => {
$scope.$apply();
})
.catch((error) => {
alert(error.message);
});
make sure that the data that you calling from this above function is similar to $scope parameter you passing in your route file that your requesting:
const data = {
posts : request.body.posts,
from_user_id: request.body.from_user_id}
and in your database helper class you running:
`INSERT INTO posts (from_user_id,post) values (?,?)`,
[params.from_user_id,params.posts]
Hope this was helpful
You seem to have an understand already. your question may help a lot more people in the future.
params should be as following, since the data object has properties from_user_id and posts
`INSERT INTO posts (from_user_id,posts) values (?, ?)`,
[params.from_user_id,params.posts]
Might be useful https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp
--- EDIT 2 ---
After closely looking at the code and fixing some naming variables the code works fine, the data is being inserted in mysql as it should.
If you are new to Angular you can use the code as reference.

How to access Symfony 3.4 object values from Request::createFromGlobals()

I am trying to use Symfony 3.4 components in a legacy project. There is a form that has two fields city and state. I want to send those two fields to a class method. So, I built an intermediate PHP file to pass the data to using javascript. The form and javascript are here.
<form class="form-inline" id="addpharmacies">
<div class="form-group">
<label for="city" ><?php print xlt("City");?></label>
<input type="text" class="form-control" id="city">
</div>
<div class="form-group">
<label for="state"><?php print xlt("State");?></label>
<input type="text" class="form-control" id="state">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
let f = document.getElementById('addpharmacies');
f.addEventListener('submit', importPharm);
function importPharm() {
top.restoreSession();
let city = document.getElementById("city").value;
let state = document.getElementById("state").value;
if (city.length === 0 || state.length ===0) {
alert("City and state must both be filled out")
return false;
}
let body = {"city": city, "state": state};
let req = new Request('pharmacyHelper.php', {method: "POST", body: body});
fetch(req)
.then(response=> {
if (response.status === 200) {
return response.json()
} else {
throw new Error("Bad response from the server");
}
})
.then(json => {
alert(json) // Not a great UI experience
})
}
As you can see that I am using a listener to submit the form by way of the javascript function importPharm. The javascript gets the data from the form via a getElementById call to city and state fields.
A request is created and the data is passed into the request and the helper file is called to pass the data. I have verified that something is being sent to the helper file. But I can see is [object Object] when I do a getContent().
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$request = Request::createFromGlobals();
$content = $request->getContent();
file_put_contents("api.txt", $content);
When I try:
$request->request->get('city','');
I get nothing. I have tried every combination I could find on the Symfony Site
Any suggestion will be greatly appreciated.
Well you haven't specified any headers clarifying your content-type so it's ambiguous for Symfony to detect your content type and map them to the Parameter Bag (although it displays the content body) , try adding the :
Content-Type : application/x-www-form-urlencoded
header and send your form inputs as form-data and try again , else you will need to json_decode the content body and deal with it as an array or \StdClass object .
N.B : Using form-data your request would look like this
let body = "city="+city+"&state="+state;
let req = new Request('pharmacyHelper.php', {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-url-encoded',
'Accept': 'application/json'
},body: body});
fetch(req).then(response=> {
if (response.status === 200) {
return response.json()
} else {
throw new Error("Bad response from the server");
}
})
.then(json => {
alert(json) // Not a great UI experience
})

Categories