backend/src/utils/auth.utils.js

60 lines
2.1 KiB
JavaScript
Raw Normal View History

const log = require('../utils/log.utils');
const crypto = require('crypto')
const db = require('../services/dbAccess.services');
const fs = require('fs/promises')
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
}
// 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;
}
// Creates an API key for a user
async function generateKey() { // Needs testing & moving to 'register.utils'
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;
}
}
module.exports = {
isAuthed,
generateKey,
generateConfirmationEmail,
checkRequest
}