1
0
elk/server/api/[server]/oauth.ts

39 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-11-16 00:48:23 +09:00
import { stringifyQuery } from 'vue-router'
import { createError, defineEventHandler, getQuery, getRouterParams, sendRedirect } from 'h3'
import { getApp, getRedirectURI } from '~/server/shared'
2022-11-15 20:54:07 +09:00
export default defineEventHandler(async (event) => {
const { server } = getRouterParams(event)
2022-11-28 03:44:19 +09:00
const app = await getApp(server)
2022-11-15 23:29:46 +09:00
if (!app) {
throw createError({
statusCode: 400,
statusMessage: `App not registered for server: ${server}`,
})
2022-11-15 23:29:46 +09:00
}
const { code } = getQuery(event)
if (!code) {
throw createError({
statusCode: 422,
statusMessage: 'Missing authentication code.',
})
}
2022-11-15 20:54:07 +09:00
2022-11-16 00:48:23 +09:00
const result: any = await $fetch(`https://${server}/oauth/token`, {
2022-11-15 20:54:07 +09:00
method: 'POST',
body: {
2022-11-15 23:29:46 +09:00
client_id: app.client_id,
client_secret: app.client_secret,
redirect_uri: getRedirectURI(server),
2022-11-15 20:54:07 +09:00
grant_type: 'authorization_code',
code,
scope: 'read write follow push',
},
})
2022-11-15 23:29:46 +09:00
const url = `/signin/callback?${stringifyQuery({ server, token: result.access_token, vapid_key: app.vapid_key })}`
await sendRedirect(event, url, 302)
2022-11-15 20:54:07 +09:00
})