Paul Mathieu
0e67d30c7d
- use catclient instead of catprint - fix weight being 1000x what it should be - issue auth tokens for 20 hours
193 lines
5.1 KiB
JavaScript
193 lines
5.1 KiB
JavaScript
const bodyParser = require('body-parser');
|
|
const child_process = require('child_process');
|
|
const cors = require('cors');
|
|
const express = require('express');
|
|
require('express-async-errors');
|
|
const jwt = require('jsonwebtoken');
|
|
const path = require('path');
|
|
const sqlite3 = require('sqlite3').verbose();
|
|
|
|
const accessTokenSecret = 'cecinestpasunecledauthentificationjwt';
|
|
|
|
const db_name = path.join(__dirname, "data", "chikinz.db");
|
|
const db = new sqlite3.Database(db_name, err => {
|
|
if (err) {
|
|
return console.error(err.message);
|
|
}
|
|
console.log('Connected to the database.');
|
|
});
|
|
|
|
function makeTable(table) {
|
|
db.run(table, err => {
|
|
if (err) {
|
|
throw err;
|
|
}
|
|
});
|
|
}
|
|
|
|
makeTable(`
|
|
CREATE TABLE IF NOT EXISTS Chikinz (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
bandId INTEGER NOT NULL,
|
|
weight REAL NOT NULL,
|
|
killDate DATE,
|
|
wrapDate DATE NOT NULL,
|
|
sellDate DATE,
|
|
misc TEXT
|
|
);`);
|
|
|
|
makeTable(`
|
|
CREATE TABLE IF NOT EXISTS Bandz (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
name TEXT,
|
|
receiveDate DATE,
|
|
misc TEXT
|
|
);`);
|
|
|
|
function addChikin(db, chikin) {
|
|
const sql_insert = 'INSERT INTO Chikinz (bandId, weight, killDate, wrapDate) VALUES (?, ?, ?, ?);';
|
|
const {bandId, weight, killDate, wrapDate} = chikin;
|
|
return new Promise((resolve, reject) => {
|
|
db.run(sql_insert, [bandId, weight, killDate, wrapDate], function(err) {
|
|
if (err) {
|
|
return reject(err);
|
|
}
|
|
resolve(this);
|
|
});
|
|
});
|
|
}
|
|
|
|
function getBandz(db) {
|
|
return new Promise((resolve, reject) => {
|
|
const bandz = [];
|
|
db.each('SELECT id, name from Bandz', (err, row) => {
|
|
if (err) {
|
|
return reject(err);
|
|
}
|
|
bandz.push(row);
|
|
}, (err, rows) => {
|
|
if (bandz.length !== rows) {
|
|
return reject('did not store all rows');
|
|
}
|
|
resolve(bandz);
|
|
});
|
|
});
|
|
}
|
|
|
|
function getChikin(db, chikinId) {
|
|
return new Promise((resolve, reject) => {
|
|
db.get('SELECT * from Chikinz where id=?', chikinId, (err, row) => {
|
|
if (err) {
|
|
return reject(err);
|
|
}
|
|
resolve(row);
|
|
});
|
|
});
|
|
}
|
|
|
|
const authenticateJWT = (req, res, next) => {
|
|
const authHeader = req.headers.authorization;
|
|
|
|
if (authHeader) {
|
|
const token = authHeader.split(' ')[1];
|
|
|
|
jwt.verify(token, accessTokenSecret, (err, payload) => {
|
|
if (err) {
|
|
console.log(err);
|
|
return res.sendStatus(403);
|
|
}
|
|
if (new Date().getTime() > payload.expiration) {
|
|
console.log('expired token');
|
|
return res.sendStatus(403);
|
|
}
|
|
|
|
req.auth = payload;
|
|
next();
|
|
});
|
|
} else {
|
|
res.sendStatus(401);
|
|
}
|
|
};
|
|
|
|
const app = express();
|
|
|
|
app.use(bodyParser.json());
|
|
app.use(cors());
|
|
|
|
app.listen(3000, () => {
|
|
console.log('Server started (http://localhost:3000/)!');
|
|
});
|
|
|
|
|
|
// all access points below
|
|
|
|
app.get("/", (req, res) => {
|
|
res.send("This is not the way.");
|
|
});
|
|
|
|
app.get('/bandz', authenticateJWT, async (req, res) => {
|
|
const bandz = await getBandz(db);
|
|
res.json({message: 'This is the way.', bandz});
|
|
});
|
|
|
|
app.post('/toktok', (req, res) => {
|
|
const {password} = req.body;
|
|
|
|
if (password != 'goldchocoboisbestchocobo.goldchocoboisonlychocobo') {
|
|
return res.json({message: 'This is not the way.'});
|
|
}
|
|
|
|
// 20-hour tokens
|
|
const expiration = new Date().getTime() + 20 * 3600 * 1000;
|
|
const token = jwt.sign({expiration}, accessTokenSecret);
|
|
|
|
res.json({message: 'This is the way.', token});
|
|
});
|
|
|
|
app.post('/wrap', authenticateJWT, async (req, res) => {
|
|
const chikin = req.body;
|
|
console.log(chikin);
|
|
const {lastID} = await addChikin(db, chikin);
|
|
res.json({message: 'This is the way.', chikinId: lastID});
|
|
});
|
|
|
|
app.post('/print', authenticateJWT, async (req, res) => {
|
|
const {chikinId} = req.body;
|
|
|
|
const qr_url = `http://lafermedumalpas.fr/chikinz/${chikinId}`;
|
|
const chikin = await getChikin(db, chikinId);
|
|
const weight = chikin.weight / 1000;
|
|
const line0 = 'Poulet fermier bio';
|
|
const line1 = `${weight.toFixed(2)} kg`;
|
|
|
|
const pricePerKg = 12;
|
|
const price = weight * pricePerKg;
|
|
const line2 = `${pricePerKg.toFixed(2)} €/kg - ${price.toFixed(2)} €`;
|
|
|
|
// const args = ['/Users/paul/scratch/printer/catprint.py',
|
|
// '--address', '0DE203E8-0E8F-4361-9E80-D9C3794612A4',
|
|
// '--template0', [qr_url, line0, line1, line2].join(';'),
|
|
// '--feed',
|
|
// ];
|
|
const args = ['/Users/paul/scratch/printer/catclient.py',
|
|
'--template0', [qr_url, line0, line1, line2].join(';'),
|
|
'--feed',
|
|
];
|
|
|
|
const proc = child_process.spawn('python', args);
|
|
proc.stdout.on('data', data => console.log(`stdout: ${data}`));
|
|
proc.stderr.on('data', data => console.log(`stderr: ${data}`));
|
|
|
|
res.json({message: 'This is the way.'});
|
|
});
|
|
|
|
// catch errors
|
|
|
|
app.use((err, req, res, next) => {
|
|
console.error(err);
|
|
res.status(500).json({
|
|
message: 'This is not the way.',
|
|
error: err.message,
|
|
});
|
|
});
|