2023-02-08 20:00:43 +00:00
|
|
|
import { stringifyQuery } from 'ufo'
|
2022-11-15 11:54:07 +00:00
|
|
|
|
2022-11-26 17:56:35 +00:00
|
|
|
export default defineEventHandler(async (event) => {
|
2023-01-01 19:30:39 +00:00
|
|
|
const { origin } = getQuery(event) as { origin: string }
|
2022-12-24 00:51:45 +00:00
|
|
|
let { server } = getRouterParams(event)
|
|
|
|
server = server.toLocaleLowerCase().trim()
|
2023-01-01 19:30:39 +00:00
|
|
|
const app = await getApp(origin, server)
|
2022-11-15 14:29:46 +00:00
|
|
|
|
|
|
|
if (!app) {
|
2022-11-29 22:55:53 +00:00
|
|
|
throw createError({
|
|
|
|
statusCode: 400,
|
|
|
|
statusMessage: `App not registered for server: ${server}`,
|
|
|
|
})
|
2022-11-15 14:29:46 +00:00
|
|
|
}
|
|
|
|
|
2022-11-26 17:56:35 +00:00
|
|
|
const { code } = getQuery(event)
|
2022-11-29 22:55:53 +00:00
|
|
|
if (!code) {
|
|
|
|
throw createError({
|
|
|
|
statusCode: 422,
|
|
|
|
statusMessage: 'Missing authentication code.',
|
|
|
|
})
|
|
|
|
}
|
2022-11-15 11:54:07 +00:00
|
|
|
|
2022-11-15 15:48:23 +00:00
|
|
|
const result: any = await $fetch(`https://${server}/oauth/token`, {
|
2022-11-15 11:54:07 +00:00
|
|
|
method: 'POST',
|
|
|
|
body: {
|
2022-11-15 14:29:46 +00:00
|
|
|
client_id: app.client_id,
|
|
|
|
client_secret: app.client_secret,
|
2023-01-01 19:30:39 +00:00
|
|
|
redirect_uri: getRedirectURI(origin, server),
|
2022-11-15 11:54:07 +00:00
|
|
|
grant_type: 'authorization_code',
|
|
|
|
code,
|
|
|
|
scope: 'read write follow push',
|
|
|
|
},
|
2023-01-09 00:06:47 +00:00
|
|
|
retry: 3,
|
2022-11-15 11:54:07 +00:00
|
|
|
})
|
2022-11-15 14:29:46 +00:00
|
|
|
|
2022-12-17 23:29:16 +00:00
|
|
|
const url = `/signin/callback?${stringifyQuery({ server, token: result.access_token, vapid_key: app.vapid_key })}`
|
2022-11-26 17:56:35 +00:00
|
|
|
await sendRedirect(event, url, 302)
|
2022-11-15 11:54:07 +00:00
|
|
|
})
|