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

67 lines
2.5 KiB
TypeScript

// TODO: remove this page.
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 NextResponse.json({ message: 'Missing oauth2 data.', error: null, value: null }, { status: 400 });
}
// Verify state against user id in user table.
const user = await db.user.findFirst({
where: {
id: state
}
})
if (!user) {
return NextResponse.json({ message: 'You do not have permissions for this.', error: null, value: null }, { status: 403 });
}
// 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 NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { 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 NextResponse.json({ message: null, error: null, value: null }, { status: 200 })
} catch (error) {
console.log("[ACCOUNT/AUTHORIZE]", error);
return NextResponse.json({ message: 'Something went wrong', error: error, value: null }, { status: 500 })
}
}