Can't verify password on client side - javascript

I am trying to use pdf.js on my webpage where I need to verify that the password entered by the user of PDF is correct before uploading it to the server.
But I am not able to make it work.
I used CDN hosted pdf.min.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js" integrity="sha512-Z8CqofpIcnJN80feS2uccz+pXWgZzeKxDsDNMD/dJ6997/LSRY+W4NmEt9acwR+Gt9OHN0kkI1CTianCwoqcjQ==" crossorigin="anonymous"></script>
and this is the password checking function:
function checkPass() {
pdfjsLib.getDocument({
url: 'pdf.pdf',
password: '01010101'
}).promise.then(function (pdf) {
input.classList.add("rightpass");
}).catch(function (error) {
input.classList.add("wrongpass");
console.log(error);
});
}
and in the console log, it logs Deprecated API usage: No "GlobalWorkerOptions.workerSrc" specified.
I tried to disable it by pdfjsLib.disableWorker = true; but it didn't work.
I just need to verify the password and nothing else no rendering.

Here is a working code sample:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js"></script>
<script>
const pdfName = "empty-protected.pdf";
async function loaded()
{
const loadingTask = pdfjsLib.getDocument({ url: pdfName, password: "qwerty" });
loadingTask.promise.then(() => console.log(1, "OK"), (ex) => console.log(1, ex));
const loadingTask2 = pdfjsLib.getDocument({ url: pdfName, password: "" });
loadingTask2.promise.then(() => console.log(2, "OK"), (ex) => console.log(2, ex));
}
</script>
</head>
<body onload="javascript:loaded();">
</body>
</html>
Here is the password-protected pdf file (password is qwerty) that I used for the experiment:
https://mega.nz/file/lJg2GKgS#AdVJ0DZ1OfsGrlSqM67dfr_r2n8lBiiOm9q0o4wt7e4
Incliding pdf.worker.min.js changes the warning "Warning: Deprecated API usage: No "GlobalWorkerOptions.workerSrc" specified." to "Warning: Setting up fake worker."

Related

Is it important to hide Stripe secret key in Javascript?

I would like to know if it's important to hide my stripe key in my javascript.
In fact, in my Symfony website, I put this key in my javascript to allow users to pay their orders.
And this is how I made that:
</footer>
</body>
<script src="https://kit.fontawesome.com/47f28c9d14.js" crossorigin="anonymous"></script>
<script type="text/javascript">
var stripe = Stripe("pk_live_....");
var checkoutButton = document.getElementById("checkout-button");
checkoutButton.addEventListener("click", function () {
fetch("/orders/create-session/154154154", {method: "POST"})
.then(function (response) { return response.json(); })
.then(function (session) { if (session.error == 'order')
{ window.location.replace('/orders'); } else { return stripe.redirectToCheckout({sessionId: session.id}); } })
.then(function (result) { if (result.error) { alert(result.error.message); } })
.catch(function(error) { console.error("Error:", error); }); });
</script>
</html>
But if you open console and check the source code you can see my stripe key...
Thanks
Yes, you can use the Stripe 'publishable' key in your client side app.
More information: https://stripe.com/docs/keys?locale=en-GB

AppCheck tokens are not recognised only when using mobile

I'm developing a webapp authentication system using Firebase. When I login and use the webapp from my computer everything works fine but when I use it on mobile appcheck does not work anymore and it gives me the following error in the console:
https://content-firebaseappcheck.googleapis.com/v1/projects/nameoftheproject/apps/1:784721317237:web:5db5892bc06253ab6b173c:exchangeRecaptchaEnterpriseToken?key=myKey
Failed to load resource: the server responded with a status of 403 ()
This is the code I'm using to create initialise appCheck in my webapp:
const appCheck = initializeAppCheck(app, {
provider: new ReCaptchaEnterpriseProvider(config[process.env.REACT_APP_ENV]['recaptcha-key']),
isTokenAutoRefreshEnabled: true
});
export const getAppCheckToken = async () => {
let appCheckTokenResponse;
try {
appCheckTokenResponse = await getToken(appCheck, false);
} catch(err) {
console.log(err);
}
return appCheckTokenResponse.token;
}
So a typical use case for that function is this:
//This is the code from one of my functions, it's just an example to show you how I use appcheck tokens
if (querySnapshot.docs.length === 0) {
headerAPI.headers['X-Firebase-AppCheck'] = await getAppCheckToken();
await axios.post(signupAPI, {
email: email,
username: displayName
}, headerAPI);
await sendEmailVerification(auth.currentUser, {
url: config[process.env.REACT_APP_ENV]['url-used-to-send-mail-auth-signup'],
handleCodeInApp: true
})
props.cookieAlert('Info', 'Cookies', 'Informations here...');
} else {
window.location.href = '/dashboard/home';
}
Now, I can't understand why it doesn't work on mobile...I hope my code is clear enough to let you understand my troubles, thank you in advance.

No error but not writing into firestore. The code works in 7.9.1 but this is 7.14.1. Is this the error?

