From 22745197e2a773b228253307f8b6ee88e00e6851 Mon Sep 17 00:00:00 2001 From: Sven Sauleau Date: Wed, 15 Feb 2023 18:31:20 +0000 Subject: [PATCH] oauth: get token support code in URL --- backend/test/mastodon/oauth.spec.ts | 20 ++++++++++++++++++++ functions/oauth/token.ts | 19 +++++++++++++++---- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/backend/test/mastodon/oauth.spec.ts b/backend/test/mastodon/oauth.spec.ts index 023b2e4..eb55137 100644 --- a/backend/test/mastodon/oauth.spec.ts +++ b/backend/test/mastodon/oauth.spec.ts @@ -240,5 +240,25 @@ describe('Mastodon APIs', () => { assert.equal(res.status, 200) assertCORS(res) }) + + test('token handles code in URL', async () => { + const db = await makeDB() + const client = await createTestClient(db, 'https://localhost') + + const code = client.id + '.a' + + const req = new Request('https://example.com/oauth/token?code=' + code, { + method: 'POST', + headers: { + 'content-type': 'application/json', + }, + body: '', + }) + const res = await oauth_token.handleRequest(db, req) + assert.equal(res.status, 200) + + const data = await res.json() + assert.equal(data.access_token, code) + }) }) }) diff --git a/functions/oauth/token.ts b/functions/oauth/token.ts index 7c5a479..395761a 100644 --- a/functions/oauth/token.ts +++ b/functions/oauth/token.ts @@ -24,12 +24,23 @@ export async function handleRequest(db: D1Database, request: Request): Promise(request) - if (!data.code) { + let data: Body = { code: null } + try { + data = await readBody(request) + } catch (err: any) { + // ignore error + } + + let code = data.code + if (!code) { + const url = new URL(request.url) + code = url.searchParams.get('code') + } + if (!code) { return errors.notAuthorized('missing authorization') } - const parts = data.code.split('.') + const parts = code.split('.') const clientId = parts[0] const client = await getClientById(db, clientId) @@ -38,7 +49,7 @@ export async function handleRequest(db: D1Database, request: Request): Promise