[mastodon-client] Code cleanup and refactor for /oauth/token

This commit is contained in:
Laura Hausmann 2023-10-06 01:22:42 +02:00
parent 4b76d0ce6f
commit a3d2330f26
No known key found for this signature in database
GPG key ID: D044E84C5BE01605
2 changed files with 13 additions and 17 deletions

View file

@ -3,6 +3,7 @@ import { AuthHelpers } from "@/server/api/mastodon/helpers/auth.js";
import { convertId, IdType } from "@/misc/convert-id.js";
import { AuthConverter } from "@/server/api/mastodon/converters/auth.js";
import { v4 as uuid } from "uuid";
import { MastoApiError } from "@/server/api/mastodon/middleware/catch-errors.js";
export function setupEndpointsAuth(router: Router): void {
router.post("/v1/apps", async (ctx) => {
@ -30,9 +31,7 @@ export function setupEndpointsAuthRoot(router: Router): void {
if (state) param += `&state=${state}`;
if (redirect_uri) param += `&redirect_uri=${redirect_uri}`;
const client = client_id ? client_id : "";
ctx.redirect(
`${Buffer.from(client.toString(), "base64").toString()}?${param}`,
);
ctx.redirect(`${Buffer.from(client.toString(), "base64").toString()}?${param}`);
});
router.post("/oauth/token", async (ctx) => {
@ -50,19 +49,14 @@ export function setupEndpointsAuthRoot(router: Router): void {
if (body.code) {
token = body.code;
}
try {
const accessToken = await AuthHelpers.getAuthToken(body.client_secret, token ? token : "");
const ret = {
const accessToken = await AuthHelpers.getAuthToken(body.client_secret, token ? token : "").catch(_ => {
throw new MastoApiError(401);
});
ctx.body = {
access_token: accessToken,
token_type: "Bearer",
scope: body.scope || "read write follow push",
created_at: Math.floor(new Date().getTime() / 1000),
};
ctx.body = ret;
} catch (err: any) {
console.error(err);
ctx.status = 401;
ctx.body = err.response.data;
}
});
}

View file

@ -32,6 +32,7 @@ import { initializeStreamingServer } from "./api/streaming.js";
import removeTrailingSlash from "koa-remove-trailing-slashes";
import { koaBody } from "koa-body";
import { setupEndpointsAuthRoot } from "@/server/api/mastodon/endpoints/auth.js";
import { CatchErrorsMiddleware } from "@/server/api/mastodon/middleware/catch-errors.js";
export const serverLogger = new Logger("server", "gray", false);
// Init app
@ -134,6 +135,7 @@ mastoRouter.use(async (ctx, next) => {
await next();
});
mastoRouter.use(CatchErrorsMiddleware);
setupEndpointsAuthRoot(mastoRouter);
// Register router