@opengis/fastify-table
Version:
core-plugins
47 lines (46 loc) • 1.81 kB
JavaScript
import qr from "qrcode";
import config from "../../../../../config.js";
import pgClients from "../../../../plugins/pg/pgClients.js";
import { getSecret, generate } from "./providers/totp.js";
const headers = {
"Content-Type": "image/png",
};
export default async function qrCode(req, reply) {
const { pg = pgClients.client } = req;
const { uid } = req.user || {};
if (!uid) {
return reply.status(401).send({ error: "unauthorized", code: 401 });
}
if (!pg || !pg?.pk?.["admin.users"] || !pg?.pk?.["admin.users_social_auth"]) {
return reply.status(400).send({
error: "db connection / users/users_social_auth tables are required",
code: 400,
});
}
const userExists = await pg
.query(`select uid from admin.users where uid=$1`, [uid])
.then((el) => el.rows?.[0]?.uid);
if (!userExists) {
return reply.status(404).send({ error: "invalid user", code: 404 });
}
const { enabled, secret } = await getSecret({ pg, uid });
const { otp } = secret
? await pg
.query(`select social_auth_url as otp from admin.users_social_auth
where uid=$1 and social_auth_type=$2`, [uid, "TOTP"])
?.then((el) => el.rows?.[0] || {})
: await generate({ uid, pg });
const base64 = otp ? await qr.toDataURL(otp) : undefined;
if (enabled && !config.local && !config.debug) {
return reply
.status(400)
.send({ error: "2factor already enabled", code: 400 });
}
if (!otp || !base64) {
return reply.status(500).send({ error: "generation error", code: 500 });
}
// substring to exclude data:image/png;base64,
return reply
.headers(headers)
.send(Buffer.from(base64.substring(22), "base64"));
}