changed anilist login flow

This commit is contained in:
2026-01-06 20:12:08 +01:00
parent 8296e8d7da
commit 82ddc6d5e9
10 changed files with 602 additions and 161 deletions

View File

@@ -2,58 +2,49 @@ import { FastifyInstance } from "fastify";
import { run } from "../../shared/database";
async function anilist(fastify: FastifyInstance) {
fastify.get("/anilist", async (request, reply) => {
fastify.post("/anilist/store", async (request, reply) => {
try {
const { code, state } = request.query as { code?: string; state?: string };
const {
userId,
accessToken,
tokenType = "Bearer",
expiresIn
} = request.body as {
userId: number;
accessToken: string;
tokenType?: string;
expiresIn?: number;
};
if (!code) return reply.status(400).send("No code");
if (!state) return reply.status(400).send("No user state");
const userId = Number(state);
if (!userId || isNaN(userId)) {
return reply.status(400).send("Invalid user id");
}
const tokenRes = await fetch("https://anilist.co/api/v2/oauth/token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
grant_type: "authorization_code",
client_id: process.env.ANILIST_CLIENT_ID,
client_secret: process.env.ANILIST_CLIENT_SECRET,
redirect_uri: "http://localhost:54322/api/anilist",
code
})
});
const tokenData = await tokenRes.json();
if (!tokenData.access_token) {
console.error("AniList token error:", tokenData);
return reply.status(500).send("Failed to get AniList token");
if (!userId || !accessToken) {
return reply.status(400).send({ error: "Faltan datos (User ID o Token)" });
}
// 1. Verificar que el token es válido consultando a AniList
const userRes = await fetch("https://graphql.anilist.co", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${tokenData.token_type} ${tokenData.access_token}`
Authorization: `${tokenType} ${accessToken}`
},
body: JSON.stringify({
query: `query { Viewer { id } }`
})
});
if (!userRes.ok) {
return reply.status(401).send({ error: "Token de AniList inválido o expirado" });
}
const userData = await userRes.json();
const anilistUserId = userData?.data?.Viewer?.id;
if (!anilistUserId) {
console.error("AniList Viewer error:", userData);
return reply.status(500).send("Failed to fetch AniList user");
return reply.status(500).send({ error: "No se pudo obtener el ID de usuario de AniList" });
}
const expiresAt = new Date(
Date.now() + tokenData.expires_in * 1000
Date.now() + 365 * 24 * 60 * 60 * 1000
).toISOString();
await run(
@@ -71,19 +62,19 @@ async function anilist(fastify: FastifyInstance) {
[
userId,
"AniList",
tokenData.access_token,
tokenData.refresh_token,
tokenData.token_type,
accessToken,
"", // <- aquí
tokenType,
anilistUserId,
expiresAt
],
"userdata"
);
return reply.redirect("http://localhost:54322/?anilist=success");
return reply.send({ ok: true, anilistUserId });
} catch (e) {
console.error("AniList error:", e);
return reply.redirect("http://localhost:54322/?anilist=error");
return reply.status(500).send({ error: "Error interno del servidor al guardar AniList" });
}
});
}