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 = { module.exports = {
'env': { 'env': {
'browser': true, 'browser': true,
'commonjs': true, 'commonjs': true,
'es2021': true 'es2021': true
}, },
'extends': 'eslint:recommended', 'extends': 'eslint:recommended',
'overrides': [ 'overrides': [
],
'parserOptions': {
'ecmaVersion': 'latest'
},
'rules': {
'indent': [
'error',
2
], ],
'parserOptions': { 'linebreak-style': [
'ecmaVersion': 'latest' 'error',
}, 'unix'
'rules': { ],
'indent': [ 'quotes': [
'error', 'error',
4 'single'
], ],
'linebreak-style': [ 'semi': [
'error', 'error',
'unix' 'never'
], ]
'quotes': [ }
'error',
'single'
],
'semi': [
'error',
'never'
]
}
} }

View File

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

View File

@ -5,30 +5,30 @@ const log = require('../utils/log.utils')
const clean = require('../utils/sanitizer.utils') const clean = require('../utils/sanitizer.utils')
async function findPisByOrigDest(start,end) { async function findPisByOrigDest(start,end) {
log.out(`pisServices.findPisByOrigDest: Searching for PIS for Orig: ${start}, Dest: ${end}`, 'dbug') log.out(`pisServices.findPisByOrigDest: Searching for PIS for Orig: ${start}, Dest: ${end}`, 'dbug')
const firstCrs = clean.cleanApiEndpointTxt(start.toLowerCase()) const firstCrs = clean.cleanApiEndpointTxt(start.toLowerCase())
const lastCrs = clean.cleanApiEndpointTxt(end.toLowerCase()) const lastCrs = clean.cleanApiEndpointTxt(end.toLowerCase())
const query = { const query = {
stops: { stops: {
$all: [ $all: [
{ $elemMatch: { $eq: firstCrs } }, { $elemMatch: { $eq: firstCrs } },
{ $elemMatch: { $eq: lastCrs } } { $elemMatch: { $eq: lastCrs } }
] ]
}, },
$expr: { $expr: {
$and: [ $and: [
{ $eq: [{ $arrayElemAt: [ '$stops', -1 ] }, lastCrs] }, { $eq: [{ $arrayElemAt: [ '$stops', -1 ] }, lastCrs] },
{ $eq: [{ $arrayElemAt: [ '$stops', 0 ] }, firstCrs] } { $eq: [{ $arrayElemAt: [ '$stops', 0 ] }, firstCrs] }
] ]
}
} }
//const oldQuery = {$and:[{$expr:{$eq:[{$first:"$stops"},firstCrs]}},{$expr:{$eq:[{$last:"$stops"},lastCrs]}}]} }
const search = db.query('pis', query) //const oldQuery = {$and:[{$expr:{$eq:[{$first:"$stops"},firstCrs]}},{$expr:{$eq:[{$last:"$stops"},lastCrs]}}]}
return search 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. // Hopefully at some point, I will also be able to implement a find PIS code by headcode option.
module.exports = { 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 db = require('../services/dbAccess.services')
const os = require('os') const os = require('os')
const vers = require('../configs/version.configs') const vers = require('../configs/version.configs')
async function hits(){ async function hits(){
log.out("statsServices.hits: Statistics Requested", "info") log.out('statsServices.hits: Statistics Requested', 'info')
var dat = db.query("meta", {target: "counters"}); var dat = db.query('meta', {target: 'counters'})
var ver = db.query("meta", {target: "versions"}); var ver = db.query('meta', {target: 'versions'})
log.out(`statsServices.hits: fetched server meta`, "info") log.out('statsServices.hits: fetched server meta', 'info')
let out = {}; let out = {}
out.host = os.hostname(); out.host = os.hostname()
out.mode = process.env.NODE_ENV; // eslint-disable-next-line no-undef
out.verBkend = vers.app; out.mode = process.env.NODE_ENV
out.verApi = vers.api; out.verBkend = vers.app
out.dat = await dat; out.verApi = vers.api
out.ver = await ver; out.dat = await dat
log.out(`statsServices.hits: Sending Data: ${JSON.stringify(out)}`, "info") out.ver = await ver
return out; log.out(`statsServices.hits: Sending Data: ${JSON.stringify(out)}`, 'info')
return out
} }
module.exports = { 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 crypto = require('crypto')
const db = require('../services/dbAccess.services'); const db = require('../services/dbAccess.services')
const fs = require('fs/promises') const fs = require('fs/promises')
const minify = require('html-minifier').minify; const minify = require('html-minifier').minify
// Checks users registration key against issued keys // Checks users registration key against issued keys
async function isAuthed(uuid) { // Needs testing async function isAuthed(uuid) { // Needs testing
const q = {uuid: uuid} const q = {uuid: uuid}
const res = await db.query("users", q) const res = await db.query('users', q)
log.out(`authUtils.checkUser: DB Query answer: ${JSON.stringify(res[0])}`, "dbug") log.out(`authUtils.checkUser: DB Query answer: ${JSON.stringify(res[0])}`, 'dbug')
const authorized = res && res[0] && res[0].domain; const authorized = res && res[0] && res[0].domain
if (authorized) db.userAtime(uuid) if (authorized) db.userAtime(uuid)
return authorized return authorized
} }
// Checks whether a registration request key is valid // Checks whether a registration request key is valid
async function checkRequest(key) { async function checkRequest(key) {
const collection = "registrations" const collection = 'registrations'
const query = {uuid: key} const query = {uuid: key}
const res = await db.query(collection, query) const res = await db.query(collection, query)
log.out(`authUtils.checkRequest: DB Query result: ${JSON.stringify(res)}`, "dbug") log.out(`authUtils.checkRequest: DB Query result: ${JSON.stringify(res)}`, 'dbug')
const result = res.length > 0 && res[0].time const result = res.length > 0 && res[0].time
? { result: true, domain: res[0].domain } ? { result: true, domain: res[0].domain }
: { result: false }; : { result: false }
return result; return result
} }
// Creates an API key for a user // Creates an API key for a user
async function generateKey() { // Needs testing & moving to 'register.utils' async function generateKey() { // Needs testing & moving to 'register.utils'
return crypto.randomUUID() return crypto.randomUUID()
}; }
async function generateConfirmationEmail(eml, uuid) { async function generateConfirmationEmail(eml, uuid) {
try { try {
let htmlTpl = await fs.readFile('mail-templates/register.html', 'utf-8'); let htmlTpl = await fs.readFile('mail-templates/register.html', 'utf-8')
let mini = minify(((htmlTpl).replace(/>>ACCESSCODE<</g, uuid)), { // Add collapse whitespace here let mini = minify(((htmlTpl).replace(/>>ACCESSCODE<</g, uuid)), { // Add collapse whitespace here
removeComments: true, removeComments: true,
collapseWhitespace: true, collapseWhitespace: true,
minifyCSS: true minifyCSS: true
}); })
let txtTpl = fs.readFile('mail-templates/register.txt', 'utf-8'); let txtTpl = fs.readFile('mail-templates/register.txt', 'utf-8')
return msg = { // CSS Needs to be inlined. See css-inline, or css-inliner return { // CSS Needs to be inlined. See css-inline, or css-inliner
to: eml, to: eml,
subject: "OwlBoard Registration", subject: 'OwlBoard Registration',
text: (await txtTpl).replace(/>>ACCESSCODE<</g, uuid), text: (await txtTpl).replace(/>>ACCESSCODE<</g, uuid),
html: mini html: mini
}
} catch(err) {
log.out(`mailServices.generateConfirmationEmail: Error reading templates, $(err)`, "err");
return false;
} }
} catch(err) {
log.out('mailServices.generateConfirmationEmail: Error reading templates, $(err)', 'err')
return false
}
} }
module.exports = { module.exports = {
isAuthed, isAuthed,
generateKey, generateKey,
generateConfirmationEmail, generateConfirmationEmail,
checkRequest checkRequest
} }