hermes-web/app/api/account/reauthorize/route.ts
2023-12-30 10:56:40 +00:00

73 lines
2.5 KiB
TypeScript

import axios from 'axios'
import { db } from "@/lib/db"
import { NextResponse } from "next/server";
import { GET as authorize } from '../authorize/route'
export async function GET(req: Request) {
try {
// Verify state against user id in user table.
const key = await db.apiKey.findFirst({
where: {
id: req.headers.get('x-api-key') as string
}
})
console.log("API USER:", key)
if (!key) {
return new NextResponse("Forbidden", { status: 403 });
}
const connection = await db.twitchConnection.findFirst({
where: {
userId: key.userId
}
})
if (!connection) {
return new NextResponse("Forbidden", { status: 403 });
}
try {
const { expires_in }: { client_id:string, login:string, scopes:string[], user_id:string, expires_in:number } = (await axios.get("https://id.twitch.tv/oauth2/validate", {
headers: {
Authorization: 'OAuth ' + connection.accessToken
}
})).data;
if (expires_in > 3600)
return new NextResponse("", { status: 201 });
} catch (error) {
console.log("Oudated Twitch token.")
}
// Post to https://id.twitch.tv/oauth2/token
const token: { access_token:string, expires_in:number, refresh_token:string, token_type:string, scope:string[] } = (await axios.post("https://id.twitch.tv/oauth2/token", {
client_id: process.env.TWITCH_BOT_CLIENT_ID,
client_secret: process.env.TWITCH_BOT_CLIENT_SECRET,
grant_type: "refresh_token",
refresh_token: connection.refreshToken
})).data
// Fetch values from token.
const { access_token, expires_in, refresh_token, token_type } = token
console.log("AT", access_token)
console.log("RT", refresh_token)
console.log("TT", token_type)
if (!access_token || !refresh_token || token_type !== "bearer") {
return new NextResponse("Unauthorized", { status: 401 });
}
await db.twitchConnection.update({
where: {
userId: key.userId
},
data: {
accessToken: access_token
}
})
return new NextResponse("", { status: 200 });
} catch (error) {
console.log("[ACCOUNT]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}