UNPKG

naystack

Version:

A stack built with tight Next + Drizzle + GraphQL

98 lines (94 loc) 2.57 kB
// src/auth/email/utils.ts import { verify as verify2 } from "jsonwebtoken"; // src/auth/email/token.ts import { compare } from "bcryptjs"; import { JsonWebTokenError, sign, verify } from "jsonwebtoken"; import { NextResponse } from "next/server"; function getUserIdFromRefreshToken(refreshKey, refreshToken) { if (refreshToken) try { const decoded = verify(refreshToken, refreshKey); if (typeof decoded !== "string" && typeof decoded.id === "number") return decoded.id; } catch (e) { if (!(e instanceof JsonWebTokenError)) console.error(e, "errors"); return null; } return null; } // src/auth/utils/errors.ts import { NextResponse as NextResponse2 } from "next/server"; function handleError(status, message, onError) { const res = onError?.({ status, message }); if (res) return res; return new NextResponse2(message, { status }); } // src/auth/email/utils.ts async function massageRequest(req, options) { const data = await req.json(); if (!data.email || !data.password) return { error: handleError(400, "Missing email or password", options.onError) }; if (options.turnstileKey) { if (!data.captchaToken) return { error: handleError(400, "Missing captcha", options.onError) }; if (!await verifyCaptcha(data.captchaToken, options.turnstileKey)) return { error: handleError(400, "Invalid captcha", options.onError) }; } return { data: { email: data.email, password: data.password, ...data } }; } async function verifyCaptcha(token, secret) { const res = await fetch( "https://challenges.cloudflare.com/turnstile/v0/siteverify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ secret, response: token }) } ); if (res.ok) { const data = await res.json(); return data.success; } return false; } var getUserContext = (refreshKey, signingKey, req) => { const bearer = req.headers.get("authorization"); if (!bearer) { const refresh = req.cookies.get("refresh")?.value; const userId = getUserIdFromRefreshToken(refreshKey, refresh); if (userId) return { refreshUserID: userId }; return null; } const token = bearer.slice(7); try { const res = verify2(token, signingKey); if (typeof res === "string") { return null; } return { accessUserId: res.id }; } catch { } return null; }; export { getUserContext, massageRequest, verifyCaptcha };