65 lines
2.3 KiB
TypeScript
65 lines
2.3 KiB
TypeScript
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
|
|
|
|
if (!code || !scope || !state) {
|
|
return new NextResponse("Bad Request", { status: 400 });
|
|
}
|
|
|
|
// 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://tomtospeech.com/api/account/authorize"
|
|
})).data
|
|
|
|
// Fetch values from token.
|
|
const { access_token, expires_in, refresh_token, token_type } = token
|
|
|
|
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.name, {
|
|
headers: {
|
|
"Authorization": "Bearer " + access_token,
|
|
"Client-Id": process.env.TWITCH_BOT_CLIENT_ID
|
|
}
|
|
})
|
|
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/AUTHORIZE]", error);
|
|
return new NextResponse("Internal Error", { status: 500 });
|
|
}
|
|
} |