75 lines
2.6 KiB
TypeScript
75 lines
2.6 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
|
||
|
|
||
|
console.log("CODE:", code)
|
||
|
console.log("SCOPE:", scope)
|
||
|
console.log("STATE:", state)
|
||
|
if (!code || !scope || !state) {
|
||
|
return new NextResponse("Bad Request", { status: 400 });
|
||
|
}
|
||
|
console.log("VERIFY")
|
||
|
// Verify state against user id in user table.
|
||
|
const user = await db.user.findFirst({
|
||
|
where: {
|
||
|
id: state
|
||
|
}
|
||
|
})
|
||
|
|
||
|
console.log("USER", user)
|
||
|
if (!user) {
|
||
|
return new NextResponse("Bad Request", { status: 400 });
|
||
|
}
|
||
|
|
||
|
console.log("FETCH 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,
|
||
|
code: code,
|
||
|
grant_type: "authorization_code",
|
||
|
redirect_uri: "https://hermes.goblincaves.com/api/account/authorize"
|
||
|
})).data
|
||
|
console.log("TOKEN", token)
|
||
|
|
||
|
// 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 });
|
||
|
}
|
||
|
|
||
|
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 });
|
||
|
}
|
||
|
}
|