pis #12

Merged
fred.boniface merged 95 commits from pis into main 2023-05-06 21:54:51 +01:00
6 changed files with 169 additions and 163 deletions
Showing only changes of commit 7580ff8175 - Show all commits

View File

@ -1,31 +1,31 @@
module.exports = {
'env': {
'browser': true,
'commonjs': true,
'es2021': true
},
'extends': 'eslint:recommended',
'overrides': [
'env': {
'browser': true,
'commonjs': true,
'es2021': true
},
'extends': 'eslint:recommended',
'overrides': [
],
'parserOptions': {
'ecmaVersion': 'latest'
},
'rules': {
'indent': [
'error',
2
],
'parserOptions': {
'ecmaVersion': 'latest'
},
'rules': {
'indent': [
'error',
4
],
'linebreak-style': [
'error',
'unix'
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'never'
]
}
'linebreak-style': [
'error',
'unix'
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'never'
]
}
}

View File

@ -1,6 +1,6 @@
const version = {
api: ["/api/v1/",],
app: "2.0.0-dev"
};
api: ['/api/v1/',],
app: '2.0.0-dev'
}
module.exports = version;
module.exports = version

View File

@ -1,82 +1,87 @@
const log = require('../utils/log.utils'); // Log Helper
const log = require('../utils/log.utils') // Log Helper
const dbUser = process.env.OWL_DB_USER || "owl"
const dbPass = process.env.OWL_DB_PASS || "twittwoo"
const dbName = process.env.OWL_DB_NAME || "owlboard"
// eslint-disable-next-line no-undef
const dbUser = process.env.OWL_DB_USER || 'owl'
// eslint-disable-next-line no-undef
const dbPass = process.env.OWL_DB_PASS || 'twittwoo'
// eslint-disable-next-line no-undef
const dbName = process.env.OWL_DB_NAME || 'owlboard'
// eslint-disable-next-line no-undef
const dbPort = process.env.OWL_DB_PORT || 27017
const dbHost = process.env.OWL_DB_HOST || "localhost"
const uri = `mongodb://${dbUser}:${dbPass}@${dbHost}:${dbPort}`;
// eslint-disable-next-line no-undef
const dbHost = process.env.OWL_DB_HOST || 'localhost'
const uri = `mongodb://${dbUser}:${dbPass}@${dbHost}:${dbPort}`
const { MongoClient } = require('mongodb');
const { MongoClient } = require('mongodb')
const client = new MongoClient(uri);
const db = client.db(dbName);
const client = new MongoClient(uri)
const db = client.db(dbName)
async function query(collection, query){
await client.connect();
log.out(`dbAccess.query: Connecting to collection: '${collection}'`, "info")
var qcoll = db.collection(collection);
var qcursor = qcoll.find(query)
qcursor.project({_id: 0})
log.out(`dbAccess.query: Running Query: ${JSON.stringify(query)}`, "info")
increment(collection)
return (await qcursor.toArray());
await client.connect()
log.out(`dbAccess.query: Connecting to collection: '${collection}'`, 'info')
var qcoll = db.collection(collection)
var qcursor = qcoll.find(query)
qcursor.project({_id: 0})
log.out(`dbAccess.query: Running Query: ${JSON.stringify(query)}`, 'info')
increment(collection)
return (await qcursor.toArray())
}
async function increment(target) {
log.out(`dbAccess.increment: Incrementing counter for: ${target}`, "info")
await client.connect();
let col = db.collection("meta");
let update = {}
update[target] = 1
col.updateOne({target: "counters"}, {$inc:update})
log.out(`dbAccess.increment: Incrementing counter for: ${target}`, 'info')
await client.connect()
let col = db.collection('meta')
let update = {}
update[target] = 1
col.updateOne({target: 'counters'}, {$inc:update})
}
async function addUser(uuid, domain) { // Needs testing
log.out(`dbAccess.addUser: Adding user to database`)
let doc = {uuid: uuid, domain: domain, atime: new Date}
await client.connect();
let col = db.collection("users");
res = await col.insertOne(doc);
if (res.insertedId) {
return true
}
return false
log.out('dbAccess.addUser: Adding user to database')
let doc = {uuid: uuid, domain: domain, atime: new Date}
await client.connect()
let col = db.collection('users')
let res = await col.insertOne(doc)
if (res.insertedId) {
return true
}
return false
}
async function addRegReq(uuid, domain) { // Needs testing
log.out(`dbAccess.addRegReq: Adding registration request`)
let doc = {uuid: uuid, time: new Date, domain: domain}
await client.connect();
let col = db.collection("registrations");
res = col.insertOne(doc);
return res;
log.out('dbAccess.addRegReq: Adding registration request')
let doc = {uuid: uuid, time: new Date, domain: domain}
await client.connect()
let col = db.collection('registrations')
let res = col.insertOne(doc)
return res
}
async function userAtime(uuid) { // Needs testing
log.out(`dbAccess.userAtime: Updating access time for user`);
let q = {uuid: uuid};
let n = {$set: {uuid: uuid, atime: new Date}};
await client.connect();
let col = db.collection("users");
res = col.updateOne(q, n, {upsert: true})
return res;
log.out('dbAccess.userAtime: Updating access time for user')
let q = {uuid: uuid}
let n = {$set: {uuid: uuid, atime: new Date}}
await client.connect()
let col = db.collection('users')
let res = col.updateOne(q, n, {upsert: true})
return res
}
// Deletes one single registration request entry from the DB
async function delRegReq(uuid) {
log.out(`dbAccess.delRegReq: Deleting a Registration Request`)
collection = "registrations"
await client.connect()
let col = db.collection(collection)
col.deleteOne({uuid: uuid})
log.out('dbAccess.delRegReq: Deleting a Registration Request')
let collection = 'registrations'
await client.connect()
let col = db.collection(collection)
col.deleteOne({uuid: uuid})
}
module.exports = {
query,
increment, // Probqbly doesn't need exporting?
addUser,
userAtime,
addRegReq,
delRegReq
query,
increment, // Probqbly doesn't need exporting?
addUser,
userAtime,
addRegReq,
delRegReq
}

