hermes-web/app/api/account/authorize/route.ts

72 lines
2.5 KiB
TypeScript
Raw Normal View History

2023-12-30 05:56:40 -05:00
import axios from 'axios'
import { db } from "@/lib/db"
import { NextResponse } from "next/server";
export async function GET(req: Request) {
try {
const { searchParams } = new URL(req.url)
const code = searchParams.get('code') as string
const scope = searchParams.get('scope') as string
const state = searchParams.get('state') as string
console.log("CODE:", code)
console.log("SCOPE:", scope)
console.log("STATE:", state)
if (!code || !scope || !state) {
return new NextResponse("Bad Request", { status: 400 });
}
2023-12-30 05:56:40 -05:00
// Verify state against user id in user table.
const user = await db.user.findFirst({
where: {
id: state
}
})
if (!user) {
return new NextResponse("Bad Request", { status: 400 });
}
// 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,
code: code,
grant_type: "authorization_code",
redirect_uri: "https://hermes.goblincaves.com/api/account/authorize"
})).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)
2023-12-30 05:56:40 -05:00
if (!access_token || !refresh_token || token_type !== "bearer") {
return new NextResponse("Unauthorized", { status: 401 });
}
let info = await axios.get("https://api.twitch.tv/helix/users?login=" + user.username, {
headers: {
"Authorization": "Bearer " + access_token,
"Client-Id": process.env.TWITCH_BOT_CLIENT_ID
}
})
console.log(info.data.data)
const broadcasterId = info.data.data[0]['id']
await db.twitchConnection.create({
data: {
broadcasterId: broadcasterId,
accessToken: access_token,
refreshToken: refresh_token,
userId: state
}
})
return new NextResponse("", { status: 200 });
} catch (error) {
console.log("[ACCOUNT]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}