Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions community/src/api_v0/message/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,15 @@ import {
} from './service';

const adminUser = {
id: 'admin-1',
id: 'admin-1', permissions: ['event.manage', 'reaction.read'],
discordid: null,
name: 'Admin',
displayName: 'Admin',
role: 'admin' as const,
};

const normalUser = {
...adminUser,
role: 'user' as const,
permissions: [],
};

const createContext = (overrides: {
Expand Down
9 changes: 5 additions & 4 deletions community/src/api_v0/message/service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { can } from "../../../../share/permissions";
import { RouteHandler } from "@hono/zod-openapi"
import { AppContext } from "../../core/types"
import { CommunityProviderError } from "../../lib/community/error"
Expand Down Expand Up @@ -37,7 +38,7 @@ export const createMessageService: RouteHandler<typeof createMessageRoute, AppCo
const community = c.get("community");
const db = c.get("db");

if (appUser.role !== "admin") {
if (!can(appUser.permissions, "event.manage")) {
return c.json({ error: "Forbidden" }, 403);
}

Expand Down Expand Up @@ -75,7 +76,7 @@ export const createMessageService: RouteHandler<typeof createMessageRoute, AppCo
export const listMessagesService: RouteHandler<typeof listMessagesRoute, AppContext> = async (c) => {
const appUser = c.get("appUser");

if (appUser.role !== "admin") {
if (!can(appUser.permissions, "event.manage")) {
return c.json({ error: "Forbidden" }, 403);
}

Expand All @@ -90,7 +91,7 @@ export const listMessagesService: RouteHandler<typeof listMessagesRoute, AppCont
export const getMessageService: RouteHandler<typeof getMessageRoute, AppContext> = async (c) => {
const appUser = c.get("appUser");

if (appUser.role !== "admin") {
if (!can(appUser.permissions, "event.manage")) {
return c.json({ error: "Forbidden" }, 403);
}

Expand All @@ -112,7 +113,7 @@ export const getMessageReactionsService: RouteHandler<typeof getMessageReactions
const community = c.get("community");
const db = c.get("db");

if (appUser.role !== "admin") {
if (!can(appUser.permissions, "reaction.read")) {
return c.json({ error: "Forbidden" }, 403);
}

Expand Down
3 changes: 2 additions & 1 deletion community/src/api_v0/user/id/role/service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { can } from "../../../../../../share/permissions";
import { RouteHandler } from "@hono/zod-openapi";
import { AppContext } from "../../../../core/types";
import { getUserRolesByIdRoute, updateUserRolesRoute } from "./schema";
Expand All @@ -18,7 +19,7 @@ export const getUserRolesByIdService: RouteHandler<typeof getUserRolesByIdRoute,

export const updateUserRolesService: RouteHandler<typeof updateUserRolesRoute, AppContext> = async (c) => {
const user = c.get("appUser");
if (user.role !== "admin") throw new HTTPException(403);
if (!can(user.permissions, "role.manage")) throw new HTTPException(403);
const mockRole = { roleId: "r-123", roleName: "admin" };
return c.json([mockRole], 200);
};
7 changes: 4 additions & 3 deletions community/src/api_v0/user/id/service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { can } from "../../../../../share/permissions";
import { RouteHandler } from "@hono/zod-openapi";
import { AppContext } from "../../../core/types";
import { getUserByIdRoute, updateUserByIdRoute, deleteUserByIdRoute } from "./schema";
Expand All @@ -10,7 +11,7 @@ export const getUserByIdService: RouteHandler<typeof getUserByIdRoute, AppContex
if (!userId) {
return c.json({ message: "User ID is required" }, 401);
}
if (appUser.role !== "admin") {
if (!can(appUser.permissions, "member.read_private")) {
return c.json({ message: "Forbidden" }, 403);
}
const db = c.get("db");
Expand All @@ -33,7 +34,7 @@ export const updateUserByIdService: RouteHandler<typeof updateUserByIdRoute, App
if (!userId) {
return c.json({ message: "User ID is required" }, 401);
}
if (appUser.role !== "admin") {
if (!can(appUser.permissions, "member.edit")) {
return c.json({ message: "Forbidden" }, 403);
}
const db = c.get("db");
Expand All @@ -60,7 +61,7 @@ export const deleteUserByIdService: RouteHandler<typeof deleteUserByIdRoute, App
if (!userId) {
return c.body(null, 204);
}
if (appUser.role !== "admin") {
if (!can(appUser.permissions, "member.edit")) {
return c.json({ message: "Forbidden" }, 403);
}
const db = c.get("db");
Expand Down
1 change: 0 additions & 1 deletion community/src/api_v0/user/me/identity/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ const appUser = {
id: 'user-1',
name: 'Test User',
memberId: null,
role: 'user' as const,
};
const linkedAccount = {
id: 'account-row-1',
Expand Down
4 changes: 2 additions & 2 deletions community/src/api_v0/user/me/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export const getUserMeService: RouteHandler<typeof getUserMeRoute, AppContext> =
return c.json({ error: "User not found in database" }, 404);
}

return c.json({ ...dbUser, memberId: appUser.memberId, role: appUser.role }, 200);
return c.json({ ...dbUser, memberId: appUser.memberId, permissions: [...appUser.permissions] }, 200);
};

export const updateUserMeService: RouteHandler<typeof updateUserMeRoute, AppContext> = async (c) => {
Expand All @@ -59,5 +59,5 @@ export const updateUserMeService: RouteHandler<typeof updateUserMeRoute, AppCont
return c.json({ error: "User not found in database" }, 404);
}

return c.json({ ...updatedUser, memberId: appUser.memberId, role: appUser.role }, 200);
return c.json({ ...updatedUser, memberId: appUser.memberId, permissions: [...appUser.permissions] }, 200);
};
2 changes: 1 addition & 1 deletion community/src/api_v0/user/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const CurrentUserSchema = z.object({
emailVerified: z.boolean(),
image: z.string().nullable(),
memberId: z.string().uuid().nullable(),
role: z.enum(["user", "admin"]),
permissions: z.array(z.string()),
}).openapi("CurrentUser")

// Better Auth owns identity, account linkage, member linkage, and application
Expand Down
5 changes: 3 additions & 2 deletions community/src/api_v0/user/service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { can } from "../../../../share/permissions";
import { RouteHandler } from "@hono/zod-openapi";
import { AppContext } from "../../core/types";
import { createUserRoute, listUsersRoute } from "./schema";
Expand All @@ -9,7 +10,7 @@ export const createUserService: RouteHandler<typeof createUserRoute, AppContext>
const body = c.req.valid("json");
const now = new Date();

if (appUser.role !== "admin") {
if (!can(appUser.permissions, "member.edit")) {
return c.json({ message: "Forbidden" }, 403);
}

Expand All @@ -30,7 +31,7 @@ export const listUsersService: RouteHandler<typeof listUsersRoute, AppContext> =
const db = c.get("db");
const appUser = c.get("appUser");

if (appUser.role !== "admin") {
if (!can(appUser.permissions, "member.read_private")) {
return c.json({ message: "Forbidden" }, 403);
}

Expand Down
13 changes: 7 additions & 6 deletions community/src/auth/better-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,11 @@ test("Better Auth signs members in with Discord as the only provider", async ()
});

test("post-login routing only sends active members to their profile", () => {
assert.equal(getPostLoginRedirectPath("admin", null), "/");
assert.equal(getPostLoginRedirectPath("user", "active"), "/me");
assert.equal(getPostLoginRedirectPath("user", "pending"), "/join");
assert.equal(getPostLoginRedirectPath("user", "rejected"), "/join");
assert.equal(getPostLoginRedirectPath("user", "withdrawn"), "/join");
assert.equal(getPostLoginRedirectPath("user", null), "/join");
assert.equal(getPostLoginRedirectPath(["event.manage"], null), "/");
assert.equal(getPostLoginRedirectPath(["member.read_private"], "active"), "/admin/members");
assert.equal(getPostLoginRedirectPath([], "active"), "/me");
assert.equal(getPostLoginRedirectPath([], "pending"), "/join");
assert.equal(getPostLoginRedirectPath([], "rejected"), "/join");
assert.equal(getPostLoginRedirectPath([], "withdrawn"), "/join");
assert.equal(getPostLoginRedirectPath([], null), "/join");
});
62 changes: 31 additions & 31 deletions community/src/auth/better-auth.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { can } from "../../../share/permissions";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import * as schema from "../../../share/drizzle/schema";
Expand All @@ -8,6 +9,7 @@ import { sign } from "hono/jwt";
import { setCookie } from "hono/cookie";
import { eq } from "drizzle-orm";
import { getAuthDatabase, type AppDatabase } from "../core/db";
import { findPermissions } from "../core/permissions";

export const getAuth = (c: Context<AppContext>, database?: AppDatabase) => {
const db = database ?? getAuthDatabase(c);
Expand All @@ -21,16 +23,15 @@ export const getAuth = (c: Context<AppContext>, database?: AppDatabase) => {
trustedOrigins: [
c.env.FRONTEND_URL || "http://localhost:3000"
],
// No additionalFields: membership and role belong to the domain and live
// in public.app_accounts, so Better Auth owns its tables outright and
// they can be moved to their own database.
// additionalFields は使わない。部員であることや権限はドメインの情報で、
// public.app_accounts などに置く。Better Auth のテーブルには認証の情報だけを持たせ、
// 別のデータベースへ移せるようにしておく。
databaseHooks: {
user: {
create: {
// A subject only becomes usable once the domain has its own
// record of it. Creating it here keeps the write in the
// boundary layer instead of a trigger that would make the
// authentication schema depend on the domain again.
// ログインした人は、ドメイン側に自分の行(app_accounts)ができて初めて使える。
// トリガーで作ると認証のスキーマがドメインに依存してしまうので、
// 境目にあたるここで作る。
after: async (createdUser) => {
await db
.insert(schema.appAccounts)
Expand All @@ -51,13 +52,13 @@ export const getAuth = (c: Context<AppContext>, database?: AppDatabase) => {
},
},
socialProviders: {
// Discord is the only identity provider. The same account both signs
// the member in and supplies the guild membership evidence the join
// flow verifies, so there is no second provider to link or reconcile.
// ログイン手段は Discord だけ。同じアカウントで、ログインと、
// 入部時に確かめるサーバー参加の証明の両方をまかなう。
// そのため、別のログイン手段とアカウントを結び付ける必要がない。
discord: {
clientId: c.env.DISCORD_CLIENT_ID,
clientSecret: c.env.DISCORD_CLIENT_SECRET,
// Appended to Better Auth's default identify+email scopes.
// Better Auth の既定(identify と email)に追加で求める範囲。
scope: ["guilds"],
}
},
Expand All @@ -67,12 +68,18 @@ export const getAuth = (c: Context<AppContext>, database?: AppDatabase) => {
});
};

// ログイン直後に移動させるページを、権限と在籍状態から決める。上から順に判定する。
export const getPostLoginRedirectPath = (
role: 'admin' | 'user',
permissions: readonly string[],
memberStatus: string | null | undefined,
) => role === 'admin' ? '/' : memberStatus === 'active' ? '/me' : '/join';
) => {
if (can(permissions, "event.manage")) return "/";
if (can(permissions, "member.read_private")) return "/admin/members";
if (memberStatus === "active") return "/me";
return "/join";
};

// JWT Endpoint Route definition
// JWT を発行するエンドポイントの定義
export const getJwtRoute = createRoute({
method: "get",
path: "/jwt",
Expand All @@ -94,7 +101,7 @@ export const getJwtRoute = createRoute({
},
});

// JWT Endpoint Handler
// JWT を発行するエンドポイントの処理
export const getJwtHandler = async (c: Context<AppContext>) => {
const auth = getAuth(c);
const session = await auth.api.getSession({
Expand All @@ -109,24 +116,20 @@ export const getJwtHandler = async (c: Context<AppContext>) => {
}

try {
// Better Auth proved who the caller is; the domain decides what the JWT
// may claim, so role and membership are read from app_accounts.
// 誰がログインしたかは Better Auth が確かめた。何ができるかは JWT に入れず、
// リクエストのたびにデータベースが決める。
const authDb = getAuthDatabase(c);

// The create hook normally provisions this row. Repairing it here costs
// one statement per sign-in and keeps a subject that slipped through —
// a hook that failed, a row seeded outside the flow — from being locked
// out permanently with no path back except editing the database.
// この行はふつう、ユーザー作成時のフックで作られる。フックが失敗したなどで
// 行がないと、データベースを直接直す以外に戻る手段がなくなる。
// ログインのたびに 1 回書き込むだけで防げるので、ここでも作っておく。
await authDb
.insert(schema.appAccounts)
.values({ userId: session.user.id })
.onConflictDoNothing();

const [currentUser] = await authDb
.select({
role: schema.appAccounts.role,
memberId: schema.appAccounts.memberId,
})
.select({ memberId: schema.appAccounts.memberId })
.from(schema.appAccounts)
.where(eq(schema.appAccounts.userId, session.user.id))
.limit(1);
Expand All @@ -136,12 +139,9 @@ export const getJwtHandler = async (c: Context<AppContext>) => {
return c.redirect(`${frontendUrl}/login?error=user_not_found`);
}

const role = currentUser.role === "admin" ? "admin" : "user";
const db = c.get("db");
db.setIdentity({
userId: session.user.id,
memberId: currentUser.memberId,
role,
});

const memberId = currentUser.memberId;
Expand All @@ -156,7 +156,6 @@ export const getJwtHandler = async (c: Context<AppContext>) => {
id: session.user.id,
sid: session.session.id,
name: session.user.name,
role,
exp: Math.min(
Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 7,
Math.floor(new Date(session.session.expiresAt).getTime() / 1000),
Expand All @@ -175,8 +174,9 @@ export const getJwtHandler = async (c: Context<AppContext>) => {
domain: c.env.COOKIE_DOMAIN || undefined,
});

const redirectPath = getPostLoginRedirectPath(role, member?.memberStatus);
console.log(`[JWT Endpoint] Successfully issued JWT for user ${session.user.id} with role ${payload.role}`);
const permissions = await findPermissions(authDb, session.user.id);
const redirectPath = getPostLoginRedirectPath(permissions, member?.memberStatus);
console.log(`[JWT Endpoint] Successfully issued JWT for user ${session.user.id}`);
return c.redirect(`${frontendUrl}${redirectPath}`);
} catch (error) {
console.error("[JWT Endpoint] Error generating JWT:", error);
Expand Down
23 changes: 12 additions & 11 deletions community/src/core/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,24 @@ test('auth middleware reloads the application user and does not turn downstream
let capturedUser: appUser | undefined;
let capturedIdentity: unknown;

// The middleware asks the authentication store who the caller is, then asks
// the domain what that subject may do. Two selects, never a join across them.
// ミドルウェアは、認証ストアに「誰か」を、ドメインに「どの部員か」と「何ができるか」を聞く。
// 認証ストアとドメインをまたいで結合はしない。
let selectCall = 0;
const transaction = {
select: () => {
selectCall += 1;
const rows = selectCall === 1
? [{ id: 'user-1', name: 'Test User' }]
: [{ memberId: null, role: 'user', permissionKey: null }];
// The domain lookup left-joins the grants and groups by the account, so
// the stub has to offer the same shape as the builder it stands in for.
: [{ memberId: null }];
const limit = async () => rows;
// The domain lookup left-joins the grants; the subject lookup does not.
const where = () => Object.assign(limit(), { limit });
const leftJoin = () => ({ leftJoin, where });
return { from: () => ({ innerJoin: () => ({ where }), leftJoin, where }) };
},
// 権限の検索(findPermissions)。部員の行がないので、権限は 1 つも返らない。
selectDistinct: () => ({
from: () => ({ innerJoin: () => ({ innerJoin: () => ({ where: async () => [] }) }) }),
}),
};
const db = {
transaction: (operation: (tx: unknown) => Promise<unknown>) => operation(transaction),
Expand Down Expand Up @@ -65,12 +66,9 @@ test('auth middleware reloads the application user and does not turn downstream
memberId: null,
// No member row, so no role, so nothing granted.
permissions: [],
role: 'user',
});
assert.deepEqual(capturedIdentity, {
userId: 'user-1',
memberId: null,
role: 'user',
});
});

Expand Down Expand Up @@ -136,13 +134,16 @@ test('the development bypass still applies to a local request', async () => {
selectCall += 1;
const rows = selectCall === 1
? [{ id: 'user-1', name: 'Local Dev' }]
: [{ memberId: null, role: 'user', permissionKey: null }];
: [{ memberId: null }];
const limit = async () => rows;
// The domain lookup left-joins the grants; the subject lookup does not.
const where = () => Object.assign(limit(), { limit });
const leftJoin = () => ({ leftJoin, where });
return { from: () => ({ innerJoin: () => ({ where }), leftJoin, where }) };
},
// 権限の検索(findPermissions)。部員の行がないので、権限は 1 つも返らない。
selectDistinct: () => ({
from: () => ({ innerJoin: () => ({ innerJoin: () => ({ where: async () => [] }) }) }),
}),
};
const db = {
transaction: (operation: (tx: unknown) => Promise<unknown>) => operation(transaction),
Expand Down
Loading
Loading