udemy-go-web-2/static/js/common.js

94 lines
2.7 KiB
JavaScript

export let card;
export let stripe;
const payButton = document.getElementById("pay-button");
export const processing = document.getElementById("processing-payment");
export function hidePayButton() {
payButton.classList.add("d-none");
processing.classList.remove("d-none");
}
export function showPayButton() {
payButton.classList.remove("d-none");
processing.classList.add("d-none");
}
export function showError(element, msg) {
const messages = document.getElementById(element);
messages.classList.add("alert-danger");
messages.classList.remove("alert-success");
messages.classList.remove("d-none");
messages.innerText = msg;
}
export function showSuccess(element, msg) {
const messages = document.getElementById(element);
messages.classList.add("alert-success");
messages.classList.remove("alert-danger");
messages.classList.remove("d-none");
messages.innerText = msg;
}
export function stripeInit(pubKey) {
stripe = Stripe(pubKey);
(function () {
// create stripe & elements
const elements = stripe.elements();
const style = {
base: {
fontSize: '16px',
lineHeight: '24px',
}
};
// create card entry
card = elements.create('card', {
style: style,
hidePostalCode: true,
});
card.mount("#card-element");
// check for input errors
card.addEventListener('change', function (event) {
var displayError = document.getElementById("card-errors");
if (event.error) {
displayError.classList.remove('d-none');
displayError.textContent = event.error.message;
} else {
displayError.classList.add('d-none');
displayError.textContent = "";
}
});
})();
}
export function checkAuth(api) {
if (localStorage.getItem("token") === null) {
location.href = "/login";
return
} else {
let token = localStorage.getItem("token")
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Bearer " + token);
const requestOptions = {
method: "POST",
headers: myHeaders,
}
fetch(api + "/api/is-authenticated", requestOptions)
.then(response => response.json())
.then(function(data) {
if (data.error === true) {
console.log("not logged in");
location.href = "/login"
} else {
console.log("Logged in");
}
})
}
}