UNPKG

@opengis/fastify-table

Version:

core-plugins

130 lines (129 loc) 4.77 kB
import { Agent } from "undici"; import config from "../../../../../config.js"; import { applyHook } from "../../../../../utils.js"; import logger from "../../../../plugins/logger/getLogger.js"; import pgClients from "../../../../plugins/pg/pgClients.js"; import checkReferer from "../../../../plugins/auth/funcs/checkReferer.js"; import getQuery from "../../../../plugins/auth/funcs/getQuery.js"; import logAuth from "../../../../plugins/auth/funcs/logAuth.js"; import authorizeUser from "../../../../plugins/auth/funcs/authorizeUser.js"; function fetchWithoutSSL(url, options) { const httpsAgent = new Agent({ connect: { rejectUnauthorized: false, }, }); return fetch(url, { ...(options || {}), dispatcher: httpsAgent, }); } const getIp = (req) => (req.headers?.["x-real-ip"] || req.headers?.["x-forwarded-for"] || req.ip || req.connection?.remoteAddress || "") .split(":") .pop(); export default async function authByData(req, reply) { const { pg = pgClients.client, query = {}, headers = {} } = req; const { referer } = headers; const d1 = Date.now(); const timeList = [d1]; const ip = getIp(req); const { data: code, type } = query; // token const { security } = config; const authType = type || (referer?.includes("softpro.ua") ? "google" : null) || (referer?.includes("nsdi.gov.ua") ? "govid" : null) || (referer?.includes("admin.nsdi.gki.com.ua") ? "govid" : null); // fix admin auth const hostOauth = { google: security?.social_auth_host_local || "https://id.softpro.ua", govid: security?.id_gov_ua_host_local || "https://nsdi.gov.ua", }[authType || ""]; if (!hostOauth) { logger.file("auth/by_data/warn", { error: "invalid oauth params", referer, authType, hostOauth, }); return reply.status(400).send("Невалідний парметр тип авторизації"); } // referer + token check const invalidReferer = await checkReferer({ req, referer, hostOauth, }); if (!code || invalidReferer) { logger.file("auth/by_data/warn", { error: "invalid request", referer, code, }); return reply .status(403) .send("Параметри data / code / state мають невірний формат, або Ви перейшли за прямим посиланням."); } const url = authType === "govid" ? `${hostOauth}/api-user/auth_data?token=${code}` : `${hostOauth}/oauth/token?code=${code}`; try { const response = await fetchWithoutSSL(url); const body = await response.text(); console.log(`${authType} login: ${code} ${config.debug ? body : ""}`); if (response.status !== 200 || !body?.startsWith?.("{")) { return reply.status(response.status).send(body); } const data = JSON.parse(body); const hookData = (await applyHook("onAuthByData", { req, pg, data, authType, })); if (hookData?.href) { return reply.redirect(hookData.href); } // get user / create new user const _user = config.pg && !hookData?.user ? await getQuery({ pg, data }) : hookData?.user || {}; await logAuth({ uid: _user?.uid, type: "byData", data, ip, }, pg); console.log("register user sql"); timeList.push(Date.now()); logger.file("auth/by_data", { msec: Date.now() - d1, time: { total: timeList[5] - timeList[0], authorization_code: timeList[1] - timeList[0], access_token: timeList[2] - timeList[1], develop: timeList[3] - timeList[2], getQueryGovua: timeList[4] - timeList[3], register: timeList[5] - timeList[4], }, serial: data?.serial, query: { code }, ip, }); // console.log(user) const href = await authorizeUser(_user, req, authType); // govid / google(social) // console.log(href) return reply.redirect(href); } catch (err) { logger.file("auth/by_data/error", { error: err.toString(), stack: err.stack, }); return reply .status(500) .send(`Помилка авторизації через ${authType === "govid" ? "id.gov.ua" : "google"}. Зверніться до Адміністратора!`); } }