I am trying to write into Firestore using Javascript but it doesn't work although there is no error. I am using 7.14.1 version. This code ran properly on 7.9.1 so I don't know if this is the error.
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-auth.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-analytics.js"></script>
I try to console log before reading data, it works but the console log after reading data does not work.
function retriveid(){
fireauth.onAuthStateChanged(function(user) {
if (user) {
var user = fireauth.currentUser;
if (user != null) {
user.providerData.forEach(function () {
console.log("Firestore loaded");
const songname = document.getElementById('songname');
const singername = document.getElementById('singer');
const youtubelink = document.getElementById('ytlink');
const audiolink = document.getElementById('aulink')
console.log(categoryname.value, songname.value, singername.value, youtubelink.value, audiolink.value, user.uid);
firestore.collection("song").doc("Rock").set({
song_name: songname.value,
singer_name: singername.value,
youtube_link: youtubelink.value,
audio_link: audiolink.value
})
.then(function(){
console.log("Document successfully written!");
})
.catch(function(error){
console.error("Error writing document: ", error);
})
});
}
} else {
// No user is signed in.
console.log("not yet log in")
}
});
}
Hi Doug i have the same error, only you need modify the link in "...firebase-app.js" to "...firebase.js"
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase.js"></script>
the function ..listAll() works correctly. It will help you a lot, I had to consult several sources, i leave you an example:
storageRef = firebase.storage().ref('images/'+idReport);
storageRef.listAll().then(function(result) {
result.items.forEach(function(imageRef) {
// And finally display them
displayImage(imageRef);
});
}).catch(function(error) {
// Handle any errors
});
function displayImage(imageRef) {
imageRef.getDownloadURL().then(function(url) {
console.log("url", url);
}).catch(function(error) {
console.log("error", error);
});
}

Unable to get azure OAuth2 token with javascript for O365 Comm-Services

i have a problem and hope you guys can help me.
I want to build a small page for my colleagues that they can check the newest informations from O365 admin-portal.
For that i want to use the "Office 365 Service Communications API"(https://manage.office.com/api/v1.0/contoso.com/ServiceComms/Messages)
I already registered the application in my azure-ad so i am already able to get the Information via Postman or Powershell(Invoke-Rest). But i have problem to get it with JavaScript. With normal rest-options i always get a CORS error. Thats why i thought i try it with the MSAL.js library.
But i cant get it work. Maybe my Code is wrong?!
And i was a little bit confused because in the official docs they say i must deactivate CORS in my browser?! (https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-browser --> under prerequisites)
It cant be that difficult... hope you can help me.
Here is my Code:
<!DOCTYPE html>
<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.2.0/js/msal.js"></script>
<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.2.0/js/msal.min.js"></script>
<html lang="en">
<script type="text/javascript">
var Demo;
const msalConfig = {
auth: {
clientId: '2076e785-XXXX-XXXX-XXXX-XXXXXXXXXX'
}
};
const msalInstance = new Msal.UserAgentApplication(msalConfig);
msalInstance.handleRedirectCallback((error, response) => {
// handle redirect response or error
});
var loginRequest = {
scopes: ["user.read", "mail.send"] // optional Array<string>
};
msalInstance.loginPopup(loginRequest)
.then(response => {
// handle response
})
.catch(err => {
// handle error
});
// if the user is already logged in you can acquire a token
if (msalInstance.getAccount()) {
var tokenRequest = {
scopes: ["user.read", "mail.send"]
};
msalInstance.acquireTokenSilent(tokenRequest)
.then(response => {
})
.catch(err => {
// could also check if err instance of InteractionRequiredAuthError if you can import the class.
if (err.name === "InteractionRequiredAuthError") {
return msalInstance.acquireTokenPopup(tokenRequest)
.then(response => {
// get access token from response
// response.accessToken
})
.catch(err => {
// handle error
});
}
});
} else {
// user is not logged in, you will need to log them in to acquire a token
}
var headers = new Headers();
var bearer = "Bearer " + Demo;
var options = {
method: "GET",
headers: headers
};
var graphEndpoint = "https://manage.office.com/api/v1.0/contoso.onmicrosoft.com/ServiceComms/Messages";
fetch(graphEndpoint, options)
.then(resp => {
//do something with response
});
</script>
</html>
As far as I knew, we just can use the sdk msal.js to request azure ad access token without cors issue. But when we make the fetch request to https://manage.office.com in the client-side application(single page application), we will meet the cors error. Because the request is cross domain. Regarding how to fix it, please refer to the https://medium.com/#dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9.

Getting error: 'Stich is not defined' in JavaScript password reset function

I am trying to develop a password reset webpage to use in my email/password authentication for MongoDB Stitch, this is my code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- Stitch JavaScript SDK -->
<!-- Base Stitch Browser SDK -->
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.0.0/stitch.js"></script>
<script>// Parse the URL query parameters
const url = window.location.search;
const params = new URLSearchParams(url);
const token = params.get('token');
const tokenId = params.get('tokenId');
const newPassword = "test";
// Confirm the user's email/password account
const emailPassClient = Stitch.defaultAppClient.auth
.getProviderClient(UserPasswordAuthProviderClient.factory);
emailPassClient.resetPassword(token, tokenId, newPassword).then(() => {
console.log("Successfully reset password!");
}).catch(err => {
console.log("Error resetting password:", err);
});
</script>
</body>
</html>
I am getting an error like the following:
Uncaught ReferenceError: Stitch is not defined
Perhaps I am importing the stitch bundles incorrectly?
Call stitch.Stitch.initializeDefaultAppClient(ID)
Note that you have to initialize a default app client, you can't just call stitch.Stitch.defaultappClient
const client = stitch.Stitch.initializeDefaultAppClient('<<app-id>>');
var emailClient = client.auth.getProviderClient(window.stitch.UserPasswordAuthProviderClient.factory);
emailPassClient.resetPassword(token, tokenId, newPassword).then(() => {
console.log("Successfully reset password!");
}).catch(err => {
console.log("Error resetting password:", err);
});

Categories