Files
Emmelia-Link-Flayer-Rewrite/middleware/balanceAuthorization.js
2023-02-27 00:20:54 -05:00

65 lines
2.6 KiB
JavaScript

// To ensure the command caller has, 1. an account and 2. has enough balance for the request
// The pricing table needs to be in the DB so it can be updated via API
const { DebugBuilder } = require("../utilities/debugBuilder");
const log = new DebugBuilder("server", "balanceAuthorizations");
const {
checkForAccount,
createAccount,
verifyBalance,
insufficientTokensResponse,
welcomeResponse
} = require("../controllers/accountController");
/**
* Authorize a transaction amount for an account
*
* @param {*} interaction
* @param {*} command
* @param {undefined|number} _tokens The amount of tokens to authorize, set to undefined if the value is in the interaction
* @param {*} next
* @returns
*/
exports.authorizeTokenUsage = async (interaction, command, _tokens = undefined, next) => {
log.DEBUG("Command requires tokens? ", command.isPrivileged)
if(!command.requiresTokens) return next(true);
if(!interaction.member && (!_tokens || !interaction.options.getNumber("tokens") || !command.defaultTokenUsage)) throw new Error("No member or tokens specified before attempting to authorize");
const memberId = interaction.member.id;
var tokensToBeUsed;
if (!_tokens || _tokens && isNaN(_tokens)){
if (interaction.options.getNumber("tokens")) tokensToBeUsed = interaction.options.getNumber("tokens");
else tokensToBeUsed = command.defaultTokenUsage;
}
else tokensToBeUsed = _tokens;
log.DEBUG(`Authorizing ${memberId} for a purchase worth ${tokensToBeUsed} tokens`)
log.DEBUG("Checking for account associated with discord ID: ", memberId);
await checkForAccount(memberId, async (err, results) => {
if (err) throw err;
log.DEBUG("Results from checking for account: ", results);
// First time user is attempting transaction
if(!results){
log.DEBUG("No account for discord ID: ", memberId);
await createAccount(memberId, (err, results) => {
if (err) throw err;
if (results) return welcomeResponse(interaction);
})
} else{
// User has an account
log.DEBUG(`Account ID: ${results.account_id} found for discord ID: ${memberId}`);
await verifyBalance(tokensToBeUsed, results.account_id, async (err, isVerified) => {
if (err) throw err;
if(!isVerified) return insufficientTokensResponse(interaction);
return next(isVerified);
})
}
})
}