refactor(database): ♻️ Move Token to its own ORM abstraction, optimize familiar_followers route

This commit is contained in:
Jesse Wierzbinski 2024-11-03 17:45:21 +01:00
parent 962c159ddd
commit 845041e4db
No known key found for this signature in database
55 changed files with 694 additions and 504 deletions

View file

@ -47,7 +47,7 @@ describe("/oauth/authorize", () => {
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
@ -79,7 +79,7 @@ describe("/oauth/authorize", () => {
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: "jwt=invalid-jwt",
},
@ -118,7 +118,7 @@ describe("/oauth/authorize", () => {
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
@ -160,7 +160,7 @@ describe("/oauth/authorize", () => {
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
@ -200,7 +200,7 @@ describe("/oauth/authorize", () => {
const response2 = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt2}`,
},
@ -245,7 +245,7 @@ describe("/oauth/authorize", () => {
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
@ -289,7 +289,7 @@ describe("/oauth/authorize", () => {
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
@ -331,7 +331,7 @@ describe("/oauth/authorize", () => {
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
@ -373,7 +373,7 @@ describe("/oauth/authorize", () => {
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},

View file

@ -1,11 +1,10 @@
import { auth, jsonOrForm } from "@/api";
import { randomString } from "@/math";
import { Application, User, db } from "@versia/kit/db";
import { RolePermissions, Tokens } from "@versia/kit/tables";
import { Application, Token, User } from "@versia/kit/db";
import { RolePermissions } from "@versia/kit/tables";
import { type JWTPayload, SignJWT, jwtVerify } from "jose";
import { JOSEError } from "jose/errors";
import { z } from "zod";
import { TokenType } from "~/classes/functions/token";
import type { PluginType } from "../index.ts";
const schemas = {
@ -282,11 +281,11 @@ export default (plugin: PluginType): void =>
.setProtectedHeader({ alg: "EdDSA" })
.sign(keys.private);
await db.insert(Tokens).values({
await Token.insert({
accessToken: randomString(64, "base64url"),
code,
scope: scope ?? application.data.scopes,
tokenType: TokenType.Bearer,
tokenType: "Bearer",
applicationId: application.id,
redirectUri: redirect_uri ?? application.data.redirectUri,
expiresAt: new Date(

View file

@ -1,16 +1,10 @@
import { randomString } from "@/math.ts";
import { setCookie } from "@hono/hono/cookie";
import { createRoute, z } from "@hono/zod-openapi";
import { User, db } from "@versia/kit/db";
import { Token, User, db } from "@versia/kit/db";
import { type SQL, and, eq, isNull } from "@versia/kit/drizzle";
import {
OpenIdAccounts,
RolePermissions,
Tokens,
Users,
} from "@versia/kit/tables";
import { OpenIdAccounts, RolePermissions, Users } from "@versia/kit/tables";
import { SignJWT } from "jose";
import { TokenType } from "~/classes/functions/token.ts";
import type { PluginType } from "../../index.ts";
import { automaticOidcFlow } from "../../utils.ts";
@ -314,11 +308,11 @@ export default (plugin: PluginType): void => {
const code = randomString(32, "hex");
await db.insert(Tokens).values({
await Token.insert({
accessToken: randomString(64, "base64url"),
code,
scope: flow.application.scopes,
tokenType: TokenType.Bearer,
tokenType: "Bearer",
userId: user.id,
applicationId: flow.application.id,
});

View file

@ -1,7 +1,5 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { Application, db } from "@versia/kit/db";
import { eq } from "@versia/kit/drizzle";
import { Tokens } from "@versia/kit/tables";
import { afterAll, describe, expect, test } from "bun:test";
import { Application, Token } from "@versia/kit/db";
import { fakeRequest, getTestUsers } from "~/tests/utils";
const { deleteUsers, users } = await getTestUsers(1);
@ -13,28 +11,23 @@ const application = await Application.insert({
secret: "test-secret",
name: "Test Application",
});
beforeAll(async () => {
await db.insert(Tokens).values({
code: "test-code",
redirectUri: application.data.redirectUri,
clientId: application.data.clientId,
accessToken: "test-access-token",
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
createdAt: new Date().toISOString(),
tokenType: "Bearer",
scope: application.data.scopes,
userId: users[0].id,
applicationId: application.id,
});
const token = await Token.insert({
code: "test-code",
redirectUri: application.data.redirectUri,
clientId: application.data.clientId,
accessToken: "test-access-token",
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
createdAt: new Date().toISOString(),
tokenType: "Bearer",
scope: application.data.scopes,
userId: users[0].id,
applicationId: application.id,
});
afterAll(async () => {
await deleteUsers();
await application.delete();
await db
.delete(Tokens)
.where(eq(Tokens.clientId, application.data.clientId));
await token.delete();
});
describe("/oauth/revoke", () => {

View file

@ -1,7 +1,7 @@
import { jsonOrForm } from "@/api";
import { createRoute, z } from "@hono/zod-openapi";
import { db } from "@versia/kit/db";
import { type SQL, eq } from "@versia/kit/drizzle";
import { Token, db } from "@versia/kit/db";
import { and, eq } from "@versia/kit/drizzle";
import { Tokens } from "@versia/kit/tables";
import type { PluginType } from "../../index.ts";
@ -62,16 +62,12 @@ export default (plugin: PluginType): void => {
const { client_id, client_secret, token } =
context.req.valid("json");
const foundToken = await db.query.Tokens.findFirst({
where: (tokenTable, { eq, and }): SQL | undefined =>
and(
eq(tokenTable.accessToken, token ?? ""),
eq(tokenTable.clientId, client_id),
),
with: {
application: true,
},
});
const foundToken = await Token.fromSql(
and(
eq(Tokens.accessToken, token ?? ""),
eq(Tokens.clientId, client_id),
),
);
if (!(foundToken && token)) {
return context.json(
@ -85,7 +81,7 @@ export default (plugin: PluginType): void => {
}
// Check if the client secret is correct
if (foundToken.application?.secret !== client_secret) {
if (foundToken.data.application?.secret !== client_secret) {
return context.json(
{
error: "unauthorized_client",

View file

@ -1,7 +1,5 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { Application, db } from "@versia/kit/db";
import { eq } from "@versia/kit/drizzle";
import { Tokens } from "@versia/kit/tables";
import { afterAll, describe, expect, test } from "bun:test";
import { Application, Token } from "@versia/kit/db";
import { fakeRequest, getTestUsers } from "~/tests/utils";
const { deleteUsers, users } = await getTestUsers(1);
@ -13,27 +11,22 @@ const application = await Application.insert({
secret: "test-secret",
name: "Test Application",
});
beforeAll(async () => {
await db.insert(Tokens).values({
code: "test-code",
redirectUri: application.data.redirectUri,
clientId: application.data.clientId,
accessToken: "test-access-token",
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
createdAt: new Date().toISOString(),
tokenType: "Bearer",
scope: application.data.scopes,
userId: users[0].id,
});
const token = await Token.insert({
code: "test-code",
redirectUri: application.data.redirectUri,
clientId: application.data.clientId,
accessToken: "test-access-token",
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
createdAt: new Date().toISOString(),
tokenType: "Bearer",
scope: application.data.scopes,
userId: users[0].id,
});
afterAll(async () => {
await deleteUsers();
await application.delete();
await db
.delete(Tokens)
.where(eq(Tokens.clientId, application.data.clientId));
await token.delete();
});
describe("/oauth/token", () => {

View file

@ -1,7 +1,7 @@
import { jsonOrForm } from "@/api";
import { createRoute, z } from "@hono/zod-openapi";
import { Application, db } from "@versia/kit/db";
import { type SQL, eq } from "@versia/kit/drizzle";
import { Application, Token } from "@versia/kit/db";
import { and, eq } from "@versia/kit/drizzle";
import { Tokens } from "@versia/kit/tables";
import type { PluginType } from "../../index.ts";
@ -154,17 +154,13 @@ export default (plugin: PluginType): void => {
);
}
const token = await db.query.Tokens.findFirst({
where: (token, { eq, and }): SQL | undefined =>
and(
eq(token.code, code),
eq(
token.redirectUri,
decodeURI(redirect_uri),
),
eq(token.clientId, client_id),
),
});
const token = await Token.fromSql(
and(
eq(Tokens.code, code),
eq(Tokens.redirectUri, decodeURI(redirect_uri)),
eq(Tokens.clientId, client_id),
),
);
if (!token) {
return context.json(
@ -177,28 +173,22 @@ export default (plugin: PluginType): void => {
}
// Invalidate the code
await db
.update(Tokens)
.set({ code: null })
.where(eq(Tokens.id, token.id));
await token.update({ code: null });
return context.json(
{
access_token: token.accessToken,
token_type: "Bearer",
expires_in: token.expiresAt
...token.toApi(),
expires_in: token.data.expiresAt
? Math.floor(
(new Date(token.expiresAt).getTime() -
(new Date(
token.data.expiresAt,
).getTime() -
Date.now()) /
1000,
)
: null,
id_token: token.idToken,
id_token: token.data.idToken,
refresh_token: null,
scope: token.scope,
created_at: Math.floor(
new Date(token.createdAt).getTime() / 1000,
),
},
200,
);

View file

@ -13,7 +13,7 @@ describe("/api/v1/sso/:id", () => {
const response = await fakeRequest("/api/v1/sso/unknown", {
method: "GET",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
},
});
@ -25,7 +25,7 @@ describe("/api/v1/sso/:id", () => {
const response2 = await fakeRequest("/api/v1/sso/unknown", {
method: "DELETE",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
},
});

View file

@ -12,7 +12,7 @@ describe("/api/v1/sso", () => {
const response = await fakeRequest("/api/v1/sso", {
method: "GET",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
},
});
@ -24,7 +24,7 @@ describe("/api/v1/sso", () => {
const response = await fakeRequest("/api/v1/sso", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0]?.accessToken}`,
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({