Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
import { json, type RequestEvent } from '@sveltejs/kit'; | |
import prisma from '$lib/prisma'; | |
/** @type {import('./$types').RequestHandler} */ | |
export async function GET(request : RequestEvent) { | |
if (!request.cookies.get('hf_access_token')) { | |
return json({ | |
error: { | |
token: "You must be logged" | |
} | |
}, { status: 401 }) | |
} | |
const response = await fetch("https://huggingface.co/oauth/userinfo", { | |
method: "GET", | |
headers: { | |
Authorization: `Bearer ${request.cookies.get('hf_access_token')}`, | |
}, | |
}) | |
const me = await response.clone().json().catch(() => ({})); | |
if (!me?.sub) { | |
return json({ | |
error: { | |
token: "Token is invalid" | |
} | |
}, { status: 401 }) | |
} | |
const userExist = await prisma.user.findFirst({ | |
where: { | |
sub: me.sub | |
} | |
}) | |
let user; | |
if (!userExist) { | |
user = await prisma.user.create({ | |
data: { | |
sub: me.sub, | |
name: me.name, | |
preferred_username: me.preferred_username, | |
picture: me.picture | |
} | |
}) | |
} else { | |
user = await prisma.user.update({ | |
where: { | |
sub: me.sub | |
}, | |
data: { | |
name: me.name, | |
preferred_username: me.preferred_username, | |
picture: me.picture | |
} | |
}) | |
} | |
return json({ | |
user: { | |
...user, | |
is_admin: process?.env?.SECRET_HF_ADMIN?.includes(user.sub) | |
} | |
}) | |
} | |