Initial content
This commit is contained in:
Binary file not shown.
@@ -0,0 +1,27 @@
|
||||
DROP TABLE IF EXISTS Results;
|
||||
DROP TABLE IF EXISTS Calculations;
|
||||
DROP TABLE IF EXISTS People;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `Calculations` (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, `age` INTEGER,
|
||||
years INTEGER, `nextage` INTEGER);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `People` (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(255));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `Results` (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
calculationId INTEGER REFERENCES `Calculations` (`id`)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
personId INTEGER REFERENCES `People` (`id`)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE);
|
||||
|
||||
INSERT INTO Calculations (id, age, years, nextage) VALUES
|
||||
(1, 35, 5, 40), (2, 35, 10, 45);
|
||||
|
||||
INSERT INTO People (id, name) VALUES
|
||||
(1, 'Alice'), (2, "Bob");
|
||||
|
||||
INSERT INTO Results (calculationId, personId) VALUES
|
||||
(1, 1), (2, 2), (2, 1);
|
||||
@@ -0,0 +1,5 @@
|
||||
[
|
||||
{ "city": "London", "population": 8982000 },
|
||||
{ "city": "Paris", "population": 2161000 },
|
||||
{ "city": "Beijing", "population": 21540000 }
|
||||
]
|
||||
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.FeathersWrapper = void 0;
|
||||
class FeathersWrapper {
|
||||
ws;
|
||||
constructor(ws) {
|
||||
this.ws = ws;
|
||||
}
|
||||
get(id) {
|
||||
return this.ws.getOne(id);
|
||||
}
|
||||
find(params) {
|
||||
return this.ws.getMany(params.query);
|
||||
}
|
||||
create(data, params) {
|
||||
return this.ws.store(data);
|
||||
}
|
||||
remove(id, params) {
|
||||
return this.ws.delete(id);
|
||||
}
|
||||
update(id, data, params) {
|
||||
return this.ws.replace(id, data);
|
||||
}
|
||||
patch(id, data, params) {
|
||||
return this.ws.modify(id, data);
|
||||
}
|
||||
}
|
||||
exports.FeathersWrapper = FeathersWrapper;
|
||||
@@ -0,0 +1,73 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createAdapter = void 0;
|
||||
const validation_types_1 = require("./validation_types");
|
||||
function createAdapter(app, ws, baseUrl) {
|
||||
app.get(baseUrl, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.getMany(req.query));
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
app.get(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
const data = await ws.getOne((req.params.id));
|
||||
if (data == undefined) {
|
||||
resp.writeHead(404);
|
||||
}
|
||||
else {
|
||||
resp.json(data);
|
||||
}
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
app.post(baseUrl, async (req, resp) => {
|
||||
try {
|
||||
const data = await ws.store(req.body);
|
||||
resp.json(data);
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
app.delete(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.delete(req.params.id));
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
app.put(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.replace(req.params.id, req.body));
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
app.patch(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.modify(req.params.id, req.body));
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
const writeErrorResponse = (err, resp) => {
|
||||
console.error(err);
|
||||
resp.writeHead(err instanceof validation_types_1.ValidationError ? 400 : 500);
|
||||
resp.end();
|
||||
};
|
||||
}
|
||||
exports.createAdapter = createAdapter;
|
||||
@@ -0,0 +1,51 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createApi = void 0;
|
||||
const results_api_1 = require("./results_api");
|
||||
const validation_adapter_1 = require("./validation_adapter");
|
||||
const results_api_validation_1 = require("./results_api_validation");
|
||||
const feathers_adapter_1 = require("./feathers_adapter");
|
||||
const feathers_1 = require("@feathersjs/feathers");
|
||||
const express_1 = __importStar(require("@feathersjs/express"));
|
||||
const validation_types_1 = require("./validation_types");
|
||||
const createApi = (app) => {
|
||||
// createAdapter(app, new Validator(new ResultWebService(),
|
||||
// ResultWebServiceValidation), "/api/results");
|
||||
const feathersApp = (0, express_1.default)((0, feathers_1.feathers)(), app).configure((0, express_1.rest)());
|
||||
const service = new validation_adapter_1.Validator(new results_api_1.ResultWebService(), results_api_validation_1.ResultWebServiceValidation);
|
||||
feathersApp.use('/api/results', new feathers_adapter_1.FeathersWrapper(service));
|
||||
feathersApp.hooks({
|
||||
error: {
|
||||
all: [(ctx) => {
|
||||
if (ctx.error instanceof validation_types_1.ValidationError) {
|
||||
ctx.http = { status: 400 };
|
||||
ctx.error = undefined;
|
||||
}
|
||||
}]
|
||||
}
|
||||
});
|
||||
};
|
||||
exports.createApi = createApi;
|
||||
@@ -0,0 +1,68 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ResultWebService = void 0;
|
||||
const data_1 = __importDefault(require("../data"));
|
||||
const jsonpatch = __importStar(require("fast-json-patch"));
|
||||
const validation_functions_1 = require("./validation_functions");
|
||||
const results_api_validation_1 = require("./results_api_validation");
|
||||
class ResultWebService {
|
||||
getOne(id) {
|
||||
return data_1.default.getResultById(id);
|
||||
}
|
||||
getMany(query) {
|
||||
if (query.name) {
|
||||
return data_1.default.getResultsByName(query.name, 10);
|
||||
}
|
||||
else {
|
||||
return data_1.default.getAllResults(10);
|
||||
}
|
||||
}
|
||||
async store(data) {
|
||||
const { name, age, years } = data;
|
||||
const nextage = age + years;
|
||||
const id = await data_1.default.saveResult({ id: 0, name, age,
|
||||
years, nextage });
|
||||
return await data_1.default.getResultById(id);
|
||||
}
|
||||
delete(id) {
|
||||
return data_1.default.delete(Number.parseInt(id));
|
||||
}
|
||||
replace(id, data) {
|
||||
const { name, age, years, nextage } = data;
|
||||
const validated = (0, validation_functions_1.validateModel)({ name, age, years, nextage }, results_api_validation_1.ResultModelValidation);
|
||||
return data_1.default.update({ id, ...validated });
|
||||
}
|
||||
async modify(id, data) {
|
||||
const dbData = await this.getOne(id);
|
||||
if (dbData !== undefined) {
|
||||
return await this.replace(id, jsonpatch.applyPatch(dbData, data).newDocument);
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.ResultWebService = ResultWebService;
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ResultModelValidation = exports.ResultWebServiceValidation = void 0;
|
||||
const validator_1 = __importDefault(require("validator"));
|
||||
const intValidator = {
|
||||
validation: [val => validator_1.default.isInt(val.toString())],
|
||||
converter: (val) => Number.parseInt(val)
|
||||
};
|
||||
const partialResultValidator = {
|
||||
name: [(val) => !validator_1.default.isEmpty(val)],
|
||||
age: intValidator,
|
||||
years: intValidator
|
||||
};
|
||||
exports.ResultWebServiceValidation = {
|
||||
keyValidator: intValidator,
|
||||
store: partialResultValidator,
|
||||
replace: {
|
||||
...partialResultValidator,
|
||||
nextage: intValidator
|
||||
}
|
||||
};
|
||||
exports.ResultModelValidation = {
|
||||
propertyRules: { ...partialResultValidator, nextage: intValidator },
|
||||
modelRule: [(m) => m.nextage === m.age + m.years]
|
||||
};
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Validator = void 0;
|
||||
const validation_functions_1 = require("./validation_functions");
|
||||
class Validator {
|
||||
ws;
|
||||
validation;
|
||||
constructor(ws, validation) {
|
||||
this.ws = ws;
|
||||
this.validation = validation;
|
||||
}
|
||||
getOne(id) {
|
||||
return this.ws.getOne(this.validateId(id));
|
||||
}
|
||||
getMany(query) {
|
||||
if (this.validation.getMany) {
|
||||
query = (0, validation_functions_1.validate)(query, this.validation.getMany);
|
||||
}
|
||||
return this.ws.getMany(query);
|
||||
}
|
||||
store(data) {
|
||||
if (this.validation.store) {
|
||||
data = (0, validation_functions_1.validate)(data, this.validation.store);
|
||||
}
|
||||
return this.ws.store(data);
|
||||
}
|
||||
delete(id) {
|
||||
return this.ws.delete(this.validateId(id));
|
||||
}
|
||||
replace(id, data) {
|
||||
if (this.validation.replace) {
|
||||
data = (0, validation_functions_1.validate)(data, this.validation.replace);
|
||||
}
|
||||
return this.ws.replace(this.validateId(id), data);
|
||||
}
|
||||
modify(id, data) {
|
||||
if (this.validation.modify) {
|
||||
data = (0, validation_functions_1.validate)(data, this.validation.modify);
|
||||
}
|
||||
return this.ws.modify(this.validateId(id), data);
|
||||
}
|
||||
validateId(val) {
|
||||
return (0, validation_functions_1.validateIdProperty)(val, this.validation);
|
||||
}
|
||||
}
|
||||
exports.Validator = Validator;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.validateModel = exports.validateIdProperty = exports.validate = void 0;
|
||||
const validation_types_1 = require("./validation_types");
|
||||
function validate(data, reqs) {
|
||||
let validatedData = {};
|
||||
Object.entries(reqs).forEach(([prop, rule]) => {
|
||||
const [valid, value] = applyRule(data[prop], rule);
|
||||
if (valid) {
|
||||
validatedData[prop] = value;
|
||||
}
|
||||
else {
|
||||
throw new validation_types_1.ValidationError(prop, "Validation Error");
|
||||
}
|
||||
});
|
||||
return validatedData;
|
||||
}
|
||||
exports.validate = validate;
|
||||
function applyRule(val, rule) {
|
||||
const required = Array.isArray(rule) ? true : rule.required;
|
||||
const checks = Array.isArray(rule) ? rule : rule.validation;
|
||||
const convert = Array.isArray(rule) ? (v) => v : rule.converter;
|
||||
if (val === null || val == undefined || val === "") {
|
||||
return [required ? false : true, val];
|
||||
}
|
||||
let valid = true;
|
||||
checks.forEach(check => {
|
||||
if (!check(val)) {
|
||||
valid = false;
|
||||
}
|
||||
});
|
||||
return [valid, convert ? convert(val) : val];
|
||||
}
|
||||
function validateIdProperty(val, v) {
|
||||
if (v.keyValidator) {
|
||||
const [valid, value] = applyRule(val, v.keyValidator);
|
||||
if (valid) {
|
||||
return value;
|
||||
}
|
||||
throw new validation_types_1.ValidationError("ID", "Validation Error");
|
||||
}
|
||||
return val;
|
||||
}
|
||||
exports.validateIdProperty = validateIdProperty;
|
||||
function validateModel(model, rules) {
|
||||
if (rules.propertyRules) {
|
||||
model = validate(model, rules.propertyRules);
|
||||
}
|
||||
if (rules.modelRule) {
|
||||
const [valid, data] = applyRule(model, rules.modelRule);
|
||||
if (valid) {
|
||||
return data;
|
||||
}
|
||||
throw new validation_types_1.ValidationError("Model", "Validation Error");
|
||||
}
|
||||
}
|
||||
exports.validateModel = validateModel;
|
||||
@@ -0,0 +1,14 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValidationError = void 0;
|
||||
class ValidationError {
|
||||
name;
|
||||
message;
|
||||
constructor(name, message) {
|
||||
this.name = name;
|
||||
this.message = message;
|
||||
}
|
||||
stack;
|
||||
cause;
|
||||
}
|
||||
exports.ValidationError = ValidationError;
|
||||
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getJsonCookie = exports.getCookie = exports.setJsonCookie = exports.setCookie = void 0;
|
||||
// const setheaderName = "Set-Cookie";
|
||||
// const cookieSecret = "mysecret";
|
||||
const setCookie = (resp, name, val, opts) => {
|
||||
resp.cookie(name, val, {
|
||||
maxAge: 300 * 1000,
|
||||
sameSite: "strict",
|
||||
signed: true,
|
||||
...opts
|
||||
});
|
||||
};
|
||||
exports.setCookie = setCookie;
|
||||
const setJsonCookie = (resp, name, val) => {
|
||||
;
|
||||
(0, exports.setCookie)(resp, name, JSON.stringify(val));
|
||||
};
|
||||
exports.setJsonCookie = setJsonCookie;
|
||||
const getCookie = (req, key) => {
|
||||
return req.signedCookies[key];
|
||||
};
|
||||
exports.getCookie = getCookie;
|
||||
const getJsonCookie = (req, key) => {
|
||||
const cookie = (0, exports.getCookie)(req, key);
|
||||
return cookie ? JSON.parse(cookie) : undefined;
|
||||
};
|
||||
exports.getJsonCookie = getJsonCookie;
|
||||
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.validateCookie = exports.signCookie = void 0;
|
||||
const crypto_1 = require("crypto");
|
||||
const signCookie = (value, secret) => {
|
||||
return value + "." + (0, crypto_1.createHmac)("sha512", secret)
|
||||
.update(value).digest("base64url");
|
||||
};
|
||||
exports.signCookie = signCookie;
|
||||
const validateCookie = (value, secret) => {
|
||||
const cookieValue = value.split(".")[0];
|
||||
const compareBuf = Buffer.from((0, exports.signCookie)(cookieValue, secret));
|
||||
const candidateBuf = Buffer.from(value);
|
||||
if (compareBuf.length == candidateBuf.length &&
|
||||
(0, crypto_1.timingSafeEqual)(compareBuf, candidateBuf)) {
|
||||
return cookieValue;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
exports.validateCookie = validateCookie;
|
||||
@@ -0,0 +1,65 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.registerCustomTemplateEngine = void 0;
|
||||
const fs_1 = require("fs");
|
||||
const features = __importStar(require("./custom_features"));
|
||||
const renderTemplate = (path, context, callback) => {
|
||||
(0, fs_1.readFile)(path, (err, data) => {
|
||||
if (err != undefined) {
|
||||
callback("Cannot generate content", undefined);
|
||||
}
|
||||
else {
|
||||
callback(undefined, parseTemplate(data.toString(), { ...context, features }));
|
||||
}
|
||||
});
|
||||
};
|
||||
const parseTemplate = (template, context) => {
|
||||
const ctx = Object.keys(context)
|
||||
.map((k) => `const ${k} = context.${k}`)
|
||||
.join(";");
|
||||
const expr = /{{(.*)}}/gm;
|
||||
return template.toString().replaceAll(expr, (match, group) => {
|
||||
const evalFunc = (expr) => {
|
||||
return eval(`${ctx};${expr}`);
|
||||
};
|
||||
try {
|
||||
if (group.trim()[0] === "@") {
|
||||
group = `features.${group.trim().substring(1)}`;
|
||||
group = group.replace(/\)$/m, ", context, evalFunc)");
|
||||
}
|
||||
let result = evalFunc(group);
|
||||
if (expr.test(result)) {
|
||||
result = parseTemplate(result, context);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
catch (err) {
|
||||
return err;
|
||||
}
|
||||
});
|
||||
};
|
||||
const registerCustomTemplateEngine = (expressApp) => expressApp.engine("custom", renderTemplate);
|
||||
exports.registerCustomTemplateEngine = registerCustomTemplateEngine;
|
||||
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.conditional = exports.partial = exports.style = void 0;
|
||||
const fs_1 = require("fs");
|
||||
const style = (stylesheet) => {
|
||||
return `<link href="/css/${stylesheet}" rel="stylesheet" />`;
|
||||
};
|
||||
exports.style = style;
|
||||
const partial = (file, context) => {
|
||||
const path = `./${context.settings.views}/${file}.custom`;
|
||||
return (0, fs_1.readFileSync)(path, "utf-8");
|
||||
};
|
||||
exports.partial = partial;
|
||||
const conditional = (expression, trueFile, falseFile, context, evalFunc) => {
|
||||
return (0, exports.partial)(evalFunc(expression) ? trueFile : falseFile, context);
|
||||
};
|
||||
exports.conditional = conditional;
|
||||
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const orm_repository_1 = require("./orm_repository");
|
||||
const repository = new orm_repository_1.OrmRepository();
|
||||
exports.default = repository;
|
||||
@@ -0,0 +1,59 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.fromOrmModel = exports.addSeedData = exports.defineRelationships = exports.initializeModels = void 0;
|
||||
const sequelize_1 = require("sequelize");
|
||||
const orm_models_1 = require("./orm_models");
|
||||
const primaryKey = {
|
||||
id: {
|
||||
type: sequelize_1.DataTypes.INTEGER,
|
||||
autoIncrement: true,
|
||||
primaryKey: true
|
||||
}
|
||||
};
|
||||
const initializeModels = (sequelize) => {
|
||||
orm_models_1.Person.init({
|
||||
...primaryKey,
|
||||
name: { type: sequelize_1.DataTypes.STRING }
|
||||
}, { sequelize });
|
||||
orm_models_1.Calculation.init({
|
||||
...primaryKey,
|
||||
age: { type: sequelize_1.DataTypes.INTEGER },
|
||||
years: { type: sequelize_1.DataTypes.INTEGER },
|
||||
nextage: { type: sequelize_1.DataTypes.INTEGER },
|
||||
}, { sequelize });
|
||||
orm_models_1.ResultModel.init({
|
||||
...primaryKey,
|
||||
}, { sequelize });
|
||||
};
|
||||
exports.initializeModels = initializeModels;
|
||||
const defineRelationships = () => {
|
||||
orm_models_1.ResultModel.belongsTo(orm_models_1.Person, { foreignKey: "personId" });
|
||||
orm_models_1.ResultModel.belongsTo(orm_models_1.Calculation, { foreignKey: "calculationId" });
|
||||
};
|
||||
exports.defineRelationships = defineRelationships;
|
||||
const addSeedData = async (sequelize) => {
|
||||
await sequelize.query(`
|
||||
INSERT INTO Calculations
|
||||
(id, age, years, nextage, createdAt, updatedAt) VALUES
|
||||
(1, 35, 5, 40, date(), date()),
|
||||
(2, 35, 10, 45, date(), date())`);
|
||||
await sequelize.query(`
|
||||
INSERT INTO People (id, name, createdAt, updatedAt) VALUES
|
||||
(1, 'Alice', date(), date()), (2, "Bob", date(), date())`);
|
||||
await sequelize.query(`
|
||||
INSERT INTO ResultModels
|
||||
(calculationId, personId, createdAt, updatedAt) VALUES
|
||||
(1, 1, date(), date()), (2, 2, date(), date()),
|
||||
(2, 1, date(), date());`);
|
||||
};
|
||||
exports.addSeedData = addSeedData;
|
||||
const fromOrmModel = (model) => {
|
||||
return {
|
||||
id: model?.id || 0,
|
||||
name: model?.Person?.name || "",
|
||||
age: model?.Calculation?.age || 0,
|
||||
years: model?.Calculation?.years || 0,
|
||||
nextage: model?.Calculation?.nextage || 0
|
||||
};
|
||||
};
|
||||
exports.fromOrmModel = fromOrmModel;
|
||||
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ResultModel = exports.Calculation = exports.Person = void 0;
|
||||
const sequelize_1 = require("sequelize");
|
||||
class Person extends sequelize_1.Model {
|
||||
}
|
||||
exports.Person = Person;
|
||||
class Calculation extends sequelize_1.Model {
|
||||
}
|
||||
exports.Calculation = Calculation;
|
||||
class ResultModel extends sequelize_1.Model {
|
||||
}
|
||||
exports.ResultModel = ResultModel;
|
||||
@@ -0,0 +1,88 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.OrmRepository = void 0;
|
||||
const sequelize_1 = require("sequelize");
|
||||
const orm_helpers_1 = require("./orm_helpers");
|
||||
const orm_models_1 = require("./orm_models");
|
||||
class OrmRepository {
|
||||
sequelize;
|
||||
constructor() {
|
||||
this.sequelize = new sequelize_1.Sequelize({
|
||||
dialect: "sqlite",
|
||||
storage: "orm_age.db",
|
||||
logging: console.log,
|
||||
logQueryParameters: true
|
||||
});
|
||||
this.initModelAndDatabase();
|
||||
}
|
||||
async initModelAndDatabase() {
|
||||
(0, orm_helpers_1.initializeModels)(this.sequelize);
|
||||
(0, orm_helpers_1.defineRelationships)();
|
||||
await this.sequelize.drop();
|
||||
await this.sequelize.sync();
|
||||
await (0, orm_helpers_1.addSeedData)(this.sequelize);
|
||||
}
|
||||
async saveResult(r) {
|
||||
return await this.sequelize.transaction(async (tx) => {
|
||||
const [person] = await orm_models_1.Person.findOrCreate({
|
||||
where: { name: r.name },
|
||||
transaction: tx
|
||||
});
|
||||
const [calculation] = await orm_models_1.Calculation.findOrCreate({
|
||||
where: {
|
||||
age: r.age, years: r.years, nextage: r.nextage
|
||||
},
|
||||
transaction: tx
|
||||
});
|
||||
return (await orm_models_1.ResultModel.create({
|
||||
personId: person.id, calculationId: calculation.id
|
||||
}, { transaction: tx })).id;
|
||||
});
|
||||
}
|
||||
async getAllResults(limit) {
|
||||
return (await orm_models_1.ResultModel.findAll({
|
||||
include: [orm_models_1.Person, orm_models_1.Calculation],
|
||||
limit,
|
||||
order: [["id", "DESC"]]
|
||||
})).map(row => (0, orm_helpers_1.fromOrmModel)(row));
|
||||
}
|
||||
async getResultsByName(name, limit) {
|
||||
return (await orm_models_1.ResultModel.findAll({
|
||||
include: [orm_models_1.Person, orm_models_1.Calculation],
|
||||
where: {
|
||||
"$Person.name$": name
|
||||
},
|
||||
limit, order: [["id", "DESC"]]
|
||||
})).map(row => (0, orm_helpers_1.fromOrmModel)(row));
|
||||
}
|
||||
async getResultById(id) {
|
||||
const model = await orm_models_1.ResultModel.findByPk(id, {
|
||||
include: [orm_models_1.Person, orm_models_1.Calculation]
|
||||
});
|
||||
return model ? (0, orm_helpers_1.fromOrmModel)(model) : undefined;
|
||||
}
|
||||
async delete(id) {
|
||||
const count = await orm_models_1.ResultModel.destroy({ where: { id } });
|
||||
return count == 1;
|
||||
}
|
||||
async update(r) {
|
||||
const mod = await this.sequelize.transaction(async (transaction) => {
|
||||
const stored = await orm_models_1.ResultModel.findByPk(r.id);
|
||||
if (stored !== null) {
|
||||
const [person] = await orm_models_1.Person.findOrCreate({
|
||||
where: { name: r.name }, transaction
|
||||
});
|
||||
const [calculation] = await orm_models_1.Calculation.findOrCreate({
|
||||
where: {
|
||||
age: r.age, years: r.years, nextage: r.nextage
|
||||
}, transaction
|
||||
});
|
||||
stored.personId = person.id;
|
||||
stored.calculationId = calculation.id;
|
||||
return await stored.save({ transaction });
|
||||
}
|
||||
});
|
||||
return mod ? this.getResultById(mod.id) : undefined;
|
||||
}
|
||||
}
|
||||
exports.OrmRepository = OrmRepository;
|
||||
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
@@ -0,0 +1,38 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.TransactionHelper = void 0;
|
||||
class TransactionHelper {
|
||||
steps = [];
|
||||
add(sql, params) {
|
||||
this.steps.push([sql, params]);
|
||||
return this;
|
||||
}
|
||||
run(db) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let index = 0;
|
||||
let lastRow = NaN;
|
||||
const cb = (err, rowID) => {
|
||||
if (err) {
|
||||
db.run("ROLLBACK", () => reject());
|
||||
}
|
||||
else {
|
||||
lastRow = rowID ? rowID : lastRow;
|
||||
if (++index === this.steps.length) {
|
||||
db.run("COMMIT", () => resolve(lastRow));
|
||||
}
|
||||
else {
|
||||
this.runStep(index, db, cb);
|
||||
}
|
||||
}
|
||||
};
|
||||
db.run("BEGIN", () => this.runStep(0, db, cb));
|
||||
});
|
||||
}
|
||||
runStep(idx, db, cb) {
|
||||
const [sql, params] = this.steps[idx];
|
||||
db.run(sql, params, function (err) {
|
||||
cb(err, this.lastID);
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.TransactionHelper = TransactionHelper;
|
||||
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.insertResult = exports.insertCalculation = exports.insertPerson = exports.queryByNameSql = exports.queryAllSql = void 0;
|
||||
const baseSql = `
|
||||
SELECT Results.*, name, age, years, nextage FROM Results
|
||||
INNER JOIN People ON personId = People.id
|
||||
INNER JOIN Calculations ON calculationId = Calculations.id`;
|
||||
const endSql = `ORDER BY id DESC LIMIT $limit`;
|
||||
exports.queryAllSql = `${baseSql} ${endSql}`;
|
||||
exports.queryByNameSql = `${baseSql} WHERE name = $name ${endSql}`;
|
||||
exports.insertPerson = `
|
||||
INSERT INTO People (name)
|
||||
SELECT $name
|
||||
WHERE NOT EXISTS (SELECT name FROM People WHERE name = $name)`;
|
||||
exports.insertCalculation = `
|
||||
INSERT INTO Calculations (age, years, nextage)
|
||||
SELECT $age, $years, $nextage
|
||||
WHERE NOT EXISTS
|
||||
(SELECT age, years, nextage FROM Calculations
|
||||
WHERE age = $age AND years = $years AND nextage = $nextage)`;
|
||||
exports.insertResult = `
|
||||
INSERT INTO Results (personId, calculationId)
|
||||
SELECT People.id as personId, Calculations.id as calculationId from People
|
||||
CROSS JOIN Calculations
|
||||
WHERE People.name = $name
|
||||
AND Calculations.age = $age
|
||||
AND Calculations.years = $years
|
||||
AND Calculations.nextage = $nextage`;
|
||||
@@ -0,0 +1,48 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SqlRepository = void 0;
|
||||
const fs_1 = require("fs");
|
||||
const sqlite3_1 = require("sqlite3");
|
||||
const sql_queries_1 = require("./sql_queries");
|
||||
const sql_helpers_1 = require("./sql_helpers");
|
||||
class SqlRepository {
|
||||
db;
|
||||
constructor() {
|
||||
this.db = new sqlite3_1.Database("age.db");
|
||||
this.db.exec((0, fs_1.readFileSync)("age.sql").toString(), err => {
|
||||
if (err != undefined)
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
async saveResult(r) {
|
||||
return await new sql_helpers_1.TransactionHelper()
|
||||
.add(sql_queries_1.insertPerson, { $name: r.name })
|
||||
.add(sql_queries_1.insertCalculation, {
|
||||
$age: r.age, $years: r.years, $nextage: r.nextage
|
||||
})
|
||||
.add(sql_queries_1.insertResult, {
|
||||
$name: r.name,
|
||||
$age: r.age, $years: r.years, $nextage: r.nextage
|
||||
})
|
||||
.run(this.db);
|
||||
}
|
||||
getAllResults($limit) {
|
||||
return this.executeQuery(sql_queries_1.queryAllSql, { $limit });
|
||||
}
|
||||
getResultsByName($name, $limit) {
|
||||
return this.executeQuery(sql_queries_1.queryByNameSql, { $name, $limit });
|
||||
}
|
||||
executeQuery(sql, params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, params, (err, rows) => {
|
||||
if (err == undefined) {
|
||||
resolve(rows);
|
||||
}
|
||||
else {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.SqlRepository = SqlRepository;
|
||||
@@ -0,0 +1,36 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.registerFormRoutes = exports.registerFormMiddleware = void 0;
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const data_1 = __importDefault(require("./data"));
|
||||
const cookie_parser_1 = __importDefault(require("cookie-parser"));
|
||||
const session_helpers_1 = require("./sessions/session_helpers");
|
||||
const rowLimit = 10;
|
||||
const registerFormMiddleware = (app) => {
|
||||
app.use(express_1.default.urlencoded({ extended: true }));
|
||||
app.use((0, cookie_parser_1.default)("mysecret"));
|
||||
app.use((0, session_helpers_1.sessionMiddleware)());
|
||||
};
|
||||
exports.registerFormMiddleware = registerFormMiddleware;
|
||||
const registerFormRoutes = (app) => {
|
||||
app.get("/form", async (req, resp) => {
|
||||
resp.render("data", { data: await data_1.default.getAllResults(rowLimit) });
|
||||
});
|
||||
app.post("/form/delete/:id", async (req, resp) => {
|
||||
const id = Number.parseInt(req.params["id"]);
|
||||
await data_1.default.delete(id);
|
||||
resp.redirect("/form");
|
||||
resp.end();
|
||||
});
|
||||
app.post("/form/add", async (req, resp) => {
|
||||
const nextage = Number.parseInt(req.body["age"])
|
||||
+ Number.parseInt(req.body["years"]);
|
||||
await data_1.default.saveResult({ ...req.body, nextage });
|
||||
resp.redirect("/form");
|
||||
resp.end();
|
||||
});
|
||||
};
|
||||
exports.registerFormRoutes = registerFormRoutes;
|
||||
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.santizeValue = void 0;
|
||||
const matchPattern = /[&<>="'`]/g;
|
||||
const characterMappings = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
"\"": """,
|
||||
"=": "=",
|
||||
"'": "'",
|
||||
"`": "`"
|
||||
};
|
||||
const santizeValue = (value) => value?.replace(matchPattern, match => characterMappings[match]);
|
||||
exports.santizeValue = santizeValue;
|
||||
@@ -0,0 +1,34 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const http_1 = require("http");
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const http_proxy_1 = __importDefault(require("http-proxy"));
|
||||
const helmet_1 = __importDefault(require("helmet"));
|
||||
const express_handlebars_1 = require("express-handlebars");
|
||||
const forms_1 = require("./forms");
|
||||
const api_1 = require("./api");
|
||||
const port = 5000;
|
||||
const expressApp = (0, express_1.default)();
|
||||
const proxy = http_proxy_1.default.createProxyServer({
|
||||
target: "http://localhost:5100", ws: true
|
||||
});
|
||||
expressApp.set("views", "templates/server");
|
||||
expressApp.engine("handlebars", (0, express_handlebars_1.engine)());
|
||||
expressApp.set("view engine", "handlebars");
|
||||
expressApp.use((0, helmet_1.default)());
|
||||
expressApp.use(express_1.default.json({
|
||||
type: ["application/json", "application/json-patch+json"]
|
||||
}));
|
||||
(0, forms_1.registerFormMiddleware)(expressApp);
|
||||
(0, forms_1.registerFormRoutes)(expressApp);
|
||||
(0, api_1.createApi)(expressApp);
|
||||
expressApp.use("^/$", (req, resp) => resp.redirect("/form"));
|
||||
expressApp.use(express_1.default.static("static"));
|
||||
expressApp.use(express_1.default.static("node_modules/bootstrap/dist"));
|
||||
expressApp.use((req, resp) => proxy.web(req, resp));
|
||||
const server = (0, http_1.createServer)(expressApp);
|
||||
server.on('upgrade', (req, socket, head) => proxy.ws(req, socket, head));
|
||||
server.listen(port, () => console.log(`HTTP Server listening on port ${port}`));
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.MemoryRepository = void 0;
|
||||
const crypto_1 = require("crypto");
|
||||
class MemoryRepository {
|
||||
store = new Map();
|
||||
async createSession() {
|
||||
return { id: (0, crypto_1.randomUUID)(), data: {} };
|
||||
}
|
||||
async getSession(id) {
|
||||
const wrapper = this.store.get(id);
|
||||
if (wrapper && wrapper.expires > new Date(Date.now())) {
|
||||
return structuredClone(wrapper.session);
|
||||
}
|
||||
}
|
||||
async saveSession(session, expires) {
|
||||
this.store.set(session.id, { session, expires });
|
||||
}
|
||||
async touchSession(session, expires) {
|
||||
const wrapper = this.store.get(session.id);
|
||||
if (wrapper) {
|
||||
wrapper.expires = expires;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.MemoryRepository = MemoryRepository;
|
||||
@@ -0,0 +1,34 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.customSessionMiddleware = void 0;
|
||||
//import { MemoryRepository } from "./memory_repository";
|
||||
const cookies_1 = require("../cookies");
|
||||
const orm_repository_1 = require("./orm_repository");
|
||||
const session_cookie_name = "custom_session";
|
||||
const expiry_seconds = 300;
|
||||
const getExpiryDate = () => new Date(Date.now() + (expiry_seconds * 1000));
|
||||
const customSessionMiddleware = () => {
|
||||
//const repo: SessionRepository = new MemoryRepository();
|
||||
const repo = new orm_repository_1.OrmRepository();
|
||||
return async (req, resp, next) => {
|
||||
const id = (0, cookies_1.getCookie)(req, session_cookie_name);
|
||||
const session = (id ? await repo.getSession(id) : undefined)
|
||||
?? await repo.createSession();
|
||||
req.session = session;
|
||||
(0, cookies_1.setCookie)(resp, session_cookie_name, session.id, {
|
||||
maxAge: expiry_seconds * 1000
|
||||
});
|
||||
resp.once("finish", async () => {
|
||||
if (Object.keys(session.data).length > 0) {
|
||||
if (req.method == "POST") {
|
||||
await repo.saveSession(session, getExpiryDate());
|
||||
}
|
||||
else {
|
||||
await repo.touchSession(session, getExpiryDate());
|
||||
}
|
||||
}
|
||||
});
|
||||
next();
|
||||
};
|
||||
};
|
||||
exports.customSessionMiddleware = customSessionMiddleware;
|
||||
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initializeModel = exports.SessionModel = void 0;
|
||||
const sequelize_1 = require("sequelize");
|
||||
class SessionModel extends sequelize_1.Model {
|
||||
}
|
||||
exports.SessionModel = SessionModel;
|
||||
const initializeModel = (sequelize) => {
|
||||
SessionModel.init({
|
||||
id: { type: sequelize_1.DataTypes.STRING, primaryKey: true },
|
||||
data: { type: sequelize_1.DataTypes.JSON },
|
||||
expires: { type: sequelize_1.DataTypes.DATE }
|
||||
}, { sequelize });
|
||||
};
|
||||
exports.initializeModel = initializeModel;
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.OrmRepository = void 0;
|
||||
const sequelize_1 = require("sequelize");
|
||||
const orm_models_1 = require("./orm_models");
|
||||
const crypto_1 = require("crypto");
|
||||
class OrmRepository {
|
||||
sequelize;
|
||||
constructor() {
|
||||
this.sequelize = new sequelize_1.Sequelize({
|
||||
dialect: "sqlite",
|
||||
storage: "orm_sessions.db",
|
||||
logging: console.log,
|
||||
logQueryParameters: true
|
||||
});
|
||||
this.initModelAndDatabase();
|
||||
}
|
||||
async initModelAndDatabase() {
|
||||
(0, orm_models_1.initializeModel)(this.sequelize);
|
||||
await this.sequelize.drop();
|
||||
await this.sequelize.sync();
|
||||
}
|
||||
async createSession() {
|
||||
return { id: (0, crypto_1.randomUUID)(), data: {} };
|
||||
}
|
||||
async getSession(id) {
|
||||
const dbsession = await orm_models_1.SessionModel.findOne({
|
||||
where: { id, expires: { [sequelize_1.Op.gt]: new Date(Date.now()) } }
|
||||
});
|
||||
if (dbsession) {
|
||||
return { id, data: dbsession.data };
|
||||
}
|
||||
}
|
||||
async saveSession(session, expires) {
|
||||
await orm_models_1.SessionModel.upsert({
|
||||
id: session.id,
|
||||
data: session.data,
|
||||
expires
|
||||
});
|
||||
}
|
||||
async touchSession(session, expires) {
|
||||
await orm_models_1.SessionModel.update({ expires }, { where: { id: session.id } });
|
||||
}
|
||||
}
|
||||
exports.OrmRepository = OrmRepository;
|
||||
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.sessionMiddleware = exports.getSession = void 0;
|
||||
//import { Session } from "./repository";
|
||||
const express_session_1 = __importDefault(require("express-session"));
|
||||
const connect_session_sequelize_1 = __importDefault(require("connect-session-sequelize"));
|
||||
const sequelize_1 = require("sequelize");
|
||||
const getSession = (req) => req.session;
|
||||
exports.getSession = getSession;
|
||||
const sessionMiddleware = () => {
|
||||
const sequelize = new sequelize_1.Sequelize({
|
||||
dialect: "sqlite",
|
||||
storage: "pkg_sessions.db"
|
||||
});
|
||||
const store = new ((0, connect_session_sequelize_1.default)(express_session_1.default.Store))({
|
||||
db: sequelize
|
||||
});
|
||||
store.sync();
|
||||
return (0, express_session_1.default)({
|
||||
secret: "mysecret",
|
||||
store: store,
|
||||
cookie: { maxAge: 300 * 1000, sameSite: "strict" },
|
||||
resave: false, saveUninitialized: false
|
||||
});
|
||||
};
|
||||
exports.sessionMiddleware = sessionMiddleware;
|
||||
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isOdd = exports.increment = exports.valueOrZero = exports.style = void 0;
|
||||
const style = (stylesheet) => {
|
||||
return `<link href="/css/${stylesheet}" rel="stylesheet" />`;
|
||||
};
|
||||
exports.style = style;
|
||||
const valueOrZero = (value) => {
|
||||
return value !== undefined ? value : 0;
|
||||
};
|
||||
exports.valueOrZero = valueOrZero;
|
||||
const increment = (value) => {
|
||||
return Number((0, exports.valueOrZero)(value)) + 1;
|
||||
};
|
||||
exports.increment = increment;
|
||||
const isOdd = (value) => {
|
||||
return Number((0, exports.valueOrZero)(value)) % 2;
|
||||
};
|
||||
exports.isOdd = isOdd;
|
||||
@@ -0,0 +1,9 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.testHandler = void 0;
|
||||
const testHandler = async (req, resp) => {
|
||||
resp.setHeader("Content-Type", "application/json");
|
||||
resp.json(req.body);
|
||||
resp.end();
|
||||
};
|
||||
exports.testHandler = testHandler;
|
||||
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getValidationResults = exports.validate = void 0;
|
||||
const validator_1 = __importDefault(require("validator"));
|
||||
const validate = (propName) => {
|
||||
const tests = {};
|
||||
const handler = (req, resp, next) => {
|
||||
const vreq = req;
|
||||
if (!vreq.validation) {
|
||||
vreq.validation = { results: {}, valid: true };
|
||||
}
|
||||
vreq.validation.results[propName] = { valid: true };
|
||||
Object.keys(tests).forEach(k => {
|
||||
let valid = vreq.validation.results[propName][k]
|
||||
= tests[k](req.body?.[propName]);
|
||||
if (!valid) {
|
||||
vreq.validation.results[propName].valid = false;
|
||||
vreq.validation.valid = false;
|
||||
}
|
||||
});
|
||||
next();
|
||||
};
|
||||
handler.required = () => {
|
||||
tests.required = (val) => !validator_1.default.isEmpty(val, { ignore_whitespace: true });
|
||||
return handler;
|
||||
};
|
||||
handler.minLength = (min) => {
|
||||
tests.minLength = (val) => validator_1.default.isLength(val, { min });
|
||||
return handler;
|
||||
};
|
||||
handler.isInteger = () => {
|
||||
tests.isInteger = (val) => validator_1.default.isInt(val);
|
||||
return handler;
|
||||
};
|
||||
return handler;
|
||||
};
|
||||
exports.validate = validate;
|
||||
const getValidationResults = (req) => {
|
||||
return req.validation || { valid: true };
|
||||
};
|
||||
exports.getValidationResults = getValidationResults;
|
||||
Binary file not shown.
Binary file not shown.
+9057
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"name": "part2app",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"server": "tsc-watch --noClear --onsuccess \"node dist/server/server.js\"",
|
||||
"client": "webpack serve",
|
||||
"start": "npm-run-all --parallel server client",
|
||||
"cmdline": "node --watch ./src/cmdline/main.mjs"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@feathersjs/express": "^5.0.14",
|
||||
"@feathersjs/feathers": "^5.0.14",
|
||||
"@inquirer/prompts": "^3.3.0",
|
||||
"bootstrap": "^5.3.2",
|
||||
"connect-session-sequelize": "^7.1.7",
|
||||
"cookie-parser": "^1.4.6",
|
||||
"express": "^4.18.2",
|
||||
"express-handlebars": "^7.1.2",
|
||||
"express-session": "^1.17.3",
|
||||
"fast-json-patch": "^3.1.1",
|
||||
"handlebars": "^4.7.8",
|
||||
"helmet": "^7.1.0",
|
||||
"http-proxy": "^1.18.1",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"sequelize": "^6.35.1",
|
||||
"sqlite3": "^5.1.6",
|
||||
"validator": "^13.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node20": "^20.1.2",
|
||||
"@types/cookie-parser": "^1.4.6",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/express-session": "^1.17.10",
|
||||
"@types/multer": "^1.4.11",
|
||||
"@types/node": "^20.6.1",
|
||||
"@types/validator": "^13.11.5",
|
||||
"handlebars-loader": "^1.7.3",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"tsc-watch": "^6.0.4",
|
||||
"typescript": "^5.2.2",
|
||||
"webpack": "^5.89.0",
|
||||
"webpack-cli": "^5.1.4",
|
||||
"webpack-dev-server": "^4.15.1"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// do nothing
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import validator from "validator";
|
||||
|
||||
export const validate = (propName, formdata) => {
|
||||
|
||||
const val = formdata.get(propName);
|
||||
const results = { };
|
||||
|
||||
const validationChain = {
|
||||
get propertyName() { return propName},
|
||||
get results () { return results }
|
||||
};
|
||||
validationChain.required = () => {
|
||||
results.required = !validator.isEmpty(val, { ignore_whitespace: true});
|
||||
return validationChain;
|
||||
}
|
||||
validationChain.minLength = (min) => {
|
||||
results.minLength = validator.isLength(val, { min});
|
||||
return validationChain;
|
||||
};
|
||||
validationChain.isInteger = () => {
|
||||
results.isInteger = validator.isInt(val);
|
||||
return validationChain;
|
||||
}
|
||||
return validationChain;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { select } from "@inquirer/prompts";
|
||||
import { ops } from "./operations.mjs";
|
||||
|
||||
(async function run() {
|
||||
let loop = true;
|
||||
while (loop) {
|
||||
const selection = await select({
|
||||
message: "Select an operation",
|
||||
choices: [...Object.keys(ops).map(k => {return { value: k }})]
|
||||
});
|
||||
await ops[selection]();
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,73 @@
|
||||
import { input } from "@inquirer/prompts";
|
||||
|
||||
const baseUrl = "http://localhost:5000";
|
||||
|
||||
export const ops = {
|
||||
|
||||
"Get All": () => sendRequest("GET", "/api/results"),
|
||||
|
||||
"Get Name": async () => {
|
||||
const name = await input({ message: "Name?"});
|
||||
await sendRequest("GET", `/api/results?name=${name}`);
|
||||
},
|
||||
|
||||
"Get ID": async () => {
|
||||
const id = await input({ message: "ID?"});
|
||||
await sendRequest("GET", `/api/results/${id}`);
|
||||
},
|
||||
|
||||
"Store": async () => {
|
||||
const values = {
|
||||
name: await input({message: "Name?"}),
|
||||
age: await input({message: "Age?"}),
|
||||
years: await input({message: "Years?"})
|
||||
};
|
||||
await sendRequest("POST", "/api/results", values);
|
||||
},
|
||||
|
||||
"Delete": async () => {
|
||||
const id = await input({ message: "ID?"});
|
||||
await sendRequest("DELETE", `/api/results/${id}`);
|
||||
},
|
||||
|
||||
"Replace": async () => {
|
||||
const id = await input({ message: "ID?"});
|
||||
const values = {
|
||||
name: await input({message: "Name?"}),
|
||||
age: await input({message: "Age?"}),
|
||||
years: await input({message: "Years?"}),
|
||||
nextage: await input({message: "Next Age?"})
|
||||
};
|
||||
await sendRequest("PUT", `/api/results/${id}`, values);
|
||||
},
|
||||
|
||||
"Modify": async () => {
|
||||
const id = await input({ message: "ID?"});
|
||||
const values = {
|
||||
name: await input({message: "Name?"}),
|
||||
age: await input({message: "Age?"}),
|
||||
years: await input({message: "Years?"}),
|
||||
nextage: await input({message: "Next Age?"})
|
||||
};
|
||||
await sendRequest("PATCH", `/api/results/${id}`,
|
||||
Object.entries(values).filter(([p, v]) => v !== "")
|
||||
.map(([p, v]) => ({ op: "replace", path: "/" + p, value: v})),
|
||||
"application/json-patch+json");
|
||||
},
|
||||
|
||||
"Exit": () => process.exit()
|
||||
}
|
||||
|
||||
const sendRequest = async (method, url, body, contentType) => {
|
||||
const response = await fetch(baseUrl + url, {
|
||||
method, headers: { "Content-Type": contentType ?? "application/json"},
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
if (response.status == 200) {
|
||||
const data = await response.json();
|
||||
(Array.isArray(data) ? data : [data])
|
||||
.forEach(elem => console.log(JSON.stringify(elem)));
|
||||
} else {
|
||||
console.log(response.status + " " + response.statusText);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Id, NullableId, Params } from "@feathersjs/feathers";
|
||||
import { WebService } from "./http_adapter";
|
||||
|
||||
export class FeathersWrapper<T> {
|
||||
|
||||
constructor(private ws: WebService<T>) {}
|
||||
|
||||
get(id: Id) {
|
||||
return this.ws.getOne(id);
|
||||
}
|
||||
|
||||
find(params: Params) {
|
||||
return this.ws.getMany(params.query);
|
||||
}
|
||||
|
||||
create(data: any, params: Params) {
|
||||
return this.ws.store(data);
|
||||
}
|
||||
|
||||
remove(id: NullableId, params: Params) {
|
||||
return this.ws.delete(id);
|
||||
}
|
||||
|
||||
update(id: NullableId, data: any, params: Params) {
|
||||
return this.ws.replace(id, data);
|
||||
}
|
||||
|
||||
patch(id: NullableId, data: any, params: Params) {
|
||||
return this.ws.modify(id, data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Express, Response } from "express";
|
||||
import { ValidationError } from "./validation_types";
|
||||
|
||||
export interface WebService<T> {
|
||||
getOne(id: any) : Promise<T | undefined>;
|
||||
getMany(query: any) : Promise<T[]>;
|
||||
store(data: any) : Promise<T | undefined>;
|
||||
delete(id: any): Promise<boolean>;
|
||||
replace(id: any, data: any): Promise<T | undefined>;
|
||||
modify(id: any, data: any): Promise<T | undefined>;
|
||||
}
|
||||
|
||||
export function createAdapter<T>(app: Express, ws: WebService<T>, baseUrl: string) {
|
||||
|
||||
app.get(baseUrl, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.getMany(req.query));
|
||||
resp.end();
|
||||
} catch (err) { writeErrorResponse(err, resp) }
|
||||
});
|
||||
|
||||
app.get(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
const data = await ws.getOne((req.params.id));
|
||||
if (data == undefined) {
|
||||
resp.writeHead(404);
|
||||
} else {
|
||||
resp.json(data);
|
||||
}
|
||||
resp.end();
|
||||
} catch (err) { writeErrorResponse(err, resp) }
|
||||
});
|
||||
|
||||
app.post(baseUrl, async (req, resp) => {
|
||||
try {
|
||||
const data = await ws.store(req.body);
|
||||
resp.json(data);
|
||||
resp.end();
|
||||
} catch (err) { writeErrorResponse(err, resp) }
|
||||
});
|
||||
|
||||
app.delete(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.delete(req.params.id));
|
||||
resp.end();
|
||||
} catch (err) { writeErrorResponse(err, resp) }
|
||||
});
|
||||
|
||||
app.put(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.replace(req.params.id, req.body));
|
||||
resp.end();
|
||||
} catch (err) { writeErrorResponse(err, resp) }
|
||||
});
|
||||
|
||||
app.patch(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.modify(req.params.id, req.body));
|
||||
resp.end();
|
||||
} catch (err) { writeErrorResponse(err, resp) }
|
||||
});
|
||||
|
||||
const writeErrorResponse = (err: any, resp: Response) => {
|
||||
console.error(err);
|
||||
resp.writeHead(err instanceof ValidationError ? 400 : 500);
|
||||
resp.end();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Express } from "express";
|
||||
import { createAdapter } from "./http_adapter";
|
||||
import { ResultWebService } from "./results_api";
|
||||
import { Validator } from "./validation_adapter";
|
||||
import { ResultWebServiceValidation } from "./results_api_validation";
|
||||
import { FeathersWrapper } from "./feathers_adapter";
|
||||
import { feathers } from "@feathersjs/feathers";
|
||||
import feathersExpress, { rest } from "@feathersjs/express";
|
||||
import { ValidationError } from "./validation_types";
|
||||
|
||||
export const createApi = (app: Express) => {
|
||||
|
||||
// createAdapter(app, new Validator(new ResultWebService(),
|
||||
// ResultWebServiceValidation), "/api/results");
|
||||
|
||||
const feathersApp = feathersExpress(feathers(), app).configure(rest());
|
||||
|
||||
const service = new Validator(new ResultWebService(),
|
||||
ResultWebServiceValidation);
|
||||
|
||||
feathersApp.use('/api/results', new FeathersWrapper(service));
|
||||
|
||||
feathersApp.hooks({
|
||||
error: {
|
||||
all: [(ctx) => {
|
||||
if (ctx.error instanceof ValidationError) {
|
||||
ctx.http = { status: 400};
|
||||
ctx.error = undefined;
|
||||
}
|
||||
}]
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { WebService } from "./http_adapter";
|
||||
import { Result } from "../data/repository";
|
||||
import repository from "../data";
|
||||
import * as jsonpatch from "fast-json-patch";
|
||||
import { validateModel } from "./validation_functions";
|
||||
import { ResultModelValidation } from "./results_api_validation";
|
||||
|
||||
export class ResultWebService implements WebService<Result> {
|
||||
|
||||
getOne(id: any): Promise<Result | undefined> {
|
||||
return repository.getResultById(id);
|
||||
}
|
||||
|
||||
getMany(query: any): Promise<Result[]> {
|
||||
if (query.name) {
|
||||
return repository.getResultsByName(query.name, 10);
|
||||
} else {
|
||||
return repository.getAllResults(10);
|
||||
}
|
||||
}
|
||||
|
||||
async store(data: any): Promise<Result | undefined> {
|
||||
const { name, age, years} = data;
|
||||
const nextage = age + years;
|
||||
const id = await repository.saveResult({ id: 0, name, age,
|
||||
years, nextage});
|
||||
return await repository.getResultById(id);
|
||||
}
|
||||
|
||||
delete(id: any): Promise<boolean> {
|
||||
return repository.delete(Number.parseInt(id));
|
||||
}
|
||||
|
||||
replace(id: any, data: any): Promise<Result | undefined> {
|
||||
const { name, age, years, nextage } = data;
|
||||
const validated = validateModel({ name, age, years, nextage },
|
||||
ResultModelValidation)
|
||||
return repository.update({ id, ...validated });
|
||||
}
|
||||
|
||||
async modify(id: any, data: any): Promise<Result | undefined> {
|
||||
const dbData = await this.getOne(id);
|
||||
if (dbData !== undefined) {
|
||||
return await this.replace(id,
|
||||
jsonpatch.applyPatch(dbData, data).newDocument);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { ModelValidation, ValidationRequirements, ValidationRule,
|
||||
WebServiceValidation } from "./validation_types";
|
||||
import validator from "validator";
|
||||
|
||||
const intValidator : ValidationRule = {
|
||||
validation: [val => validator.isInt(val.toString())],
|
||||
converter: (val) => Number.parseInt(val)
|
||||
}
|
||||
|
||||
const partialResultValidator: ValidationRequirements = {
|
||||
name: [(val) => !validator.isEmpty(val)],
|
||||
age: intValidator,
|
||||
years: intValidator
|
||||
}
|
||||
|
||||
export const ResultWebServiceValidation: WebServiceValidation = {
|
||||
|
||||
keyValidator: intValidator,
|
||||
|
||||
store: partialResultValidator,
|
||||
|
||||
replace: {
|
||||
...partialResultValidator,
|
||||
nextage: intValidator
|
||||
}
|
||||
}
|
||||
|
||||
export const ResultModelValidation : ModelValidation = {
|
||||
propertyRules: { ...partialResultValidator, nextage: intValidator },
|
||||
modelRule: [(m: any) => m.nextage === m.age + m.years]
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { WebService } from "./http_adapter";
|
||||
import { validate, validateIdProperty } from "./validation_functions";
|
||||
import { WebServiceValidation } from "./validation_types";
|
||||
|
||||
export class Validator<T> implements WebService<T> {
|
||||
|
||||
constructor(private ws: WebService<T>,
|
||||
private validation: WebServiceValidation) {}
|
||||
|
||||
getOne(id: any): Promise<T | undefined> {
|
||||
return this.ws.getOne(this.validateId(id));
|
||||
}
|
||||
|
||||
getMany(query: any): Promise<T[]> {
|
||||
if (this.validation.getMany) {
|
||||
query = validate(query, this.validation.getMany);
|
||||
}
|
||||
return this.ws.getMany(query);
|
||||
}
|
||||
|
||||
store(data: any): Promise<T | undefined> {
|
||||
if (this.validation.store) {
|
||||
data = validate(data, this.validation.store);
|
||||
}
|
||||
return this.ws.store(data);
|
||||
}
|
||||
|
||||
delete(id: any): Promise<boolean> {
|
||||
return this.ws.delete(this.validateId(id));
|
||||
}
|
||||
|
||||
replace(id: any, data: any): Promise<T | undefined> {
|
||||
if (this.validation.replace) {
|
||||
data = validate(data, this.validation.replace);
|
||||
}
|
||||
return this.ws.replace(this.validateId(id), data);
|
||||
}
|
||||
|
||||
modify(id: any, data: any): Promise<T | undefined> {
|
||||
if (this.validation.modify) {
|
||||
data = validate(data, this.validation.modify);
|
||||
}
|
||||
return this.ws.modify(this.validateId(id), data);
|
||||
}
|
||||
|
||||
validateId(val: any) {
|
||||
return validateIdProperty(val, this.validation);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { ModelValidation, ValidationError, ValidationRequirements,
|
||||
ValidationRule, WebServiceValidation } from "./validation_types";
|
||||
|
||||
export type ValidationResult = [valid: boolean, value: any];
|
||||
|
||||
export function validate(data: any, reqs: ValidationRequirements): any {
|
||||
let validatedData: any = {};
|
||||
Object.entries(reqs).forEach(([prop, rule]) => {
|
||||
const [valid, value] = applyRule(data[prop], rule);
|
||||
if (valid) {
|
||||
validatedData[prop] = value;
|
||||
} else {
|
||||
throw new ValidationError(prop, "Validation Error");
|
||||
}
|
||||
});
|
||||
return validatedData;
|
||||
}
|
||||
|
||||
function applyRule(val: any,
|
||||
rule: ValidationRule): ValidationResult {
|
||||
const required = Array.isArray(rule) ? true : rule.required;
|
||||
const checks = Array.isArray(rule) ? rule : rule.validation;
|
||||
const convert = Array.isArray(rule) ? (v: any) => v : rule.converter;
|
||||
if (val === null || val == undefined || val === "") {
|
||||
return [required ? false : true, val];
|
||||
}
|
||||
let valid = true;
|
||||
checks.forEach(check => {
|
||||
if (!check(val)) {
|
||||
valid = false;
|
||||
}
|
||||
});
|
||||
return [valid, convert ? convert(val) : val];
|
||||
}
|
||||
|
||||
export function validateIdProperty<T>(val: any,
|
||||
v: WebServiceValidation) : any {
|
||||
if (v.keyValidator) {
|
||||
const [valid, value] = applyRule(val, v.keyValidator);
|
||||
if (valid) {
|
||||
return value;
|
||||
}
|
||||
throw new ValidationError("ID", "Validation Error");
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
export function validateModel(model: any, rules: ModelValidation) : any {
|
||||
if (rules.propertyRules) {
|
||||
model = validate(model, rules.propertyRules);
|
||||
}
|
||||
if (rules.modelRule) {
|
||||
const [valid, data] = applyRule(model, rules.modelRule);
|
||||
if (valid) {
|
||||
return data;
|
||||
}
|
||||
throw new ValidationError("Model", "Validation Error");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export interface WebServiceValidation {
|
||||
keyValidator?: ValidationRule;
|
||||
getMany?: ValidationRequirements;
|
||||
store?: ValidationRequirements;
|
||||
replace?: ValidationRequirements;
|
||||
modify?: ValidationRequirements;
|
||||
}
|
||||
|
||||
export type ValidationRequirements = {
|
||||
[key: string] : ValidationRule
|
||||
}
|
||||
|
||||
export type ValidationRule =
|
||||
((value: any) => boolean)[] |
|
||||
{
|
||||
required? : boolean,
|
||||
validation: ((value: any) => boolean)[],
|
||||
converter?: (value: any) => any,
|
||||
}
|
||||
|
||||
export class ValidationError implements Error {
|
||||
constructor(public name: string, public message: string) {}
|
||||
stack?: string | undefined;
|
||||
cause?: unknown;
|
||||
}
|
||||
|
||||
export type ModelValidation = {
|
||||
modelRule?: ValidationRule,
|
||||
propertyRules?: ValidationRequirements
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//import { IncomingMessage, ServerResponse } from "http";
|
||||
//import { signCookie, validateCookie } from "./cookies_signed";
|
||||
import { CookieOptions, Request, Response } from "express";
|
||||
|
||||
// const setheaderName = "Set-Cookie";
|
||||
// const cookieSecret = "mysecret";
|
||||
|
||||
export const setCookie = (resp: Response, name: string, val: string,
|
||||
opts?: CookieOptions) => {
|
||||
resp.cookie(name, val, {
|
||||
maxAge: 300 * 1000,
|
||||
sameSite: "strict",
|
||||
signed: true,
|
||||
...opts
|
||||
});
|
||||
}
|
||||
|
||||
export const setJsonCookie = (resp: Response, name: string, val: any) => {;
|
||||
setCookie(resp, name, JSON.stringify(val));
|
||||
}
|
||||
|
||||
export const getCookie = (req: Request, key: string): string | undefined => {
|
||||
return req.signedCookies[key];
|
||||
}
|
||||
|
||||
export const getJsonCookie = (req: Request, key: string) : any => {
|
||||
const cookie = getCookie(req, key);
|
||||
return cookie ? JSON.parse(cookie) : undefined;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { createHmac, timingSafeEqual } from "crypto";
|
||||
|
||||
export const signCookie = (value: string, secret: string) => {
|
||||
return value + "." + createHmac("sha512", secret)
|
||||
.update(value).digest("base64url");
|
||||
}
|
||||
|
||||
export const validateCookie = (value: string, secret: string) => {
|
||||
const cookieValue = value.split(".")[0];
|
||||
const compareBuf = Buffer.from(signCookie(cookieValue, secret));
|
||||
const candidateBuf = Buffer.from(value);
|
||||
if (compareBuf.length == candidateBuf.length &&
|
||||
timingSafeEqual(compareBuf, candidateBuf)) {
|
||||
return cookieValue;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { ApiRepository } from "./repository";
|
||||
import { OrmRepository } from "./orm_repository";
|
||||
|
||||
const repository: ApiRepository = new OrmRepository();
|
||||
export default repository;
|
||||
@@ -0,0 +1,63 @@
|
||||
import { DataTypes, Sequelize } from "sequelize";
|
||||
import { Calculation, Person, ResultModel } from "./orm_models";
|
||||
import { Result } from "./repository";
|
||||
|
||||
const primaryKey = {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
autoIncrement: true,
|
||||
primaryKey: true
|
||||
}
|
||||
};
|
||||
|
||||
export const initializeModels = (sequelize: Sequelize) => {
|
||||
|
||||
Person.init({
|
||||
...primaryKey,
|
||||
name: { type: DataTypes.STRING }
|
||||
}, { sequelize });
|
||||
|
||||
Calculation.init({
|
||||
...primaryKey,
|
||||
age: { type: DataTypes.INTEGER},
|
||||
years: { type: DataTypes.INTEGER},
|
||||
nextage: { type: DataTypes.INTEGER},
|
||||
}, { sequelize });
|
||||
|
||||
ResultModel.init({
|
||||
...primaryKey,
|
||||
}, { sequelize });
|
||||
}
|
||||
|
||||
export const defineRelationships = () => {
|
||||
ResultModel.belongsTo(Person, { foreignKey: "personId" });
|
||||
ResultModel.belongsTo(Calculation, { foreignKey: "calculationId"});
|
||||
}
|
||||
|
||||
export const addSeedData = async (sequelize: Sequelize) => {
|
||||
await sequelize.query(`
|
||||
INSERT INTO Calculations
|
||||
(id, age, years, nextage, createdAt, updatedAt) VALUES
|
||||
(1, 35, 5, 40, date(), date()),
|
||||
(2, 35, 10, 45, date(), date())`);
|
||||
|
||||
await sequelize.query(`
|
||||
INSERT INTO People (id, name, createdAt, updatedAt) VALUES
|
||||
(1, 'Alice', date(), date()), (2, "Bob", date(), date())`);
|
||||
|
||||
await sequelize.query(`
|
||||
INSERT INTO ResultModels
|
||||
(calculationId, personId, createdAt, updatedAt) VALUES
|
||||
(1, 1, date(), date()), (2, 2, date(), date()),
|
||||
(2, 1, date(), date());`);
|
||||
}
|
||||
|
||||
export const fromOrmModel = (model: ResultModel | null) : Result => {
|
||||
return {
|
||||
id: model?.id || 0,
|
||||
name: model?.Person?.name || "",
|
||||
age: model?.Calculation?.age || 0,
|
||||
years: model?.Calculation?.years || 0,
|
||||
nextage: model?.Calculation?.nextage || 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Model, CreationOptional, ForeignKey, InferAttributes,
|
||||
InferCreationAttributes } from "sequelize";
|
||||
|
||||
export class Person extends Model<InferAttributes<Person>,
|
||||
InferCreationAttributes<Person>> {
|
||||
|
||||
declare id?: CreationOptional<number>;
|
||||
declare name: string
|
||||
}
|
||||
|
||||
export class Calculation extends Model<InferAttributes<Calculation>,
|
||||
InferCreationAttributes<Calculation>> {
|
||||
|
||||
declare id?: CreationOptional<number>;
|
||||
declare age: number;
|
||||
declare years: number;
|
||||
declare nextage: number;
|
||||
}
|
||||
|
||||
export class ResultModel extends Model<InferAttributes<ResultModel>,
|
||||
InferCreationAttributes<ResultModel>> {
|
||||
|
||||
declare id: CreationOptional<number>;
|
||||
declare personId: ForeignKey<Person["id"]>;
|
||||
declare calculationId: ForeignKey<Calculation["id"]>;
|
||||
|
||||
declare Person?: InferAttributes<Person>;
|
||||
declare Calculation?: InferAttributes<Calculation>;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Sequelize } from "sequelize";
|
||||
import { ApiRepository, Result } from "./repository";
|
||||
import { addSeedData, defineRelationships,
|
||||
fromOrmModel, initializeModels } from "./orm_helpers";
|
||||
import { Calculation, Person, ResultModel } from "./orm_models";
|
||||
|
||||
export class OrmRepository implements ApiRepository {
|
||||
sequelize: Sequelize;
|
||||
|
||||
constructor() {
|
||||
this.sequelize = new Sequelize({
|
||||
dialect: "sqlite",
|
||||
storage: "orm_age.db",
|
||||
logging: console.log,
|
||||
logQueryParameters: true
|
||||
});
|
||||
this.initModelAndDatabase();
|
||||
}
|
||||
|
||||
async initModelAndDatabase() : Promise<void> {
|
||||
initializeModels(this.sequelize);
|
||||
defineRelationships();
|
||||
await this.sequelize.drop();
|
||||
await this.sequelize.sync();
|
||||
await addSeedData(this.sequelize);
|
||||
}
|
||||
|
||||
async saveResult(r: Result): Promise<number> {
|
||||
return await this.sequelize.transaction(async (tx) => {
|
||||
|
||||
const [person] = await Person.findOrCreate({
|
||||
where: { name : r.name},
|
||||
transaction: tx
|
||||
});
|
||||
|
||||
const [calculation] = await Calculation.findOrCreate({
|
||||
where: {
|
||||
age: r.age, years: r.years, nextage: r.nextage
|
||||
},
|
||||
transaction: tx
|
||||
});
|
||||
|
||||
return (await ResultModel.create({
|
||||
personId: person.id, calculationId: calculation.id},
|
||||
{transaction: tx})).id;
|
||||
});
|
||||
}
|
||||
|
||||
async getAllResults(limit: number): Promise<Result[]> {
|
||||
return (await ResultModel.findAll({
|
||||
include: [Person, Calculation],
|
||||
limit,
|
||||
order: [["id", "DESC"]]
|
||||
})).map(row => fromOrmModel(row));
|
||||
}
|
||||
|
||||
async getResultsByName(name: string, limit: number): Promise<Result[]> {
|
||||
return (await ResultModel.findAll({
|
||||
include: [Person, Calculation],
|
||||
where: {
|
||||
"$Person.name$": name
|
||||
},
|
||||
limit, order: [["id", "DESC"]]
|
||||
})).map(row => fromOrmModel(row));
|
||||
}
|
||||
|
||||
async getResultById(id: number): Promise<Result | undefined> {
|
||||
const model = await ResultModel.findByPk(id, {
|
||||
include: [Person, Calculation ]
|
||||
});
|
||||
return model ? fromOrmModel(model): undefined;
|
||||
}
|
||||
|
||||
async delete(id: number): Promise<boolean> {
|
||||
const count = await ResultModel.destroy({ where: { id }});
|
||||
return count == 1;
|
||||
}
|
||||
|
||||
async update(r: Result) : Promise<Result | undefined > {
|
||||
const mod = await this.sequelize.transaction(async (transaction) => {
|
||||
const stored = await ResultModel.findByPk(r.id);
|
||||
if (stored !== null) {
|
||||
const [person] = await Person.findOrCreate({
|
||||
where: { name : r.name}, transaction
|
||||
});
|
||||
const [calculation] = await Calculation.findOrCreate({
|
||||
where: {
|
||||
age: r.age, years: r.years, nextage: r.nextage
|
||||
}, transaction
|
||||
});
|
||||
stored.personId = person.id;
|
||||
stored.calculationId = calculation.id;
|
||||
return await stored.save({transaction});
|
||||
}
|
||||
});
|
||||
return mod ? this.getResultById(mod.id) : undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
export interface Result {
|
||||
id: number,
|
||||
name: string,
|
||||
age: number,
|
||||
years: number,
|
||||
nextage: number
|
||||
}
|
||||
|
||||
export interface Repository {
|
||||
|
||||
saveResult(r: Result): Promise<number>;
|
||||
|
||||
getAllResults(limit: number) : Promise<Result[]>;
|
||||
|
||||
getResultsByName(name: string, limit: number): Promise<Result[]>;
|
||||
}
|
||||
|
||||
export interface ApiRepository extends Repository {
|
||||
|
||||
getResultById(id: number): Promise<Result | undefined>;
|
||||
|
||||
delete(id: number) : Promise<boolean>;
|
||||
|
||||
update(r: Result) : Promise<Result | undefined>
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Database } from "sqlite3";
|
||||
|
||||
export class TransactionHelper {
|
||||
steps: [sql: string, params: any][] = [];
|
||||
|
||||
add(sql: string, params: any): TransactionHelper {
|
||||
this.steps.push([sql, params]);
|
||||
return this;
|
||||
}
|
||||
|
||||
run(db: Database): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let index = 0;
|
||||
let lastRow: number = NaN;
|
||||
const cb = (err: any, rowID?: number) => {
|
||||
if (err) {
|
||||
db.run("ROLLBACK", () => reject());
|
||||
} else {
|
||||
lastRow = rowID ? rowID : lastRow;
|
||||
if (++index === this.steps.length) {
|
||||
db.run("COMMIT", () => resolve(lastRow));
|
||||
} else {
|
||||
this.runStep(index, db, cb);
|
||||
}
|
||||
}
|
||||
}
|
||||
db.run("BEGIN", () => this.runStep(0, db, cb));
|
||||
});
|
||||
}
|
||||
|
||||
runStep(idx: number, db: Database, cb: (err: any, row: number) => void) {
|
||||
const [sql, params] = this.steps[idx];
|
||||
db.run(sql, params, function (err: any) {
|
||||
cb(err, this.lastID)
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
const baseSql = `
|
||||
SELECT Results.*, name, age, years, nextage FROM Results
|
||||
INNER JOIN People ON personId = People.id
|
||||
INNER JOIN Calculations ON calculationId = Calculations.id`;
|
||||
|
||||
const endSql = `ORDER BY id DESC LIMIT $limit`;
|
||||
|
||||
export const queryAllSql = `${baseSql} ${endSql}`;
|
||||
|
||||
export const queryByNameSql = `${baseSql} WHERE name = $name ${endSql}`;
|
||||
|
||||
export const insertPerson = `
|
||||
INSERT INTO People (name)
|
||||
SELECT $name
|
||||
WHERE NOT EXISTS (SELECT name FROM People WHERE name = $name)`;
|
||||
|
||||
export const insertCalculation = `
|
||||
INSERT INTO Calculations (age, years, nextage)
|
||||
SELECT $age, $years, $nextage
|
||||
WHERE NOT EXISTS
|
||||
(SELECT age, years, nextage FROM Calculations
|
||||
WHERE age = $age AND years = $years AND nextage = $nextage)`;
|
||||
|
||||
export const insertResult = `
|
||||
INSERT INTO Results (personId, calculationId)
|
||||
SELECT People.id as personId, Calculations.id as calculationId from People
|
||||
CROSS JOIN Calculations
|
||||
WHERE People.name = $name
|
||||
AND Calculations.age = $age
|
||||
AND Calculations.years = $years
|
||||
AND Calculations.nextage = $nextage`;
|
||||
@@ -0,0 +1,50 @@
|
||||
import { readFileSync } from "fs";
|
||||
import { Database } from "sqlite3";
|
||||
import { Repository, Result } from "./repository";
|
||||
import { queryAllSql, queryByNameSql,
|
||||
insertPerson, insertCalculation, insertResult } from "./sql_queries";
|
||||
import { TransactionHelper } from "./sql_helpers";
|
||||
|
||||
export class SqlRepository implements Repository {
|
||||
db: Database;
|
||||
|
||||
constructor() {
|
||||
this.db = new Database("age.db");
|
||||
this.db.exec(readFileSync("age.sql").toString(), err => {
|
||||
if (err != undefined) throw err;
|
||||
});
|
||||
}
|
||||
|
||||
async saveResult(r: Result): Promise<number> {
|
||||
return await new TransactionHelper()
|
||||
.add(insertPerson, { $name: r.name })
|
||||
.add(insertCalculation, {
|
||||
$age: r.age, $years: r.years, $nextage: r.nextage
|
||||
})
|
||||
.add(insertResult, {
|
||||
$name: r.name,
|
||||
$age: r.age, $years: r.years, $nextage: r.nextage
|
||||
})
|
||||
.run(this.db);
|
||||
}
|
||||
|
||||
getAllResults($limit: number): Promise<Result[]> {
|
||||
return this.executeQuery(queryAllSql, { $limit });
|
||||
}
|
||||
|
||||
getResultsByName($name: string, $limit: number): Promise<Result[]> {
|
||||
return this.executeQuery(queryByNameSql, { $name, $limit });
|
||||
}
|
||||
|
||||
executeQuery(sql: string, params: any) : Promise<Result[]> {
|
||||
return new Promise<Result[]>((resolve, reject) => {
|
||||
this.db.all<Result>(sql, params, (err, rows) => {
|
||||
if (err == undefined) {
|
||||
resolve(rows);
|
||||
} else {
|
||||
reject(err);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import express, { Express } from "express";
|
||||
import repository from "./data";
|
||||
import cookieMiddleware from "cookie-parser";
|
||||
import { sessionMiddleware } from "./sessions/session_helpers";
|
||||
import { Result } from "./data/repository";
|
||||
|
||||
const rowLimit = 10;
|
||||
|
||||
export const registerFormMiddleware = (app: Express) => {
|
||||
app.use(express.urlencoded({extended: true}))
|
||||
app.use(cookieMiddleware("mysecret"));
|
||||
app.use(sessionMiddleware());
|
||||
}
|
||||
|
||||
export const registerFormRoutes = (app: Express) => {
|
||||
|
||||
app.get("/form", async (req, resp) => {
|
||||
resp.render("data", {data: await repository.getAllResults(rowLimit)});
|
||||
});
|
||||
|
||||
app.post("/form/delete/:id", async (req, resp) => {
|
||||
const id = Number.parseInt(req.params["id"]);
|
||||
await repository.delete(id);
|
||||
resp.redirect("/form");
|
||||
resp.end();
|
||||
});
|
||||
|
||||
app.post("/form/add", async (req, resp) => {
|
||||
const nextage = Number.parseInt(req.body["age"])
|
||||
+ Number.parseInt(req.body["years"]);
|
||||
|
||||
await repository.saveResult({...req.body, nextage } as Result);
|
||||
resp.redirect("/form");
|
||||
resp.end();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
const matchPattern = /[&<>="'`]/g;
|
||||
|
||||
const characterMappings: Record<string, string> = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
"\"": """,
|
||||
"=": "=",
|
||||
"'": "'",
|
||||
"`": "`"
|
||||
};
|
||||
|
||||
export const santizeValue = (value: string) =>
|
||||
value?.replace(matchPattern, match => characterMappings[match]);
|
||||
@@ -0,0 +1,42 @@
|
||||
import { createServer } from "http";
|
||||
import express, {Express } from "express";
|
||||
import httpProxy from "http-proxy";
|
||||
import helmet from "helmet";
|
||||
import { engine } from "express-handlebars";
|
||||
import { registerFormMiddleware, registerFormRoutes } from "./forms";
|
||||
import { createApi } from "./api";
|
||||
|
||||
const port = 5000;
|
||||
|
||||
const expressApp: Express = express();
|
||||
|
||||
const proxy = httpProxy.createProxyServer({
|
||||
target: "http://localhost:5100", ws: true
|
||||
});
|
||||
|
||||
expressApp.set("views", "templates/server");
|
||||
expressApp.engine("handlebars", engine());
|
||||
expressApp.set("view engine", "handlebars");
|
||||
|
||||
expressApp.use(helmet());
|
||||
expressApp.use(express.json({
|
||||
type: ["application/json", "application/json-patch+json"]
|
||||
}));
|
||||
|
||||
registerFormMiddleware(expressApp);
|
||||
registerFormRoutes(expressApp);
|
||||
|
||||
createApi(expressApp);
|
||||
expressApp.use("^/$", (req, resp) => resp.redirect("/form"));
|
||||
|
||||
expressApp.use(express.static("static"));
|
||||
expressApp.use(express.static("node_modules/bootstrap/dist"));
|
||||
|
||||
expressApp.use((req, resp) => proxy.web(req, resp));
|
||||
|
||||
const server = createServer(expressApp);
|
||||
|
||||
server.on('upgrade', (req, socket, head) => proxy.ws(req, socket, head));
|
||||
|
||||
server.listen(port,
|
||||
() => console.log(`HTTP Server listening on port ${port}`));
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Session, SessionRepository } from "./repository";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
type SessionWrapper = {
|
||||
session: Session,
|
||||
expires: Date
|
||||
}
|
||||
|
||||
export class MemoryRepository implements SessionRepository {
|
||||
store = new Map<string, SessionWrapper>();
|
||||
|
||||
async createSession(): Promise<Session> {
|
||||
return { id: randomUUID(), data: {} };
|
||||
}
|
||||
|
||||
async getSession(id: string): Promise<Session | undefined> {
|
||||
const wrapper = this.store.get(id);
|
||||
if (wrapper && wrapper.expires > new Date(Date.now())) {
|
||||
return structuredClone(wrapper.session)
|
||||
}
|
||||
}
|
||||
|
||||
async saveSession(session: Session, expires: Date): Promise<void> {
|
||||
this.store.set(session.id, { session, expires });
|
||||
}
|
||||
|
||||
async touchSession(session: Session, expires: Date): Promise<void> {
|
||||
const wrapper = this.store.get(session.id);
|
||||
if (wrapper) {
|
||||
wrapper.expires = expires;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { SessionRepository, Session } from "./repository";
|
||||
//import { MemoryRepository } from "./memory_repository";
|
||||
import { setCookie, getCookie } from "../cookies";
|
||||
import { OrmRepository } from "./orm_repository";
|
||||
|
||||
const session_cookie_name = "custom_session";
|
||||
const expiry_seconds = 300;
|
||||
|
||||
const getExpiryDate = () => new Date(Date.now() + (expiry_seconds * 1_000));
|
||||
|
||||
export const customSessionMiddleware = () => {
|
||||
//const repo: SessionRepository = new MemoryRepository();
|
||||
const repo: SessionRepository = new OrmRepository();
|
||||
|
||||
return async (req: Request, resp: Response, next: NextFunction) => {
|
||||
|
||||
const id = getCookie(req, session_cookie_name);
|
||||
|
||||
const session = (id ? await repo.getSession(id) : undefined)
|
||||
?? await repo.createSession();
|
||||
|
||||
(req as any).session = session;
|
||||
|
||||
setCookie(resp, session_cookie_name, session.id, {
|
||||
maxAge: expiry_seconds * 1000
|
||||
})
|
||||
|
||||
resp.once("finish", async () => {
|
||||
if ( Object.keys(session.data).length > 0) {
|
||||
if (req.method == "POST") {
|
||||
await repo.saveSession(session, getExpiryDate());
|
||||
} else {
|
||||
await repo.touchSession(session, getExpiryDate());
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { DataTypes, InferAttributes, InferCreationAttributes, Model,
|
||||
Sequelize } from "sequelize";
|
||||
|
||||
export class SessionModel extends Model<InferAttributes<SessionModel>,
|
||||
InferCreationAttributes<SessionModel>> {
|
||||
|
||||
declare id: string
|
||||
declare data: any;
|
||||
declare expires: Date
|
||||
}
|
||||
|
||||
export const initializeModel = (sequelize: Sequelize) => {
|
||||
|
||||
SessionModel.init({
|
||||
id: { type: DataTypes.STRING, primaryKey: true },
|
||||
data: { type: DataTypes.JSON },
|
||||
expires: { type: DataTypes.DATE }
|
||||
}, { sequelize });
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Op, Sequelize } from "sequelize";
|
||||
import { Session, SessionRepository } from "./repository";
|
||||
import { SessionModel, initializeModel } from "./orm_models";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
export class OrmRepository implements SessionRepository {
|
||||
sequelize: Sequelize;
|
||||
|
||||
constructor() {
|
||||
this.sequelize = new Sequelize({
|
||||
dialect: "sqlite",
|
||||
storage: "orm_sessions.db",
|
||||
logging: console.log,
|
||||
logQueryParameters: true
|
||||
});
|
||||
this.initModelAndDatabase();
|
||||
}
|
||||
|
||||
async initModelAndDatabase() : Promise<void> {
|
||||
initializeModel(this.sequelize);
|
||||
await this.sequelize.drop();
|
||||
await this.sequelize.sync();
|
||||
}
|
||||
|
||||
async createSession(): Promise<Session> {
|
||||
return { id: randomUUID(), data: {} };
|
||||
}
|
||||
|
||||
async getSession(id: string): Promise<Session | undefined> {
|
||||
const dbsession = await SessionModel.findOne({
|
||||
where: { id, expires: { [Op.gt] : new Date(Date.now()) }}
|
||||
});
|
||||
if (dbsession) {
|
||||
return { id, data: dbsession.data };
|
||||
}
|
||||
}
|
||||
|
||||
async saveSession(session: Session, expires: Date): Promise<void> {
|
||||
await SessionModel.upsert({
|
||||
id: session.id,
|
||||
data: session.data,
|
||||
expires
|
||||
});
|
||||
}
|
||||
|
||||
async touchSession(session: Session, expires: Date): Promise<void> {
|
||||
await SessionModel.update({ expires }, { where: { id: session.id } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
export type Session = {
|
||||
id: string,
|
||||
data: { [key: string]: any }
|
||||
}
|
||||
|
||||
export interface SessionRepository {
|
||||
|
||||
createSession() : Promise<Session>;
|
||||
|
||||
getSession(id: string): Promise<Session | undefined>;
|
||||
|
||||
saveSession(session: Session, expires: Date): Promise<void>;
|
||||
|
||||
touchSession(session: Session, expires: Date) : Promise<void>
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Request } from "express";
|
||||
//import { Session } from "./repository";
|
||||
import session, { SessionData } from "express-session";
|
||||
import sessionStore from "connect-session-sequelize";
|
||||
import { Sequelize } from "sequelize";
|
||||
import { Result } from "../data/repository";
|
||||
|
||||
export const getSession = (req: Request): SessionData => (req as any).session;
|
||||
|
||||
// declare global {
|
||||
// module Express {
|
||||
// interface Request {
|
||||
// session: Session
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
declare module "express-session" {
|
||||
interface SessionData {
|
||||
personalHistory: Result[];
|
||||
}
|
||||
}
|
||||
|
||||
export const sessionMiddleware = () => {
|
||||
|
||||
const sequelize = new Sequelize({
|
||||
dialect: "sqlite",
|
||||
storage: "pkg_sessions.db"
|
||||
});
|
||||
|
||||
const store = new (sessionStore(session.Store))({
|
||||
db: sequelize
|
||||
});
|
||||
|
||||
store.sync();
|
||||
|
||||
return session({
|
||||
secret: "mysecret",
|
||||
store: store,
|
||||
cookie: { maxAge: 300 * 1000, sameSite: "strict" },
|
||||
resave: false, saveUninitialized: false
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
export const style = (stylesheet: any) => {
|
||||
return `<link href="/css/${stylesheet}" rel="stylesheet" />`;
|
||||
}
|
||||
|
||||
export const valueOrZero = (value: any) => {
|
||||
return value !== undefined ? value : 0;
|
||||
}
|
||||
|
||||
export const increment = (value: any) => {
|
||||
return Number(valueOrZero(value)) + 1;
|
||||
}
|
||||
|
||||
export const isOdd = (value: any) => {
|
||||
return Number(valueOrZero(value)) % 2;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Request, Response } from "express";
|
||||
|
||||
export const testHandler = async (req: Request, resp: Response) => {
|
||||
resp.setHeader("Content-Type", "application/json")
|
||||
resp.json(req.body);
|
||||
resp.end();
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import validator from "validator";
|
||||
|
||||
type ValidatedRequest = Request & {
|
||||
validation: {
|
||||
results: { [key: string]: {
|
||||
[key: string]: boolean, valid: boolean
|
||||
} },
|
||||
valid: boolean
|
||||
}
|
||||
}
|
||||
|
||||
export const validate = (propName: string) => {
|
||||
const tests: Record<string, (val: string) => boolean> = {};
|
||||
const handler = (req: Request, resp: Response, next: NextFunction ) => {
|
||||
|
||||
const vreq = req as ValidatedRequest;
|
||||
if (!vreq.validation) {
|
||||
vreq.validation = { results: {}, valid: true };
|
||||
}
|
||||
vreq.validation.results[propName] = { valid: true };
|
||||
|
||||
Object.keys(tests).forEach(k => {
|
||||
let valid = vreq.validation.results[propName][k]
|
||||
= tests[k](req.body?.[propName]);
|
||||
if (!valid) {
|
||||
vreq.validation.results[propName].valid = false;
|
||||
vreq.validation.valid = false;
|
||||
}
|
||||
});
|
||||
|
||||
next();
|
||||
}
|
||||
handler.required = () => {
|
||||
tests.required = (val: string) =>
|
||||
!validator.isEmpty(val, { ignore_whitespace: true});
|
||||
return handler;
|
||||
};
|
||||
handler.minLength = (min: number) => {
|
||||
tests.minLength = (val:string) => validator.isLength(val, { min});
|
||||
return handler;
|
||||
};
|
||||
handler.isInteger = () => {
|
||||
tests.isInteger = (val: string) => validator.isInt(val);
|
||||
return handler;
|
||||
}
|
||||
return handler;
|
||||
}
|
||||
|
||||
export const getValidationResults = (req: Request) => {
|
||||
return (req as ValidatedRequest).validation || { valid : true }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<script src="/bundle.js"></script>
|
||||
<link href="css/bootstrap.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<form action="/form">
|
||||
<div class="m-2">
|
||||
<label class="form-label">Name</label>
|
||||
<input name="name" class="form-control" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">City</label>
|
||||
<input name="city" class="form-control" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">File</label>
|
||||
<input name="datafile" type="file" class="form-control" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<button class="btn btn-primary" formmethod="get">
|
||||
Submit (GET)
|
||||
</button>
|
||||
<button class="btn btn-primary" formmethod="post">
|
||||
Submit (POST)
|
||||
</button>
|
||||
<button class="btn btn-primary" formmethod="post"
|
||||
formenctype="multipart/form-data">
|
||||
Submit (POST/MIME)
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
export default (value) => value % 2;
|
||||
@@ -0,0 +1,37 @@
|
||||
<div class="container fluid">
|
||||
<div class="row">
|
||||
<div class="col-7">
|
||||
{{#if name}}
|
||||
<div class="m-2">
|
||||
<h4>Hello {{ name }}. You will be {{ nextage }}
|
||||
in {{ years }} years.</h4>
|
||||
</div>
|
||||
{{/if}}
|
||||
<div>
|
||||
<form id="age_form" action="/form" method="post">
|
||||
<div class="m-2">
|
||||
<label class="form-label">Name</label>
|
||||
<input name="name" class="form-control"
|
||||
value="{{ name }}"/>
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">Current Age</label>
|
||||
<input name="age" class="form-control"
|
||||
value="{{ age }}" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">Number of Years</label>
|
||||
<input name="years" class="form-control"
|
||||
value="{{ years }}" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<button class="btn btn-primary">Submit</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-5">
|
||||
{{> history }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,37 @@
|
||||
<form class="m-2">
|
||||
<table class="table table-sm table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th><th>Name</th><th>Age</th><th>Years</th>
|
||||
<th>Next Age</th><th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{#unless data }}<tr><td colspan="5">No Data</td></tr>{{/unless }}
|
||||
{{#each data }}
|
||||
<tr>
|
||||
<td>{{ this.id }} </td>
|
||||
<td>{{ this.name }} </td>
|
||||
<td>{{ this.age }} </td>
|
||||
<td>{{ this.years }} </td>
|
||||
<td>{{ this.nextage }} </td>
|
||||
<td>
|
||||
<button class="btn btn-danger btn-sm"
|
||||
formmethod="post"
|
||||
formaction="/form/delete/{{this.id}}">
|
||||
Delete
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{{/each }}
|
||||
</tbody>
|
||||
</table>
|
||||
<button class="btn btn-primary"
|
||||
formmethod="post"
|
||||
formaction="/form/add">
|
||||
Add
|
||||
</button>
|
||||
<input type="hidden" name="name" value="Alice" />
|
||||
<input type="hidden" name="age" value="40" />
|
||||
<input type="hidden" name="years" value="10" />
|
||||
</form>
|
||||
@@ -0,0 +1,10 @@
|
||||
<table class="table table-sm table-striped">
|
||||
<thead>
|
||||
<tr><th>Field</th><th>Value</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td>Name:</td><td>{{ name }} </td></tr>
|
||||
<tr><td>City:</td><td>{{ city }} </td></tr>
|
||||
<tr><td>File:</td><td>{{ fileData }} </td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -0,0 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<script src="/bundle.js"></script>
|
||||
<link href="css/bootstrap.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
{{{ body }}}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,3 @@
|
||||
<h4 class="bg-secondary text-white m-2 p-2">
|
||||
Handlebars Even value: {{ valueOrZero req.query.c }}
|
||||
</h4>
|
||||
@@ -0,0 +1,36 @@
|
||||
{{#if personalHistory }}
|
||||
<h4>Your History</h4>
|
||||
<table class="table table-sm table-striped my-2">
|
||||
{{#each personalHistory }}
|
||||
<tr>
|
||||
<td>{{ this.name }} </td>
|
||||
<td>{{ this.age }} </td>
|
||||
<td>{{ this.years }} </td>
|
||||
<td>{{ this.nextage }} </td>
|
||||
</tr>
|
||||
{{/each }}
|
||||
</table>
|
||||
{{/if }}
|
||||
|
||||
<h4>Recent Queries</h4>
|
||||
|
||||
<table class="table table-sm table-striped my-2">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th><th>Age</th><th>Years</th><th>Result</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{#unless history }}
|
||||
<tr><td colspan="4">No data available</td></tr>
|
||||
{{/unless }}
|
||||
{{#each history }}
|
||||
<tr>
|
||||
<td>{{ this.name }} </td>
|
||||
<td>{{ this.age }} </td>
|
||||
<td>{{ this.years }} </td>
|
||||
<td>{{ this.nextage }} </td>
|
||||
</tr>
|
||||
{{/each }}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -0,0 +1,3 @@
|
||||
<h4 class="bg-primary text-white m-2 p-2">
|
||||
Handlebars Odd value: {{ valueOrZero req.query.c}}
|
||||
</h4>
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "@tsconfig/node20/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src/server",
|
||||
"outDir": "dist/server/",
|
||||
"noImplicitAny": false
|
||||
},
|
||||
"include": ["src/server/**/*"]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import path from "path";
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export default {
|
||||
mode: "development",
|
||||
entry: "./src/client/client.js",
|
||||
devtool: "source-map",
|
||||
output: {
|
||||
path: path.resolve(__dirname, "dist/client"),
|
||||
filename: "bundle.js"
|
||||
},
|
||||
devServer: {
|
||||
static: ["./static"],
|
||||
port: 5100,
|
||||
client: { webSocketURL: "http://localhost:5000/ws" }
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{ test: /\.handlebars$/, loader: "handlebars-loader" }
|
||||
]
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
"@templates": path.resolve(__dirname, "templates/client")
|
||||
}
|
||||
}
|
||||
};
|
||||
Binary file not shown.
@@ -0,0 +1,27 @@
|
||||
DROP TABLE IF EXISTS Results;
|
||||
DROP TABLE IF EXISTS Calculations;
|
||||
DROP TABLE IF EXISTS People;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `Calculations` (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, `age` INTEGER,
|
||||
years INTEGER, `nextage` INTEGER);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `People` (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(255));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `Results` (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
calculationId INTEGER REFERENCES `Calculations` (`id`)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
personId INTEGER REFERENCES `People` (`id`)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE);
|
||||
|
||||
INSERT INTO Calculations (id, age, years, nextage) VALUES
|
||||
(1, 35, 5, 40), (2, 35, 10, 45);
|
||||
|
||||
INSERT INTO People (id, name) VALUES
|
||||
(1, 'Alice'), (2, "Bob");
|
||||
|
||||
INSERT INTO Results (calculationId, personId) VALUES
|
||||
(1, 1), (2, 2), (2, 1);
|
||||
@@ -0,0 +1,5 @@
|
||||
[
|
||||
{ "city": "London", "population": 8982000 },
|
||||
{ "city": "Paris", "population": 2161000 },
|
||||
{ "city": "Beijing", "population": 21540000 }
|
||||
]
|
||||
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.FeathersWrapper = void 0;
|
||||
class FeathersWrapper {
|
||||
ws;
|
||||
constructor(ws) {
|
||||
this.ws = ws;
|
||||
}
|
||||
get(id) {
|
||||
return this.ws.getOne(id);
|
||||
}
|
||||
find(params) {
|
||||
return this.ws.getMany(params.query);
|
||||
}
|
||||
create(data, params) {
|
||||
return this.ws.store(data);
|
||||
}
|
||||
remove(id, params) {
|
||||
return this.ws.delete(id);
|
||||
}
|
||||
update(id, data, params) {
|
||||
return this.ws.replace(id, data);
|
||||
}
|
||||
patch(id, data, params) {
|
||||
return this.ws.modify(id, data);
|
||||
}
|
||||
}
|
||||
exports.FeathersWrapper = FeathersWrapper;
|
||||
@@ -0,0 +1,73 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createAdapter = void 0;
|
||||
const validation_types_1 = require("./validation_types");
|
||||
function createAdapter(app, ws, baseUrl) {
|
||||
app.get(baseUrl, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.getMany(req.query));
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
app.get(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
const data = await ws.getOne((req.params.id));
|
||||
if (data == undefined) {
|
||||
resp.writeHead(404);
|
||||
}
|
||||
else {
|
||||
resp.json(data);
|
||||
}
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
app.post(baseUrl, async (req, resp) => {
|
||||
try {
|
||||
const data = await ws.store(req.body);
|
||||
resp.json(data);
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
app.delete(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.delete(req.params.id));
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
app.put(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.replace(req.params.id, req.body));
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
app.patch(`${baseUrl}/:id`, async (req, resp) => {
|
||||
try {
|
||||
resp.json(await ws.modify(req.params.id, req.body));
|
||||
resp.end();
|
||||
}
|
||||
catch (err) {
|
||||
writeErrorResponse(err, resp);
|
||||
}
|
||||
});
|
||||
const writeErrorResponse = (err, resp) => {
|
||||
console.error(err);
|
||||
resp.writeHead(err instanceof validation_types_1.ValidationError ? 400 : 500);
|
||||
resp.end();
|
||||
};
|
||||
}
|
||||
exports.createAdapter = createAdapter;
|
||||
@@ -0,0 +1,65 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createApi = void 0;
|
||||
const results_api_1 = require("./results_api");
|
||||
const validation_adapter_1 = require("./validation_adapter");
|
||||
const results_api_validation_1 = require("./results_api_validation");
|
||||
const feathers_adapter_1 = require("./feathers_adapter");
|
||||
const feathers_1 = require("@feathersjs/feathers");
|
||||
const express_1 = __importStar(require("@feathersjs/express"));
|
||||
const validation_types_1 = require("./validation_types");
|
||||
const auth_1 = require("../auth");
|
||||
const passport_1 = __importDefault(require("passport"));
|
||||
const createApi = (app) => {
|
||||
const feathersApp = (0, express_1.default)((0, feathers_1.feathers)(), app).configure((0, express_1.rest)());
|
||||
const service = new validation_adapter_1.Validator(new results_api_1.ResultWebService(), results_api_validation_1.ResultWebServiceValidation);
|
||||
feathersApp.use('/api/results', passport_1.default.authenticate("jwt", { session: false }), (req, resp, next) => {
|
||||
req.feathers.user = req.user;
|
||||
req.feathers.authenticated
|
||||
= req.authenticated = req.user !== undefined;
|
||||
next();
|
||||
}, new feathers_adapter_1.FeathersWrapper(service));
|
||||
feathersApp.hooks({
|
||||
error: {
|
||||
all: [(ctx) => {
|
||||
if (ctx.error instanceof validation_types_1.ValidationError) {
|
||||
ctx.http = { status: 400 };
|
||||
ctx.error = undefined;
|
||||
}
|
||||
}]
|
||||
},
|
||||
before: {
|
||||
create: [(0, auth_1.roleHook)("Users")],
|
||||
remove: [(0, auth_1.roleHook)("Admins")],
|
||||
update: [(0, auth_1.roleHook)("Admins")],
|
||||
patch: [(0, auth_1.roleHook)("Admins")]
|
||||
}
|
||||
});
|
||||
};
|
||||
exports.createApi = createApi;
|
||||
@@ -0,0 +1,68 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ResultWebService = void 0;
|
||||
const data_1 = __importDefault(require("../data"));
|
||||
const jsonpatch = __importStar(require("fast-json-patch"));
|
||||
const validation_functions_1 = require("./validation_functions");
|
||||
const results_api_validation_1 = require("./results_api_validation");
|
||||
class ResultWebService {
|
||||
getOne(id) {
|
||||
return data_1.default.getResultById(id);
|
||||
}
|
||||
getMany(query) {
|
||||
if (query.name) {
|
||||
return data_1.default.getResultsByName(query.name, 10);
|
||||
}
|
||||
else {
|
||||
return data_1.default.getAllResults(10);
|
||||
}
|
||||
}
|
||||
async store(data) {
|
||||
const { name, age, years } = data;
|
||||
const nextage = age + years;
|
||||
const id = await data_1.default.saveResult({ id: 0, name, age,
|
||||
years, nextage });
|
||||
return await data_1.default.getResultById(id);
|
||||
}
|
||||
delete(id) {
|
||||
return data_1.default.delete(Number.parseInt(id));
|
||||
}
|
||||
replace(id, data) {
|
||||
const { name, age, years, nextage } = data;
|
||||
const validated = (0, validation_functions_1.validateModel)({ name, age, years, nextage }, results_api_validation_1.ResultModelValidation);
|
||||
return data_1.default.update({ id, ...validated });
|
||||
}
|
||||
async modify(id, data) {
|
||||
const dbData = await this.getOne(id);
|
||||
if (dbData !== undefined) {
|
||||
return await this.replace(id, jsonpatch.applyPatch(dbData, data).newDocument);
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.ResultWebService = ResultWebService;
|
||||
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ResultModelValidation = exports.ResultWebServiceValidation = void 0;
|
||||
const validator_1 = __importDefault(require("validator"));
|
||||
const intValidator = {
|
||||
validation: [val => validator_1.default.isInt(val.toString())],
|
||||
converter: (val) => Number.parseInt(val)
|
||||
};
|
||||
const partialResultValidator = {
|
||||
name: [(val) => !validator_1.default.isEmpty(val)],
|
||||
age: intValidator,
|
||||
years: intValidator
|
||||
};
|
||||
exports.ResultWebServiceValidation = {
|
||||
keyValidator: intValidator,
|
||||
store: partialResultValidator,
|
||||
replace: {
|
||||
...partialResultValidator,
|
||||
nextage: intValidator
|
||||
}
|
||||
};
|
||||
exports.ResultModelValidation = {
|
||||
propertyRules: { ...partialResultValidator, nextage: intValidator },
|
||||
modelRule: [(m) => m.nextage === m.age + m.years]
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Validator = void 0;
|
||||
const validation_functions_1 = require("./validation_functions");
|
||||
class Validator {
|
||||
ws;
|
||||
validation;
|
||||
constructor(ws, validation) {
|
||||
this.ws = ws;
|
||||
this.validation = validation;
|
||||
}
|
||||
getOne(id) {
|
||||
return this.ws.getOne(this.validateId(id));
|
||||
}
|
||||
getMany(query) {
|
||||
if (this.validation.getMany) {
|
||||
query = (0, validation_functions_1.validate)(query, this.validation.getMany);
|
||||
}
|
||||
return this.ws.getMany(query);
|
||||
}
|
||||
store(data) {
|
||||
if (this.validation.store) {
|
||||
data = (0, validation_functions_1.validate)(data, this.validation.store);
|
||||
}
|
||||
return this.ws.store(data);
|
||||
}
|
||||
delete(id) {
|
||||
return this.ws.delete(this.validateId(id));
|
||||
}
|
||||
replace(id, data) {
|
||||
if (this.validation.replace) {
|
||||
data = (0, validation_functions_1.validate)(data, this.validation.replace);
|
||||
}
|
||||
return this.ws.replace(this.validateId(id), data);
|
||||
}
|
||||
modify(id, data) {
|
||||
if (this.validation.modify) {
|
||||
data = (0, validation_functions_1.validate)(data, this.validation.modify);
|
||||
}
|
||||
return this.ws.modify(this.validateId(id), data);
|
||||
}
|
||||
validateId(val) {
|
||||
return (0, validation_functions_1.validateIdProperty)(val, this.validation);
|
||||
}
|
||||
}
|
||||
exports.Validator = Validator;
|
||||
@@ -0,0 +1,57 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.validateModel = exports.validateIdProperty = exports.validate = void 0;
|
||||
const validation_types_1 = require("./validation_types");
|
||||
function validate(data, reqs) {
|
||||
let validatedData = {};
|
||||
Object.entries(reqs).forEach(([prop, rule]) => {
|
||||
const [valid, value] = applyRule(data[prop], rule);
|
||||
if (valid) {
|
||||
validatedData[prop] = value;
|
||||
}
|
||||
else {
|
||||
throw new validation_types_1.ValidationError(prop, "Validation Error");
|
||||
}
|
||||
});
|
||||
return validatedData;
|
||||
}
|
||||
exports.validate = validate;
|
||||
function applyRule(val, rule) {
|
||||
const required = Array.isArray(rule) ? true : rule.required;
|
||||
const checks = Array.isArray(rule) ? rule : rule.validation;
|
||||
const convert = Array.isArray(rule) ? (v) => v : rule.converter;
|
||||
if (val === null || val == undefined || val === "") {
|
||||
return [required ? false : true, val];
|
||||
}
|
||||
let valid = true;
|
||||
checks.forEach(check => {
|
||||
if (!check(val)) {
|
||||
valid = false;
|
||||
}
|
||||
});
|
||||
return [valid, convert ? convert(val) : val];
|
||||
}
|
||||
function validateIdProperty(val, v) {
|
||||
if (v.keyValidator) {
|
||||
const [valid, value] = applyRule(val, v.keyValidator);
|
||||
if (valid) {
|
||||
return value;
|
||||
}
|
||||
throw new validation_types_1.ValidationError("ID", "Validation Error");
|
||||
}
|
||||
return val;
|
||||
}
|
||||
exports.validateIdProperty = validateIdProperty;
|
||||
function validateModel(model, rules) {
|
||||
if (rules.propertyRules) {
|
||||
model = validate(model, rules.propertyRules);
|
||||
}
|
||||
if (rules.modelRule) {
|
||||
const [valid, data] = applyRule(model, rules.modelRule);
|
||||
if (valid) {
|
||||
return data;
|
||||
}
|
||||
throw new validation_types_1.ValidationError("Model", "Validation Error");
|
||||
}
|
||||
}
|
||||
exports.validateModel = validateModel;
|
||||
@@ -0,0 +1,14 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValidationError = void 0;
|
||||
class ValidationError {
|
||||
name;
|
||||
message;
|
||||
constructor(name, message) {
|
||||
this.name = name;
|
||||
this.message = message;
|
||||
}
|
||||
stack;
|
||||
cause;
|
||||
}
|
||||
exports.ValidationError = ValidationError;
|
||||
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
@@ -0,0 +1,85 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.roleHook = exports.roleGuard = exports.createAuth = void 0;
|
||||
const orm_authstore_1 = require("./orm_authstore");
|
||||
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
|
||||
const passport_1 = __importDefault(require("passport"));
|
||||
const passport_config_1 = require("./passport_config");
|
||||
const jwt_secret = "mytokensecret";
|
||||
const store = new orm_authstore_1.OrmAuthStore();
|
||||
const createAuth = (app) => {
|
||||
(0, passport_config_1.configurePassport)({ store, jwt_secret });
|
||||
app.get("/signin", (req, resp) => {
|
||||
const data = {
|
||||
// username: req.query["username"],
|
||||
// password: req.query["password"],
|
||||
failed: req.query["failed"] ? true : false,
|
||||
signinpage: true
|
||||
};
|
||||
resp.render("signin", data);
|
||||
});
|
||||
app.post("/signin", passport_1.default.authenticate("local", {
|
||||
failureRedirect: `/signin?failed=1`,
|
||||
successRedirect: "/"
|
||||
}));
|
||||
app.use(passport_1.default.authenticate("session"), (req, resp, next) => {
|
||||
resp.locals.user = req.user;
|
||||
resp.locals.authenticated
|
||||
= req.authenticated = req.user !== undefined;
|
||||
next();
|
||||
});
|
||||
app.post("/api/signin", async (req, resp) => {
|
||||
const username = req.body.username;
|
||||
const password = req.body.password;
|
||||
const result = {
|
||||
success: await store.validateCredentials(username, password)
|
||||
};
|
||||
if (result.success) {
|
||||
result.token = jsonwebtoken_1.default.sign({ username }, jwt_secret, { expiresIn: "1hr" });
|
||||
}
|
||||
resp.json(result);
|
||||
resp.end();
|
||||
});
|
||||
app.post("/signout", async (req, resp) => {
|
||||
req.session.destroy(() => {
|
||||
resp.redirect("/");
|
||||
});
|
||||
});
|
||||
app.get("/unauthorized", async (req, resp) => {
|
||||
resp.render("unauthorized");
|
||||
});
|
||||
};
|
||||
exports.createAuth = createAuth;
|
||||
const roleGuard = (role) => {
|
||||
return async (req, resp, next) => {
|
||||
if (req.authenticated) {
|
||||
const username = req.user?.username;
|
||||
if (username != undefined
|
||||
&& await store.validateMembership(username, role)) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
resp.redirect("/unauthorized");
|
||||
}
|
||||
else {
|
||||
resp.redirect("/signin");
|
||||
}
|
||||
};
|
||||
};
|
||||
exports.roleGuard = roleGuard;
|
||||
const roleHook = (role) => {
|
||||
return async (ctx) => {
|
||||
if (!ctx.params.authenticated) {
|
||||
ctx.http = { status: 401 };
|
||||
ctx.result = {};
|
||||
}
|
||||
else if (!(await store.validateMembership(ctx.params.user.username, role))) {
|
||||
ctx.http = { status: 403 };
|
||||
ctx.result = {};
|
||||
}
|
||||
};
|
||||
};
|
||||
exports.roleHook = roleHook;
|
||||
@@ -0,0 +1,23 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initializeAuthModels = exports.RoleModel = exports.CredentialsModel = void 0;
|
||||
const sequelize_1 = require("sequelize");
|
||||
class CredentialsModel extends sequelize_1.Model {
|
||||
}
|
||||
exports.CredentialsModel = CredentialsModel;
|
||||
class RoleModel extends sequelize_1.Model {
|
||||
}
|
||||
exports.RoleModel = RoleModel;
|
||||
const initializeAuthModels = (sequelize) => {
|
||||
CredentialsModel.init({
|
||||
username: { type: sequelize_1.DataTypes.STRING, primaryKey: true },
|
||||
hashedPassword: { type: sequelize_1.DataTypes.BLOB },
|
||||
salt: { type: sequelize_1.DataTypes.BLOB }
|
||||
}, { sequelize });
|
||||
RoleModel.init({
|
||||
name: { type: sequelize_1.DataTypes.STRING, primaryKey: true },
|
||||
}, { sequelize });
|
||||
RoleModel.belongsToMany(CredentialsModel, { through: "RoleMembershipJunction", foreignKey: "name" });
|
||||
CredentialsModel.belongsToMany(RoleModel, { through: "RoleMembershipJunction", foreignKey: "username" });
|
||||
};
|
||||
exports.initializeAuthModels = initializeAuthModels;
|
||||
@@ -0,0 +1,99 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.OrmAuthStore = void 0;
|
||||
const sequelize_1 = require("sequelize");
|
||||
const orm_auth_models_1 = require("./orm_auth_models");
|
||||
const crypto_1 = require("crypto");
|
||||
class OrmAuthStore {
|
||||
sequelize;
|
||||
constructor() {
|
||||
this.sequelize = new sequelize_1.Sequelize({
|
||||
dialect: "sqlite",
|
||||
storage: "orm_auth.db",
|
||||
logging: console.log,
|
||||
logQueryParameters: true
|
||||
});
|
||||
this.initModelAndDatabase();
|
||||
}
|
||||
async initModelAndDatabase() {
|
||||
(0, orm_auth_models_1.initializeAuthModels)(this.sequelize);
|
||||
await this.sequelize.drop();
|
||||
await this.sequelize.sync();
|
||||
await this.storeOrUpdateUser("alice", "mysecret");
|
||||
await this.storeOrUpdateUser("bob", "mysecret");
|
||||
await this.storeOrUpdateRole({
|
||||
name: "Users", members: ["alice", "bob"]
|
||||
});
|
||||
await this.storeOrUpdateRole({
|
||||
name: "Admins", members: ["alice"]
|
||||
});
|
||||
}
|
||||
async getUser(name) {
|
||||
return await orm_auth_models_1.CredentialsModel.findByPk(name);
|
||||
}
|
||||
async storeOrUpdateUser(username, password) {
|
||||
const salt = (0, crypto_1.randomBytes)(16);
|
||||
const hashedPassword = await this.createHashCode(password, salt);
|
||||
const [model] = await orm_auth_models_1.CredentialsModel.upsert({
|
||||
username, hashedPassword, salt
|
||||
});
|
||||
return model;
|
||||
}
|
||||
async validateCredentials(username, password) {
|
||||
const storedCreds = await this.getUser(username);
|
||||
if (storedCreds) {
|
||||
const candidateHash = await this.createHashCode(password, storedCreds.salt);
|
||||
return (0, crypto_1.timingSafeEqual)(candidateHash, storedCreds.hashedPassword);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
createHashCode(password, salt) {
|
||||
return new Promise((resolve, reject) => {
|
||||
(0, crypto_1.pbkdf2)(password, salt, 100000, 64, "sha512", (err, hash) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
;
|
||||
resolve(hash);
|
||||
});
|
||||
});
|
||||
}
|
||||
async getRole(name) {
|
||||
const stored = await orm_auth_models_1.RoleModel.findByPk(name, {
|
||||
include: [{ model: orm_auth_models_1.CredentialsModel, attributes: ["username"] }]
|
||||
});
|
||||
if (stored) {
|
||||
return {
|
||||
name: stored.name,
|
||||
members: stored.CredentialsModels?.map(m => m.username) ?? []
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
async getRolesForUser(username) {
|
||||
return (await orm_auth_models_1.RoleModel.findAll({
|
||||
include: [{
|
||||
model: orm_auth_models_1.CredentialsModel,
|
||||
where: { username },
|
||||
attributes: []
|
||||
}]
|
||||
})).map(rm => rm.name);
|
||||
}
|
||||
async storeOrUpdateRole(role) {
|
||||
return await this.sequelize.transaction(async (transaction) => {
|
||||
const users = await orm_auth_models_1.CredentialsModel.findAll({
|
||||
where: { username: { [sequelize_1.Op.in]: role.members } },
|
||||
transaction
|
||||
});
|
||||
const [rm] = await orm_auth_models_1.RoleModel.findOrCreate({
|
||||
where: { name: role.name }, transaction
|
||||
});
|
||||
await rm.setCredentialsModels(users, { transaction });
|
||||
return role;
|
||||
});
|
||||
}
|
||||
async validateMembership(username, rolename) {
|
||||
return (await this.getRolesForUser(username)).includes(rolename);
|
||||
}
|
||||
}
|
||||
exports.OrmAuthStore = OrmAuthStore;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user