View File

@ -5,30 +5,30 @@ const log = require('../utils/log.utils')
const clean = require('../utils/sanitizer.utils')
async function findPisByOrigDest(start,end) {
log.out(`pisServices.findPisByOrigDest: Searching for PIS for Orig: ${start}, Dest: ${end}`, 'dbug')
const firstCrs = clean.cleanApiEndpointTxt(start.toLowerCase())
const lastCrs = clean.cleanApiEndpointTxt(end.toLowerCase())
const query = {
stops: {
$all: [
{ $elemMatch: { $eq: firstCrs } },
{ $elemMatch: { $eq: lastCrs } }
]
},
$expr: {
$and: [
{ $eq: [{ $arrayElemAt: [ '$stops', -1 ] }, lastCrs] },
{ $eq: [{ $arrayElemAt: [ '$stops', 0 ] }, firstCrs] }
]
}
log.out(`pisServices.findPisByOrigDest: Searching for PIS for Orig: ${start}, Dest: ${end}`, 'dbug')
const firstCrs = clean.cleanApiEndpointTxt(start.toLowerCase())
const lastCrs = clean.cleanApiEndpointTxt(end.toLowerCase())
const query = {
stops: {
$all: [
{ $elemMatch: { $eq: firstCrs } },
{ $elemMatch: { $eq: lastCrs } }
]
},
$expr: {
$and: [
{ $eq: [{ $arrayElemAt: [ '$stops', -1 ] }, lastCrs] },
{ $eq: [{ $arrayElemAt: [ '$stops', 0 ] }, firstCrs] }
]
}
//const oldQuery = {$and:[{$expr:{$eq:[{$first:"$stops"},firstCrs]}},{$expr:{$eq:[{$last:"$stops"},lastCrs]}}]}
const search = db.query('pis', query)
return search
}
//const oldQuery = {$and:[{$expr:{$eq:[{$first:"$stops"},firstCrs]}},{$expr:{$eq:[{$last:"$stops"},lastCrs]}}]}
const search = db.query('pis', query)
return search
}
// Hopefully at some point, I will also be able to implement a find PIS code by headcode option.
module.exports = {
findPisByOrigDest
findPisByOrigDest
}

View File

@ -1,24 +1,25 @@
const log = require('../utils/log.utils'); // Log Helper
const log = require('../utils/log.utils') // Log Helper
const db = require('../services/dbAccess.services')
const os = require('os')
const vers = require('../configs/version.configs')
async function hits(){
log.out("statsServices.hits: Statistics Requested", "info")
var dat = db.query("meta", {target: "counters"});
var ver = db.query("meta", {target: "versions"});
log.out(`statsServices.hits: fetched server meta`, "info")
let out = {};
out.host = os.hostname();
out.mode = process.env.NODE_ENV;
out.verBkend = vers.app;
out.verApi = vers.api;
out.dat = await dat;
out.ver = await ver;
log.out(`statsServices.hits: Sending Data: ${JSON.stringify(out)}`, "info")
return out;
log.out('statsServices.hits: Statistics Requested', 'info')
var dat = db.query('meta', {target: 'counters'})
var ver = db.query('meta', {target: 'versions'})
log.out('statsServices.hits: fetched server meta', 'info')
let out = {}
out.host = os.hostname()
// eslint-disable-next-line no-undef
out.mode = process.env.NODE_ENV
out.verBkend = vers.app
out.verApi = vers.api
out.dat = await dat
out.ver = await ver
log.out(`statsServices.hits: Sending Data: ${JSON.stringify(out)}`, 'info')
return out
}
module.exports = {
hits
hits
}

View File

@ -1,60 +1,60 @@
const log = require('../utils/log.utils');
const log = require('../utils/log.utils')
const crypto = require('crypto')
const db = require('../services/dbAccess.services');
const db = require('../services/dbAccess.services')
const fs = require('fs/promises')
const minify = require('html-minifier').minify;
const minify = require('html-minifier').minify
// Checks users registration key against issued keys
async function isAuthed(uuid) { // Needs testing
const q = {uuid: uuid}
const res = await db.query("users", q)
log.out(`authUtils.checkUser: DB Query answer: ${JSON.stringify(res[0])}`, "dbug")
const authorized = res && res[0] && res[0].domain;
if (authorized) db.userAtime(uuid)
return authorized
const q = {uuid: uuid}
const res = await db.query('users', q)
log.out(`authUtils.checkUser: DB Query answer: ${JSON.stringify(res[0])}`, 'dbug')
const authorized = res && res[0] && res[0].domain
if (authorized) db.userAtime(uuid)
return authorized
}
// Checks whether a registration request key is valid
async function checkRequest(key) {
const collection = "registrations"
const query = {uuid: key}
const res = await db.query(collection, query)
log.out(`authUtils.checkRequest: DB Query result: ${JSON.stringify(res)}`, "dbug")
const result = res.length > 0 && res[0].time
? { result: true, domain: res[0].domain }
: { result: false };
return result;
const collection = 'registrations'
const query = {uuid: key}
const res = await db.query(collection, query)
log.out(`authUtils.checkRequest: DB Query result: ${JSON.stringify(res)}`, 'dbug')
const result = res.length > 0 && res[0].time
? { result: true, domain: res[0].domain }
: { result: false }
return result
}
// Creates an API key for a user
async function generateKey() { // Needs testing & moving to 'register.utils'
return crypto.randomUUID()
};
return crypto.randomUUID()
}
async function generateConfirmationEmail(eml, uuid) {
try {
let htmlTpl = await fs.readFile('mail-templates/register.html', 'utf-8');
let mini = minify(((htmlTpl).replace(/>>ACCESSCODE<</g, uuid)), { // Add collapse whitespace here
removeComments: true,
collapseWhitespace: true,
minifyCSS: true
});
let txtTpl = fs.readFile('mail-templates/register.txt', 'utf-8');
return msg = { // CSS Needs to be inlined. See css-inline, or css-inliner
to: eml,
subject: "OwlBoard Registration",
text: (await txtTpl).replace(/>>ACCESSCODE<</g, uuid),
html: mini
}
} catch(err) {
log.out(`mailServices.generateConfirmationEmail: Error reading templates, $(err)`, "err");
return false;
try {
let htmlTpl = await fs.readFile('mail-templates/register.html', 'utf-8')
let mini = minify(((htmlTpl).replace(/>>ACCESSCODE<</g, uuid)), { // Add collapse whitespace here
removeComments: true,
collapseWhitespace: true,
minifyCSS: true
})
let txtTpl = fs.readFile('mail-templates/register.txt', 'utf-8')
return { // CSS Needs to be inlined. See css-inline, or css-inliner
to: eml,
subject: 'OwlBoard Registration',
text: (await txtTpl).replace(/>>ACCESSCODE<</g, uuid),
html: mini
}
} catch(err) {
log.out('mailServices.generateConfirmationEmail: Error reading templates, $(err)', 'err')
return false
}
}
module.exports = {
isAuthed,
generateKey,
generateConfirmationEmail,
checkRequest
isAuthed,
generateKey,
generateConfirmationEmail,
checkRequest
}