Invoices can be created
- Transactions can now be tracked
This commit is contained in:
37
config.ts
Normal file
37
config.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
/**
|
||||||
|
* Here you can change various settings like database credentials, http settings and more.
|
||||||
|
*
|
||||||
|
* Debug mode and MongoDB credentials are set via enviroment variables for security reasons.
|
||||||
|
*/
|
||||||
|
export const config: IConfig = {
|
||||||
|
authentification: {
|
||||||
|
pepper: 'J3%_zö\\^',
|
||||||
|
salt_length: 8,
|
||||||
|
argonTimecost: 8,
|
||||||
|
minPasswordLength: 4,
|
||||||
|
maxPasswordLength: 150
|
||||||
|
},
|
||||||
|
http: {
|
||||||
|
port: 2009,
|
||||||
|
host: "0.0.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* END OF CONFIG
|
||||||
|
* ====================
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
export interface IConfig {
|
||||||
|
authentification: {
|
||||||
|
pepper: string,
|
||||||
|
salt_length: number,
|
||||||
|
argonTimecost: number,
|
||||||
|
minPasswordLength: number,
|
||||||
|
maxPasswordLength: number
|
||||||
|
},
|
||||||
|
http: {
|
||||||
|
port: number,
|
||||||
|
host: string
|
||||||
|
}
|
||||||
|
}
|
||||||
923
package-lock.json
generated
923
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
10
package.json
10
package.json
@@ -21,6 +21,7 @@
|
|||||||
"author": "Mondei1",
|
"author": "Mondei1",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"argon2": "^0.27.1",
|
||||||
"body-parser": "^1.19.0",
|
"body-parser": "^1.19.0",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^8.2.0",
|
"dotenv": "^8.2.0",
|
||||||
@@ -30,9 +31,9 @@
|
|||||||
"mongoose": "^5.11.8",
|
"mongoose": "^5.11.8",
|
||||||
"mysql": "^2.18.1",
|
"mysql": "^2.18.1",
|
||||||
"ts-node": "^9.1.1",
|
"ts-node": "^9.1.1",
|
||||||
"typeorm": "^0.2.29",
|
|
||||||
"typescript": "^4.1.3",
|
"typescript": "^4.1.3",
|
||||||
"winston": "^3.3.3"
|
"winston": "^3.3.3",
|
||||||
|
"zeromq": "^6.0.0-beta.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/typescript": "2.0.0",
|
"@types/typescript": "2.0.0",
|
||||||
@@ -42,6 +43,9 @@
|
|||||||
"@types/winston": "2.4.4",
|
"@types/winston": "2.4.4",
|
||||||
"@types/dotenv": "8.2.0",
|
"@types/dotenv": "8.2.0",
|
||||||
"@types/jsonwebtoken": "8.5.0",
|
"@types/jsonwebtoken": "8.5.0",
|
||||||
"@types/mysql": "2.15.16"
|
"@types/mysql": "2.15.16",
|
||||||
|
"@types/mongoose": "5.10.3",
|
||||||
|
"@types/argon2": "0.15.0",
|
||||||
|
"@types/zeromq": "4.6.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
95
src/app.ts
95
src/app.ts
@@ -1,8 +1,27 @@
|
|||||||
|
import * as bodyParser from 'body-parser';
|
||||||
|
import * as cors from 'cors';
|
||||||
|
import { config as dconfig } from 'dotenv';
|
||||||
|
import * as express from 'express';
|
||||||
import * as rpc from 'jayson';
|
import * as rpc from 'jayson';
|
||||||
import { createConnection } from 'typeorm';
|
import * as mongoose from 'mongoose';
|
||||||
import * as winston from 'winston';
|
import * as winston from 'winston';
|
||||||
|
|
||||||
|
import { config } from '../config';
|
||||||
|
import { hashPassword, randomPepper, randomString } from './helper/crypto';
|
||||||
|
import { InvoiceScheduler } from './helper/invoiceScheduler';
|
||||||
|
import { User } from './models/user/user.model';
|
||||||
|
import { invoiceRouter } from './routes/invoice';
|
||||||
|
|
||||||
|
// Load .env
|
||||||
|
dconfig({ debug: true, encoding: 'UTF-8' });
|
||||||
|
|
||||||
export const IS_DEBUG = process.env.DEBUG == 'true';
|
export const IS_DEBUG = process.env.DEBUG == 'true';
|
||||||
|
export const MONGO_URI = process.env.MONGO_URI || "";
|
||||||
|
export const JWT_SECRET = process.env.JWT_SECRET || "";
|
||||||
|
export const INVOICE_SECRET = process.env.INVOICE_SECRET || "";
|
||||||
|
|
||||||
|
export let rpcClient: rpc.HttpClient | undefined = undefined;
|
||||||
|
export let invoiceScheduler: InvoiceScheduler | undefined = undefined;
|
||||||
|
|
||||||
export let logger: winston.Logger;
|
export let logger: winston.Logger;
|
||||||
|
|
||||||
@@ -38,30 +57,68 @@ async function run() {
|
|||||||
)
|
)
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const dbConnection = await createConnection({
|
if (IS_DEBUG) {
|
||||||
type: 'mysql',
|
logger.info('Debug mode is enabled. Do not use this in production!');
|
||||||
host: 'localhost',
|
}
|
||||||
port: 3306,
|
|
||||||
username: 'librepay',
|
if (JWT_SECRET == '') {
|
||||||
password: 'librepay',
|
logger.crit('No JWT secret was provided. Make sure you add JWT_SECRET=YOUR_SECRET to your .env file.');
|
||||||
database: 'librepay',
|
process.exit(1);
|
||||||
entities: ['models/**/*.ts'],
|
}
|
||||||
synchronize: true,
|
|
||||||
logging: false
|
if (MONGO_URI == '') {
|
||||||
}).catch(error => {
|
logger.crit('No MongoDB URI was provided. Make sure you add MONGO_URI=mongodb+srv://... to your .env file.')
|
||||||
logger.error(`Connection to database failed: ${error}`);
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (INVOICE_SECRET == '') {
|
||||||
|
logger.crit('No invoice secret was provided. Make sure you add INVOICE_SECRET=(long random string) to your .env file.')
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const connection = await mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }).catch((err) => {
|
||||||
|
logger.crit("Database connection could not be made: ", err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
logger.info(`Database connection made to ${mongoose.connection.host}`);
|
||||||
|
|
||||||
const client = rpc.Client.http({
|
// Check if admin account doesn't exists
|
||||||
|
if((await User.countDocuments()) == 0) {
|
||||||
|
const randomPassword = "$1" + randomString(12);
|
||||||
|
const salt = randomString(config.authentification.salt_length);
|
||||||
|
|
||||||
|
await User.create({
|
||||||
|
name: 'admin',
|
||||||
|
password: await hashPassword(randomPassword + salt + randomPepper()),
|
||||||
|
salt,
|
||||||
|
createdAt: new Date(Date.now()),
|
||||||
|
lastLogin: new Date(0)
|
||||||
|
});
|
||||||
|
logger.info("=================================================================================");
|
||||||
|
logger.info("ADMIN USER HAS BEEN CREATED! Username: admin\tPassword: " + randomPassword);
|
||||||
|
logger.info("=================================================================================");
|
||||||
|
} else {
|
||||||
|
logger.debug("At least one admin user already exists, skip.");
|
||||||
|
}
|
||||||
|
|
||||||
|
invoiceScheduler = new InvoiceScheduler();
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
app.use(express.json());
|
||||||
|
app.use(cors());
|
||||||
|
app.use(bodyParser.json({ limit: '2kb' }));
|
||||||
|
|
||||||
|
app.get('/', (req, res) => res.status(200).send('OK'));
|
||||||
|
app.use('/invoice', invoiceRouter);
|
||||||
|
|
||||||
|
app.listen(config.http.port, config.http.host, () => {
|
||||||
|
logger.info(`HTTP server started on port ${config.http.host}:${config.http.port}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
rpcClient = rpc.Client.http({
|
||||||
port: 18332,
|
port: 18332,
|
||||||
auth: 'admin:admin'
|
auth: 'admin:admin'
|
||||||
});
|
});
|
||||||
|
|
||||||
/*client.request('getnewaddress', ['TestRPC', 'bech32'], (err, response) => {
|
|
||||||
if (err) throw err;
|
|
||||||
console.log(response.result);
|
|
||||||
})*/
|
|
||||||
}
|
}
|
||||||
|
|
||||||
run();
|
run();
|
||||||
@@ -1,5 +1,79 @@
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
|
import { invoiceScheduler, INVOICE_SECRET } from "../app";
|
||||||
|
import { CryptoUnits, FiatUnits } from "../helper/types";
|
||||||
|
import { ICart, IInvoice } from "../models/invoice/invoice.interface";
|
||||||
|
import { Invoice } from "../models/invoice/invoice.model";
|
||||||
|
import { rpcClient } from '../app';
|
||||||
|
|
||||||
|
// POST /invoice/?sercet=XYZ
|
||||||
export async function createInvoice(req: Request, res: Response) {
|
export async function createInvoice(req: Request, res: Response) {
|
||||||
const paymentMethods = req.body.methods;
|
const secret = req.query.secret;
|
||||||
|
if (secret === undefined) {
|
||||||
|
res.status(401).send({ message: 'secret parameter is missing' });
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
if (secret !== INVOICE_SECRET) {
|
||||||
|
setTimeout(() => {
|
||||||
|
res.status(401).send();
|
||||||
|
}, 1200);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const paymentMethods: CryptoUnits[] = req.body.methods;
|
||||||
|
const successUrl: string = req.body.successUrl;
|
||||||
|
const cancelUrl: string = req.body.cancelUrl;
|
||||||
|
const cart: ICart[] = req.body.cart;
|
||||||
|
const currency: FiatUnits = req.body.currency;
|
||||||
|
const totalPrice: number = req.body.totalPrice;
|
||||||
|
|
||||||
|
if (paymentMethods === undefined) {
|
||||||
|
res.status(400).send({ message: '"paymentMethods" are not provided!' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (successUrl === undefined) {
|
||||||
|
res.status(400).send({ message: '"successUrl" is not provided!' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cancelUrl === undefined) {
|
||||||
|
res.status(400).send({ message: '"cancelUrl" is not provided!' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currency === undefined) {
|
||||||
|
res.status(400).send({ message: '"currency" is not provided!' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*if (cart === undefined && totalPrice === undefined) {
|
||||||
|
res.status(400).send({ message: 'Either "cart" or "totalPrice" has to be defined.' });
|
||||||
|
return;
|
||||||
|
}*/
|
||||||
|
|
||||||
|
rpcClient.request('getnewaddress', ['', 'bech32'], async (err, response) => {
|
||||||
|
if (err) throw err;
|
||||||
|
//console.log(response.result);
|
||||||
|
|
||||||
|
Invoice.create({
|
||||||
|
paymentMethods,
|
||||||
|
successUrl,
|
||||||
|
cancelUrl,
|
||||||
|
cart,
|
||||||
|
currency,
|
||||||
|
totalPrice,
|
||||||
|
dueBy: 60,
|
||||||
|
receiveAddress: response.result
|
||||||
|
}, (error, invoice: IInvoice) => {
|
||||||
|
if (error) {
|
||||||
|
res.status(500).send({error: error.message});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
invoiceScheduler.addInvoice(invoice);
|
||||||
|
res.status(200).send({ id: invoice.id });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
105
src/helper/crypto.ts
Normal file
105
src/helper/crypto.ts
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
import { hash, verify } from 'argon2';
|
||||||
|
import { config } from '../../config';
|
||||||
|
import { IS_DEBUG, logger } from '../app';
|
||||||
|
|
||||||
|
export async function hashPassword(input: string): Promise<string> {
|
||||||
|
const start = Date.now();
|
||||||
|
|
||||||
|
return new Promise<string>(async (resolve, reject) => {
|
||||||
|
// Get real password (remove salt and pepper)
|
||||||
|
const realPassword = input.substring(0, input.length - config.authentification.salt_length - 1);
|
||||||
|
if (!check_password_requirements(realPassword)) {
|
||||||
|
if (!IS_DEBUG) reject("This password does not meet the minimum requirements!");
|
||||||
|
else {
|
||||||
|
reject(`This password does not meet the minimum requirements! (${input} => ${realPassword})`);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const hashed = await hash(input, {
|
||||||
|
hashLength: 42,
|
||||||
|
memoryCost: 1024*32,
|
||||||
|
parallelism: 2,
|
||||||
|
timeCost: config.authentification.argonTimecost
|
||||||
|
});
|
||||||
|
const finished = Date.now();
|
||||||
|
logger.debug("Hashing took " + (finished-start) + "ms to finish! " + input);
|
||||||
|
resolve(hashed);
|
||||||
|
} catch(err) {
|
||||||
|
reject(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verfiy If given password matches with provided hash by brute forcing the pepper.
|
||||||
|
* @param password Password with salt appended
|
||||||
|
* @param hashInput Hash from database
|
||||||
|
*/
|
||||||
|
export async function verifyPassword(password: string, hashInput: string): Promise<boolean> {
|
||||||
|
return new Promise<boolean>(async (resolve, reject) => {
|
||||||
|
const start = Date.now();
|
||||||
|
const peppers = config.authentification.pepper.split('');
|
||||||
|
const realPassword = password.substring(0, password.length - config.authentification.salt_length);
|
||||||
|
|
||||||
|
while (peppers.length !== 0) {
|
||||||
|
const pepper = peppers[Math.floor(Math.random() * peppers.length)];
|
||||||
|
if (IS_DEBUG) {
|
||||||
|
logger.debug(`Try ${password}}${pepper} (left: ${peppers})`);
|
||||||
|
} else {
|
||||||
|
// Show censored password (with fixed length) in non-debug mode to prevent password leaking.
|
||||||
|
logger.debug(`Try ********${password.replace(realPassword, '')}${pepper} (left: ${peppers})`);
|
||||||
|
}
|
||||||
|
if (await verify(hashInput, password + pepper)) {
|
||||||
|
const finished = Date.now();
|
||||||
|
logger.debug("Verifying took " + (finished - start) + "ms to complete!");
|
||||||
|
resolve(true);
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
peppers.splice(peppers.indexOf(pepper), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resolve(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function randomString(length: number): string {
|
||||||
|
let result = '';
|
||||||
|
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
||||||
|
const charactersLength = characters.length;
|
||||||
|
for ( let i = 0; i < length; i++ ) {
|
||||||
|
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function randomPepper(): string {
|
||||||
|
return config.authentification.pepper.charAt(Math.floor(Math.random() * config.authentification.pepper.length));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Requirements are:
|
||||||
|
* - at least 8 characters
|
||||||
|
* - min one upper-, lowercase- and special character
|
||||||
|
* - min one number
|
||||||
|
*/
|
||||||
|
export function check_password_requirements(password: string): boolean {
|
||||||
|
// Check for length
|
||||||
|
if (password.length < config.authentification.minPasswordLength ||
|
||||||
|
password.length > config.authentification.maxPasswordLength) return false;
|
||||||
|
|
||||||
|
// Check for one lowercase
|
||||||
|
if (!(/^(?=.*[a-z]).+$/.test(password))) return false;
|
||||||
|
|
||||||
|
// Check for one uppercase
|
||||||
|
if (!(/^(?=.*[A-Z]).+$/.test(password))) return false;
|
||||||
|
|
||||||
|
// Check for one uppercase
|
||||||
|
if (!(/^(?=.*[0-9]).+$/.test(password))) return false;
|
||||||
|
|
||||||
|
// Check for special characters
|
||||||
|
if (!(/[^A-Za-z0-9]/.test(password))) return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
105
src/helper/invoiceScheduler.ts
Normal file
105
src/helper/invoiceScheduler.ts
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
import { IInvoice } from "../models/invoice/invoice.interface";
|
||||||
|
import { Subscriber } from 'zeromq';
|
||||||
|
import { logger, rpcClient } from "../app";
|
||||||
|
import { invoiceRouter } from "../routes/invoice";
|
||||||
|
import { Invoice } from "../models/invoice/invoice.model";
|
||||||
|
import { PaymentStatus } from "./types";
|
||||||
|
|
||||||
|
export class InvoiceScheduler {
|
||||||
|
private pendingInvoices: IInvoice[];
|
||||||
|
private unconfirmedTranscations: IInvoice[];
|
||||||
|
private sock: Subscriber;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.unconfirmedTranscations = [];
|
||||||
|
this.pendingInvoices = [];
|
||||||
|
|
||||||
|
// Get all pending transcations
|
||||||
|
Invoice.find({ status: PaymentStatus.PENDING }).then(invoices => {
|
||||||
|
this.pendingInvoices = invoices;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get all unconfirmed transactions
|
||||||
|
Invoice.find({ status: PaymentStatus.UNCONFIRMED }).then(invoices => {
|
||||||
|
this.unconfirmedTranscations = invoices;
|
||||||
|
});
|
||||||
|
|
||||||
|
this.sock = new Subscriber();
|
||||||
|
this.sock.connect('tcp://127.0.0.1:29000');
|
||||||
|
this.listen();
|
||||||
|
this.watchConfirmations();
|
||||||
|
}
|
||||||
|
|
||||||
|
addInvoice(invoice: IInvoice) {
|
||||||
|
logger.info(`A new invoice has been created: ${invoice.id}`)
|
||||||
|
this.pendingInvoices.push(invoice);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function waits for Bitcoin Core to respond with raw TX.
|
||||||
|
*/
|
||||||
|
private async listen() {
|
||||||
|
this.sock.subscribe('rawtx');
|
||||||
|
|
||||||
|
logger.info('Now listing for incoming transaction to any invoices ...');
|
||||||
|
for await (const [topic, msg] of this.sock) {
|
||||||
|
const rawtx = msg.toString('hex');
|
||||||
|
logger.debug(`New tx: ${rawtx}`);
|
||||||
|
rpcClient.request('decoderawtransaction', [rawtx], (err, decoded) => {
|
||||||
|
if (err) {
|
||||||
|
logger.error(`Error while decoding raw tx: ${err.message}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
decoded.result.vout.forEach(output => {
|
||||||
|
//console.log('Output:', output.scriptPubKey);
|
||||||
|
|
||||||
|
// Loop over each output and check if the address of one matches the one of an invoice.
|
||||||
|
this.pendingInvoices.forEach(invoice => {
|
||||||
|
// We found our transaction
|
||||||
|
if (output.scriptPubKey.addresses === undefined) return; // Sometimes (weird) transaction don't have any addresses
|
||||||
|
if (output.scriptPubKey.addresses.indexOf(invoice.receiveAddress) !== -1) {
|
||||||
|
logger.info(`Transcation for invoice ${invoice.id} received! (${decoded.result.hash})`);
|
||||||
|
|
||||||
|
// Change state in database
|
||||||
|
invoice.status = PaymentStatus.UNCONFIRMED;
|
||||||
|
invoice.transcationHash = decoded.result.txid;
|
||||||
|
invoice.save();
|
||||||
|
|
||||||
|
// Push to array & remove from pending
|
||||||
|
this.unconfirmedTranscations.push(invoice);
|
||||||
|
this.pendingInvoices.splice(this.pendingInvoices.indexOf(invoice), 1);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This functions loops over each unconfirmed transaction to check if it reached "trusted" threshold.
|
||||||
|
*/
|
||||||
|
private watchConfirmations() {
|
||||||
|
setInterval(() => {
|
||||||
|
this.unconfirmedTranscations.forEach(invoice => {
|
||||||
|
rpcClient.request('gettransaction', [invoice.transcationHash], (err, message) => {
|
||||||
|
if (err) {
|
||||||
|
logger.error(`Error while fetching confirmation state of ${invoice.transcationHash}: ${err.message}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Number(message.result.confirmations) > 2) {
|
||||||
|
logger.info(`Transaction (${invoice.transcationHash}) has reached more then 2 confirmations and can now be trusted!`);
|
||||||
|
invoice.status = PaymentStatus.DONE;
|
||||||
|
invoice.save(); // This will trigger a post save hook that will notify the user.
|
||||||
|
|
||||||
|
this.unconfirmedTranscations.splice(this.unconfirmedTranscations.indexOf(invoice), 1);
|
||||||
|
} else {
|
||||||
|
logger.debug(`Transcation (${invoice.transcationHash}) has not reached his threshold yet.`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, 2_000);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
export enum CryptoUnits {
|
export enum CryptoUnits {
|
||||||
BITCOIN = 'BTC',
|
BITCOIN = 'BTC',
|
||||||
|
BITCOINCASH = 'BCH',
|
||||||
ETHEREUM = 'ETH',
|
ETHEREUM = 'ETH',
|
||||||
LITECOIN = 'LTC',
|
LITECOIN = 'LTC',
|
||||||
DOGECOIN = 'DOGE',
|
DOGECOIN = 'DOGE',
|
||||||
@@ -27,10 +28,3 @@ export enum PaymentStatus {
|
|||||||
*/
|
*/
|
||||||
DONE = 2
|
DONE = 2
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SellItem {
|
|
||||||
price: {
|
|
||||||
unit: number,
|
|
||||||
currency:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
42
src/models/invoice/invoice.interface.ts
Normal file
42
src/models/invoice/invoice.interface.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { Document } from 'mongoose';
|
||||||
|
import { CryptoUnits, FiatUnits, PaymentStatus } from '../../helper/types';
|
||||||
|
|
||||||
|
export interface ICart {
|
||||||
|
price: number;
|
||||||
|
name: string;
|
||||||
|
image: string;
|
||||||
|
quantity: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IInvoice extends Document {
|
||||||
|
// Available payment methods
|
||||||
|
// [btc, xmr, eth, doge]
|
||||||
|
paymentMethods: CryptoUnits[];
|
||||||
|
|
||||||
|
// 1Kss3e9iPB9vTgWJJZ1SZNkkFKcFJXPz9t
|
||||||
|
receiveAddress: string;
|
||||||
|
|
||||||
|
paidWith?: CryptoUnits;
|
||||||
|
|
||||||
|
// Is set when invoice got paid
|
||||||
|
// 3b38c3a215d4e7981e1516b2dcbf76fca58911274d5d55b3d615274d6e10f2c1
|
||||||
|
transcationHash?: string;
|
||||||
|
|
||||||
|
cart?: ICart[];
|
||||||
|
totalPrice?: number;
|
||||||
|
currency: FiatUnits;
|
||||||
|
|
||||||
|
// Time in minutes the user has to pay.
|
||||||
|
// Time left = (createdAt + dueBy) - Date.now() / 1000
|
||||||
|
dueBy: number;
|
||||||
|
|
||||||
|
status?: PaymentStatus;
|
||||||
|
|
||||||
|
// E-Mail address of user, if he want's a confirmation email.
|
||||||
|
email?: string;
|
||||||
|
|
||||||
|
successUrl: string;
|
||||||
|
cancelUrl: string;
|
||||||
|
|
||||||
|
createdAt?: number;
|
||||||
|
}
|
||||||
6
src/models/invoice/invoice.model.ts
Normal file
6
src/models/invoice/invoice.model.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { Model, model } from 'mongoose';
|
||||||
|
import { IInvoice } from './invoice.interface';
|
||||||
|
import { schemaInvoice } from './invoice.schema';
|
||||||
|
|
||||||
|
const modelInvoice: Model<IInvoice> = model<IInvoice>('Invoice', schemaInvoice , 'Invoice');
|
||||||
|
export { modelInvoice as Invoice };
|
||||||
58
src/models/invoice/invoice.schema.ts
Normal file
58
src/models/invoice/invoice.schema.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import { NativeError, Schema, SchemaTypes } from 'mongoose';
|
||||||
|
import { CryptoUnits, FiatUnits, PaymentStatus } from '../../helper/types';
|
||||||
|
import { IInvoice } from './invoice.interface';
|
||||||
|
|
||||||
|
const urlRegex = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/
|
||||||
|
|
||||||
|
const schemaCart = new Schema({
|
||||||
|
price: { type: Number, required: true },
|
||||||
|
name: { type: String, trim: true, required: true },
|
||||||
|
image: { type: String, match: urlRegex, required: true },
|
||||||
|
quantity: { type: Number, default: 1 }
|
||||||
|
})
|
||||||
|
|
||||||
|
const schemaInvoice = new Schema({
|
||||||
|
paymentMethods: [{ type: String, enum: Object.values(CryptoUnits), default: [CryptoUnits.BITCOIN], required: true }],
|
||||||
|
receiveAddress: { type: String, required: true },
|
||||||
|
paidWith: { type: String, enum: CryptoUnits },
|
||||||
|
transcationHash: { type: String, required: false },
|
||||||
|
cart: [{ type: schemaCart, required: false }],
|
||||||
|
totalPrice: { type: Number, required: false },
|
||||||
|
currency: { type: String, enum: Object.values(FiatUnits), required: false },
|
||||||
|
dueBy: { type: Number, required: true },
|
||||||
|
status: { type: Number, enum: Object.values(PaymentStatus), default: PaymentStatus.PENDING },
|
||||||
|
email: { type: String, required: false },
|
||||||
|
successUrl: { type: String, match: urlRegex, required: false },
|
||||||
|
cancelUrl: { type: String, match: urlRegex, required: false }
|
||||||
|
}, {
|
||||||
|
timestamps: {
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
versionKey: false
|
||||||
|
});
|
||||||
|
|
||||||
|
// Validate values
|
||||||
|
schemaInvoice.post('validate', function (res, next) {
|
||||||
|
let self = this as IInvoice;
|
||||||
|
|
||||||
|
// If cart is undefined and price too, error.
|
||||||
|
if ((self.cart === undefined || self.cart.length === 0) && self.totalPrice === undefined) {
|
||||||
|
next(new Error('Either cart or price has to be defined!'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If cart is provided, calculate price.
|
||||||
|
if (self.cart !== undefined && self.totalPrice === undefined) {
|
||||||
|
let totalPrice = 0;
|
||||||
|
|
||||||
|
for (let i = 0; i < self.cart.length; i++) {
|
||||||
|
const item = self.cart[i];
|
||||||
|
totalPrice += item.price * item.quantity;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.set({ totalPrice });
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
})
|
||||||
|
|
||||||
|
export { schemaInvoice }
|
||||||
10
src/models/user/user.interface.ts
Normal file
10
src/models/user/user.interface.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { Document } from 'mongoose';
|
||||||
|
|
||||||
|
export interface IUser extends Document {
|
||||||
|
name: string,
|
||||||
|
password: string,
|
||||||
|
salt: string,
|
||||||
|
lastLogin: Date,
|
||||||
|
twoFASecret?: string,
|
||||||
|
createdAt?: Date
|
||||||
|
}
|
||||||
6
src/models/user/user.model.ts
Normal file
6
src/models/user/user.model.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { Model, model } from 'mongoose';
|
||||||
|
import { IUser } from "./user.interface";
|
||||||
|
import { schemaUser } from './user.schema';
|
||||||
|
|
||||||
|
const modelUser: Model<IUser> = model<IUser>('User', schemaUser , 'User');
|
||||||
|
export { modelUser as User };
|
||||||
15
src/models/user/user.schema.ts
Normal file
15
src/models/user/user.schema.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Schema } from 'mongoose';
|
||||||
|
|
||||||
|
const schemaUser = new Schema({
|
||||||
|
name: { type: String, required: true },
|
||||||
|
password: { type: String, required: true },
|
||||||
|
salt: { type: String, required: true },
|
||||||
|
twoFASecret: { type: String, required: false },
|
||||||
|
lastLogin: { type: Date, required: true, default: Date.now },
|
||||||
|
}, {
|
||||||
|
timestamps: {
|
||||||
|
createdAt: true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export { schemaUser }
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
|
import { createInvoice } from "../controllers/invoice";
|
||||||
|
|
||||||
const invoiceRouter = Router()
|
const invoiceRouter = Router()
|
||||||
|
|
||||||
invoiceRouter.get('/:id');
|
invoiceRouter.get('/:id');
|
||||||
invoiceRouter.post('/');
|
invoiceRouter.post('/', createInvoice);
|
||||||
|
|
||||||
export { invoiceRouter };
|
export { invoiceRouter };
|
||||||
Reference in New Issue
Block a user