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

92 lines
3.5 KiB
TypeScript

import { db } from "@/lib/db"
import { NextResponse } from "next/server";
import fetchUserWithImpersonation from '@/lib/fetch-user-impersonation';
import axios from "axios";
export async function POST(req: Request) {
try {
const user = await fetchUserWithImpersonation(req);
if (!user)
return NextResponse.json({ error: null, message: "Unauthorized", success: false }, { status: 401 });
let { access_token, expires_in, token_type, scope, state } = await req.json();
if (!token_type)
return NextResponse.json({ error: null, message: 'No token type given for the authorization.', success: false }, { status: 400 })
if (!access_token)
return NextResponse.json({ error: null, message: 'No access token given for the authorization.', success: false }, { status: 400 })
if (!scope)
return NextResponse.json({ error: null, message: 'No scope given for the authorization.', success: false }, { status: 400 })
if (!state)
return NextResponse.json({ error: null, message: 'No state given for the authorization.', success: false }, { status: 400 })
// Fetch connection state data
const info = await db.connectionState.findUnique({
where: {
state: state
}
})
if (!info)
return NextResponse.json({ error: null, message: 'No authorization code was received previously.', success: false }, { status: 400 })
if (info.type == "twitch") {
const response = await axios.get("https://id.twitch.tv/oauth2/validate", {
headers: {
Authorization: 'OAuth ' + access_token
}
})
expires_in = response.data.expires_in
}
if (!expires_in)
return NextResponse.json({ error: null, message: 'No expiration given for the authorization.', success: false }, { status: 400 })
let expiration = new Date()
expiration.setSeconds(expiration.getSeconds() + parseInt(expires_in) - 600);
await db.connection.upsert({
where: {
userId_name: {
userId: info.userId,
name: info.name
}
},
create: {
userId: info.userId,
name: info.name,
type: info.type,
clientId: info.clientId,
accessToken: access_token,
scope,
grantType: token_type,
expiresAt: expiration
},
update: {
clientId: info.clientId,
accessToken: access_token,
scope,
grantType: token_type,
expiresAt: expiration
}
})
await db.connectionState.delete({
where: {
userId_name: {
userId: user.id,
name: info.name
}
}
})
return NextResponse.json({ error: null, message: "", success: true }, { status: 200 });
} catch (error: any) {
if (error.name == 'PrismaClientKnownRequestError') {
if (error.code == 'P2002')
return NextResponse.json({ error, message: "Connection already saved.", success: false }, { status: 500 });
}
return NextResponse.json({ error, message: "Failed to save connection", success: false }, { status: 500 });
}
}