refactor(auth): factory-style use cases + controllers + real Payload impls
- Use cases (sign-in, sign-up, sign-out) → factory functions with I*UseCase aliases - Controllers → factory functions with I*Controller aliases - DI symbols + module updated with .toDynamicValue() bindings for factories - New: real UsersRepository (Payload-backed, SanitizedConfig, contract-tested) - New: real AuthenticationService (node:crypto hashing/UUIDs; createSession/ validateSession/invalidateSession deferred — see refactor log §7) - bindProductionAuth swaps both mocks for real impls (was a no-op before) - Tests refactored to construct mocks and inject directly (no container rebinding) - Feature test constructs full chain via direct factory injection Refactor log: §2, §4.1, §4.2, §5.1, §5.2, §6.1, §7 Spec: §6.1, §7 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -87,6 +87,13 @@ Entity model moves (git mv — history preserved):
|
||||
|
||||
## 2. Files added (with purpose)
|
||||
|
||||
### Task 4: Real implementations + tests
|
||||
|
||||
- `packages/auth/src/infrastructure/repositories/users.repository.ts` — real Payload-backed `UsersRepository` (implements `IUsersRepository` via `getPayload`)
|
||||
- `packages/auth/src/infrastructure/repositories/users.repository.test.ts` — contract suite backed by an in-memory Payload stub (mirrors `articles.repository.test.ts` pattern)
|
||||
- `packages/auth/src/infrastructure/services/authentication.service.ts` — real `AuthenticationService` using `node:crypto` for hashing/UUIDs; session methods deferred (see §7)
|
||||
- `packages/auth/src/infrastructure/services/authentication.service.test.ts` — tests for `generateUserId`, `hashPassword`/`verifyPassword` round-trip, and deferred-method error assertions
|
||||
|
||||
### Task 2: Entities split — new error files
|
||||
|
||||
- `packages/auth/src/entities/errors/auth.ts` — AuthenticationError, UnauthenticatedError, UnauthorizedError (split from errors.ts)
|
||||
@@ -110,10 +117,22 @@ Entity model moves (git mv — history preserved):
|
||||
## 4. Pattern changes (code-level)
|
||||
|
||||
### 4.1 Use cases — factory function pattern
|
||||
(populated when a use case is migrated)
|
||||
|
||||
Applied to all 3 auth use cases (`sign-in`, `sign-up`, `sign-out`):
|
||||
|
||||
- Use cases are now factory functions: `(deps) => async (input) => result`
|
||||
- Each file exports `export type I*UseCase = ReturnType<typeof *UseCase>` for DI typing
|
||||
- Use cases NO LONGER call `authContainer.get()` inside their bodies — all dependencies are passed as factory arguments
|
||||
- Tests construct mocks directly: `const useCase = signInUseCase(mockUsers, mockAuth); await useCase(input);`
|
||||
|
||||
### 4.2 Controllers — one per use case
|
||||
(populated when controllers are split)
|
||||
|
||||
Applied to all 3 auth controllers (`sign-in`, `sign-up`, `sign-out`):
|
||||
|
||||
- Controllers were already split (one file per use case) — Task 4 refactors them to factory functions
|
||||
- Factory pattern: `(useCase: I*UseCase) => async (input) => result`
|
||||
- Each exports `export type I*Controller = ReturnType<typeof *Controller>`
|
||||
- Validation (Zod `safeParse`) stays inside the controller factory; throws `InputParseError` on failure
|
||||
|
||||
### 4.3 Entities split — models/ + errors/ subdirs
|
||||
|
||||
@@ -129,19 +148,56 @@ Pattern now in place across auth, blog, marketing-pages, navigation (media skipp
|
||||
## 5. DI changes
|
||||
|
||||
### 5.1 Inversify `.toDynamicValue` bindings
|
||||
(populated when DI modules are updated)
|
||||
|
||||
Applied to `packages/auth/src/di/module.ts`:
|
||||
|
||||
- `AUTH_SYMBOLS` expanded with 6 new keys: `ISignInUseCase`, `ISignUpUseCase`, `ISignOutUseCase`, `ISignInController`, `ISignUpController`, `ISignOutController`
|
||||
- Use cases bound with `.toDynamicValue((ctx) => factoryFn(ctx.container.get(...)))` — dependencies resolved from the container at call time
|
||||
- Controllers bound identically, taking the corresponding use case symbol from the container
|
||||
- Repository and service bindings remain `.to(Mock*)` as the default
|
||||
|
||||
### 5.2 Mock siblings registered as default bindings
|
||||
(populated when modules are updated)
|
||||
|
||||
- `MockUsersRepository` and `MockAuthenticationService` remain the default bindings in `AuthModule`
|
||||
- `bindProductionAuth(config: SanitizedConfig)` now swaps both to `UsersRepository` and `AuthenticationService` (real Payload-backed implementations)
|
||||
- Previously `bindProductionAuth` was a no-op; it now rebinds both symbols using `.toConstantValue(new RealImpl(config))`
|
||||
|
||||
## 6. Test refactor patterns
|
||||
|
||||
### 6.1 Direct injection (no container rebinding)
|
||||
(populated when tests are migrated)
|
||||
|
||||
Applied to all auth use-case tests, controller tests, the router test, and the feature integration test:
|
||||
|
||||
- **Before:** `beforeEach` unbinds and rebinds symbols on `authContainer`
|
||||
- **After:** each test (or `it`) constructs its own `MockUsersRepository` + `MockAuthenticationService`, then calls the factory directly:
|
||||
```typescript
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const useCase = signInUseCase(users, auth);
|
||||
const result = await useCase({ username: "alice", password: "testpassword" });
|
||||
```
|
||||
- No `authContainer.unbind()` / `authContainer.bind()` calls remain in test files
|
||||
- The `authRouter` test and `container.test.ts` still reference `authContainer` (unavoidable — the router resolves controllers via the container, and the container test verifies the DI wiring), but they use the default bindings without rebinding
|
||||
- The feature test (`tests/sign-in-flow.feature.test.ts`) fully constructs the chain via direct injection rather than calling `authRouter.createCaller({})`
|
||||
|
||||
## 7. Open issues / deferred decisions
|
||||
|
||||
(populated as encountered)
|
||||
### Task 4: AuthenticationService — deferred session methods
|
||||
|
||||
Three methods on `AuthenticationService` (in `packages/auth/src/infrastructure/services/authentication.service.ts`) are deferred because Payload's auth API does not map cleanly to the generic `IAuthenticationService` session interface:
|
||||
|
||||
| Method | Why deferred |
|
||||
|---|---|
|
||||
| `createSession(user)` | Payload creates sessions via its REST `/api/users/login` endpoint and returns a JWT token. Mapping this to a generic `{ session: Session; cookie: Cookie }` shape requires knowing Payload's JWT payload structure, the session expiry, and the exact cookie name/attributes Payload uses — which vary by collection config. |
|
||||
| `validateSession(sessionId)` | Payload validates sessions by verifying a JWT. This requires calling `payload.auth()` or `payload.find()` with the token, and is tightly coupled to Payload's internal token format. |
|
||||
| `invalidateSession(sessionId)` | Payload's default auth strategy is stateless JWT — there is no server-side session store to clear. Invalidation is done client-side by expiring the cookie. A proper implementation would require either a token blocklist or switching to Payload's API keys feature. |
|
||||
|
||||
All three throw `new NotImplementedError("methodName")` with a clear message (`"NotImplemented: AuthenticationService.<method> — see refactor log §7"`). The mock (`MockAuthenticationService`) handles all test paths.
|
||||
|
||||
**TODO:** Revisit once the session cookie strategy is finalized. Consider:
|
||||
- Using Payload's local API `payload.auth()` for `validateSession`
|
||||
- Implementing a Redis-backed token blocklist for `invalidateSession`
|
||||
- Or replacing the `IAuthenticationService` interface with Payload-specific abstractions
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,52 +1,47 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { authContainer } from "@/di/container";
|
||||
import { AUTH_SYMBOLS } from "@/di/symbols";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { signInUseCase } from "@/application/use-cases/sign-in.use-case";
|
||||
import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock";
|
||||
import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock";
|
||||
import type { IUsersRepository } from "@/application/repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "@/application/services/authentication.service.interface";
|
||||
import { AuthenticationError } from "@/entities/errors/auth";
|
||||
import { signInUseCase } from "./sign-in.use-case";
|
||||
import { userFactory } from "@/__factories__/user.factory";
|
||||
|
||||
describe("signInUseCase", () => {
|
||||
let usersRepo: MockUsersRepository;
|
||||
let authService: MockAuthenticationService;
|
||||
|
||||
beforeEach(() => {
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IUsersRepository);
|
||||
}
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService);
|
||||
}
|
||||
usersRepo = new MockUsersRepository();
|
||||
authService = new MockAuthenticationService(usersRepo);
|
||||
authContainer
|
||||
.bind<IUsersRepository>(AUTH_SYMBOLS.IUsersRepository)
|
||||
.toConstantValue(usersRepo);
|
||||
authContainer
|
||||
.bind<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService)
|
||||
.toConstantValue(authService);
|
||||
});
|
||||
|
||||
it("returns a session + cookie on valid credentials", async () => {
|
||||
const result = await signInUseCase({
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const seedUser = userFactory.build({
|
||||
username: "alice",
|
||||
password: "password_alice",
|
||||
passwordHash: "hashed_testpassword",
|
||||
});
|
||||
expect(result.session.userId).toBe("1");
|
||||
await users.createUser(seedUser);
|
||||
|
||||
const useCase = signInUseCase(users, auth);
|
||||
const result = await useCase({ username: "alice", password: "testpassword" });
|
||||
|
||||
expect(result.session.userId).toBe(seedUser.id);
|
||||
expect(result.cookie.name).toBe("session");
|
||||
});
|
||||
|
||||
it("throws AuthenticationError when user does not exist", async () => {
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const useCase = signInUseCase(users, auth);
|
||||
|
||||
await expect(
|
||||
signInUseCase({ username: "ghost", password: "anything" }),
|
||||
useCase({ username: "ghost", password: "anything" }),
|
||||
).rejects.toBeInstanceOf(AuthenticationError);
|
||||
});
|
||||
|
||||
it("throws AuthenticationError on wrong password", async () => {
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
await users.createUser(
|
||||
userFactory.build({ username: "alice", passwordHash: "hashed_correctpassword" }),
|
||||
);
|
||||
|
||||
const useCase = signInUseCase(users, auth);
|
||||
await expect(
|
||||
signInUseCase({ username: "alice", password: "wrong" }),
|
||||
useCase({ username: "alice", password: "wrong" }),
|
||||
).rejects.toBeInstanceOf(AuthenticationError);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,28 +1,26 @@
|
||||
import { AuthenticationError } from "../../entities/errors/auth";
|
||||
import type { Cookie } from "../../entities/models/cookie";
|
||||
import type { Session } from "../../entities/models/session";
|
||||
import { authContainer } from "../../di/container";
|
||||
import { AUTH_SYMBOLS } from "../../di/symbols";
|
||||
import type { IUsersRepository } from "../repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "../services/authentication.service.interface";
|
||||
|
||||
export async function signInUseCase(input: {
|
||||
export type ISignInUseCase = ReturnType<typeof signInUseCase>;
|
||||
|
||||
export const signInUseCase =
|
||||
(
|
||||
usersRepository: IUsersRepository,
|
||||
authenticationService: IAuthenticationService,
|
||||
) =>
|
||||
async (input: {
|
||||
username: string;
|
||||
password: string;
|
||||
}): Promise<{ session: Session; cookie: Cookie }> {
|
||||
const usersRepository = authContainer.get<IUsersRepository>(
|
||||
AUTH_SYMBOLS.IUsersRepository,
|
||||
);
|
||||
const authService = authContainer.get<IAuthenticationService>(
|
||||
AUTH_SYMBOLS.IAuthenticationService,
|
||||
);
|
||||
|
||||
}): Promise<{ session: Session; cookie: Cookie }> => {
|
||||
const existingUser = await usersRepository.getUserByUsername(input.username);
|
||||
if (!existingUser) {
|
||||
throw new AuthenticationError("User does not exist");
|
||||
}
|
||||
|
||||
const validPassword = await authService.verifyPassword(
|
||||
const validPassword = await authenticationService.verifyPassword(
|
||||
existingUser.passwordHash,
|
||||
input.password,
|
||||
);
|
||||
@@ -30,5 +28,5 @@ export async function signInUseCase(input: {
|
||||
throw new AuthenticationError("Incorrect username or password");
|
||||
}
|
||||
|
||||
return await authService.createSession(existingUser);
|
||||
}
|
||||
return await authenticationService.createSession(existingUser);
|
||||
};
|
||||
|
||||
@@ -1,35 +1,15 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { authContainer } from "@/di/container";
|
||||
import { AUTH_SYMBOLS } from "@/di/symbols";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { signOutUseCase } from "@/application/use-cases/sign-out.use-case";
|
||||
import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock";
|
||||
import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock";
|
||||
import type { IUsersRepository } from "@/application/repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "@/application/services/authentication.service.interface";
|
||||
import { signOutUseCase } from "./sign-out.use-case";
|
||||
|
||||
describe("signOutUseCase", () => {
|
||||
let usersRepo: MockUsersRepository;
|
||||
let authService: MockAuthenticationService;
|
||||
|
||||
beforeEach(() => {
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IUsersRepository);
|
||||
}
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService);
|
||||
}
|
||||
usersRepo = new MockUsersRepository();
|
||||
authService = new MockAuthenticationService(usersRepo);
|
||||
authContainer
|
||||
.bind<IUsersRepository>(AUTH_SYMBOLS.IUsersRepository)
|
||||
.toConstantValue(usersRepo);
|
||||
authContainer
|
||||
.bind<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService)
|
||||
.toConstantValue(authService);
|
||||
});
|
||||
|
||||
it("returns a blank cookie", async () => {
|
||||
const result = await signOutUseCase("session_1");
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const useCase = signOutUseCase(auth);
|
||||
|
||||
const result = await useCase("session_1");
|
||||
expect(result.blankCookie.name).toBe("session");
|
||||
expect(result.blankCookie.value).toBe("");
|
||||
});
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import type { Cookie } from "../../entities/models/cookie";
|
||||
import { authContainer } from "../../di/container";
|
||||
import { AUTH_SYMBOLS } from "../../di/symbols";
|
||||
import type { IAuthenticationService } from "../services/authentication.service.interface";
|
||||
|
||||
export async function signOutUseCase(
|
||||
sessionId: string,
|
||||
): Promise<{ blankCookie: Cookie }> {
|
||||
const authService = authContainer.get<IAuthenticationService>(
|
||||
AUTH_SYMBOLS.IAuthenticationService,
|
||||
);
|
||||
return await authService.invalidateSession(sessionId);
|
||||
}
|
||||
export type ISignOutUseCase = ReturnType<typeof signOutUseCase>;
|
||||
|
||||
export const signOutUseCase =
|
||||
(authenticationService: IAuthenticationService) =>
|
||||
async (sessionId: string): Promise<{ blankCookie: Cookie }> => {
|
||||
return await authenticationService.invalidateSession(sessionId);
|
||||
};
|
||||
|
||||
@@ -1,47 +1,34 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { authContainer } from "@/di/container";
|
||||
import { AUTH_SYMBOLS } from "@/di/symbols";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { signUpUseCase } from "@/application/use-cases/sign-up.use-case";
|
||||
import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock";
|
||||
import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock";
|
||||
import type { IUsersRepository } from "@/application/repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "@/application/services/authentication.service.interface";
|
||||
import { AuthenticationError } from "@/entities/errors/auth";
|
||||
import { signUpUseCase } from "./sign-up.use-case";
|
||||
import { userFactory } from "@/__factories__/user.factory";
|
||||
|
||||
describe("signUpUseCase", () => {
|
||||
let usersRepo: MockUsersRepository;
|
||||
let authService: MockAuthenticationService;
|
||||
|
||||
beforeEach(() => {
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IUsersRepository);
|
||||
}
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService);
|
||||
}
|
||||
usersRepo = new MockUsersRepository();
|
||||
authService = new MockAuthenticationService(usersRepo);
|
||||
authContainer
|
||||
.bind<IUsersRepository>(AUTH_SYMBOLS.IUsersRepository)
|
||||
.toConstantValue(usersRepo);
|
||||
authContainer
|
||||
.bind<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService)
|
||||
.toConstantValue(authService);
|
||||
});
|
||||
|
||||
it("creates a new user and returns session + cookie + user", async () => {
|
||||
const result = await signUpUseCase({
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const useCase = signUpUseCase(users, auth);
|
||||
|
||||
const result = await useCase({
|
||||
username: "carol",
|
||||
password: "secret_password",
|
||||
});
|
||||
|
||||
expect(result.user.username).toBe("carol");
|
||||
expect(result.session.userId).toBe(result.user.id);
|
||||
expect(result.cookie.name).toBe("session");
|
||||
});
|
||||
|
||||
it("throws AuthenticationError when username taken", async () => {
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
await users.createUser(userFactory.build({ username: "alice" }));
|
||||
|
||||
const useCase = signUpUseCase(users, auth);
|
||||
await expect(
|
||||
signUpUseCase({ username: "alice", password: "secret_password" }),
|
||||
useCase({ username: "alice", password: "secret_password" }),
|
||||
).rejects.toBeInstanceOf(AuthenticationError);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,33 +2,31 @@ import { AuthenticationError } from "../../entities/errors/auth";
|
||||
import type { Cookie } from "../../entities/models/cookie";
|
||||
import type { Session } from "../../entities/models/session";
|
||||
import type { User } from "../../entities/models/user";
|
||||
import { authContainer } from "../../di/container";
|
||||
import { AUTH_SYMBOLS } from "../../di/symbols";
|
||||
import type { IUsersRepository } from "../repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "../services/authentication.service.interface";
|
||||
|
||||
export async function signUpUseCase(input: {
|
||||
export type ISignUpUseCase = ReturnType<typeof signUpUseCase>;
|
||||
|
||||
export const signUpUseCase =
|
||||
(
|
||||
usersRepository: IUsersRepository,
|
||||
authenticationService: IAuthenticationService,
|
||||
) =>
|
||||
async (input: {
|
||||
username: string;
|
||||
password: string;
|
||||
}): Promise<{
|
||||
session: Session;
|
||||
cookie: Cookie;
|
||||
user: Pick<User, "id" | "username">;
|
||||
}> {
|
||||
const usersRepository = authContainer.get<IUsersRepository>(
|
||||
AUTH_SYMBOLS.IUsersRepository,
|
||||
);
|
||||
const authService = authContainer.get<IAuthenticationService>(
|
||||
AUTH_SYMBOLS.IAuthenticationService,
|
||||
);
|
||||
|
||||
}> => {
|
||||
const existingUser = await usersRepository.getUserByUsername(input.username);
|
||||
if (existingUser) {
|
||||
throw new AuthenticationError("Username taken");
|
||||
}
|
||||
|
||||
const passwordHash = await authService.hashPassword(input.password);
|
||||
const userId = authService.generateUserId();
|
||||
const passwordHash = await authenticationService.hashPassword(input.password);
|
||||
const userId = authenticationService.generateUserId();
|
||||
|
||||
const newUser = await usersRepository.createUser({
|
||||
id: userId,
|
||||
@@ -36,11 +34,11 @@ export async function signUpUseCase(input: {
|
||||
passwordHash,
|
||||
});
|
||||
|
||||
const { cookie, session } = await authService.createSession(newUser);
|
||||
const { cookie, session } = await authenticationService.createSession(newUser);
|
||||
|
||||
return {
|
||||
cookie,
|
||||
session,
|
||||
user: { id: newUser.id, username: newUser.username },
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,13 +1,28 @@
|
||||
import type { SanitizedConfig as _SanitizedConfig } from "payload";
|
||||
import type { SanitizedConfig } from "payload";
|
||||
import { authContainer } from "./container";
|
||||
import { AUTH_SYMBOLS } from "./symbols";
|
||||
import { UsersRepository } from "../infrastructure/repositories/users.repository";
|
||||
import { AuthenticationService } from "../infrastructure/services/authentication.service";
|
||||
import type { IUsersRepository } from "../application/repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "../application/services/authentication.service.interface";
|
||||
|
||||
// Auth currently uses Mock repositories even in production: see Plan 3
|
||||
// decisions. This helper exists for API symmetry with other features and
|
||||
// for forward-compatibility if a Payload-backed users repo is added later.
|
||||
//
|
||||
// Until then it's a no-op that intentionally accepts (and ignores) the
|
||||
// SanitizedConfig argument so app-boot code can call it uniformly.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
export function bindProductionAuth(_config: _SanitizedConfig): void {
|
||||
// Default mock bindings from `module.ts` already loaded by container.ts;
|
||||
// nothing to swap.
|
||||
let bound = false;
|
||||
|
||||
export function bindProductionAuth(config: SanitizedConfig): void {
|
||||
if (bound) return;
|
||||
bound = true;
|
||||
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IUsersRepository);
|
||||
}
|
||||
authContainer
|
||||
.bind<IUsersRepository>(AUTH_SYMBOLS.IUsersRepository)
|
||||
.toConstantValue(new UsersRepository(config));
|
||||
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService);
|
||||
}
|
||||
authContainer
|
||||
.bind<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService)
|
||||
.toConstantValue(new AuthenticationService(config));
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import { MockUsersRepository } from "@/infrastructure/repositories/users.reposit
|
||||
import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock";
|
||||
import type { IUsersRepository } from "@/application/repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "@/application/services/authentication.service.interface";
|
||||
import type { ISignInUseCase } from "@/application/use-cases/sign-in.use-case";
|
||||
import type { ISignInController } from "@/interface-adapters/controllers/sign-in.controller";
|
||||
import { userFactory } from "@/__factories__/user.factory";
|
||||
|
||||
describe("authContainer", () => {
|
||||
@@ -36,14 +38,22 @@ describe("authContainer", () => {
|
||||
const service = authContainer.get<IAuthenticationService>(
|
||||
AUTH_SYMBOLS.IAuthenticationService,
|
||||
);
|
||||
// The service should be able to validate against the seeded users
|
||||
const user = userFactory.build({ id: "1", username: "alice", passwordHash: "hashed_password_alice" });
|
||||
const { session, cookie } = await service.createSession(user);
|
||||
expect(session.userId).toBe("1");
|
||||
expect(cookie.value).toBe(session.id);
|
||||
|
||||
// After session creation, validateSession should resolve user via the repo
|
||||
const validated = await service.validateSession(session.id);
|
||||
expect(validated.user.username).toBe("alice");
|
||||
});
|
||||
|
||||
it("resolves ISignInUseCase via toDynamicValue binding", () => {
|
||||
const useCase = authContainer.get<ISignInUseCase>(AUTH_SYMBOLS.ISignInUseCase);
|
||||
expect(typeof useCase).toBe("function");
|
||||
});
|
||||
|
||||
it("resolves ISignInController via toDynamicValue binding", () => {
|
||||
const controller = authContainer.get<ISignInController>(AUTH_SYMBOLS.ISignInController);
|
||||
expect(typeof controller).toBe("function");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,30 @@ import type { IUsersRepository } from "../application/repositories/users.reposit
|
||||
import type { IAuthenticationService } from "../application/services/authentication.service.interface";
|
||||
import { MockUsersRepository } from "../infrastructure/repositories/users.repository.mock";
|
||||
import { MockAuthenticationService } from "../infrastructure/services/authentication.service.mock";
|
||||
import {
|
||||
signInUseCase,
|
||||
type ISignInUseCase,
|
||||
} from "../application/use-cases/sign-in.use-case";
|
||||
import {
|
||||
signUpUseCase,
|
||||
type ISignUpUseCase,
|
||||
} from "../application/use-cases/sign-up.use-case";
|
||||
import {
|
||||
signOutUseCase,
|
||||
type ISignOutUseCase,
|
||||
} from "../application/use-cases/sign-out.use-case";
|
||||
import {
|
||||
signInController,
|
||||
type ISignInController,
|
||||
} from "../interface-adapters/controllers/sign-in.controller";
|
||||
import {
|
||||
signUpController,
|
||||
type ISignUpController,
|
||||
} from "../interface-adapters/controllers/sign-up.controller";
|
||||
import {
|
||||
signOutController,
|
||||
type ISignOutController,
|
||||
} from "../interface-adapters/controllers/sign-out.controller";
|
||||
import { AUTH_SYMBOLS } from "./symbols";
|
||||
|
||||
export const AuthModule = new ContainerModule((bind: interfaces.Bind) => {
|
||||
@@ -11,4 +35,42 @@ export const AuthModule = new ContainerModule((bind: interfaces.Bind) => {
|
||||
bind<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService).to(
|
||||
MockAuthenticationService,
|
||||
);
|
||||
|
||||
bind<ISignInUseCase>(AUTH_SYMBOLS.ISignInUseCase).toDynamicValue((ctx) =>
|
||||
signInUseCase(
|
||||
ctx.container.get<IUsersRepository>(AUTH_SYMBOLS.IUsersRepository),
|
||||
ctx.container.get<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService),
|
||||
),
|
||||
);
|
||||
|
||||
bind<ISignUpUseCase>(AUTH_SYMBOLS.ISignUpUseCase).toDynamicValue((ctx) =>
|
||||
signUpUseCase(
|
||||
ctx.container.get<IUsersRepository>(AUTH_SYMBOLS.IUsersRepository),
|
||||
ctx.container.get<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService),
|
||||
),
|
||||
);
|
||||
|
||||
bind<ISignOutUseCase>(AUTH_SYMBOLS.ISignOutUseCase).toDynamicValue((ctx) =>
|
||||
signOutUseCase(
|
||||
ctx.container.get<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService),
|
||||
),
|
||||
);
|
||||
|
||||
bind<ISignInController>(AUTH_SYMBOLS.ISignInController).toDynamicValue((ctx) =>
|
||||
signInController(
|
||||
ctx.container.get<ISignInUseCase>(AUTH_SYMBOLS.ISignInUseCase),
|
||||
),
|
||||
);
|
||||
|
||||
bind<ISignUpController>(AUTH_SYMBOLS.ISignUpController).toDynamicValue((ctx) =>
|
||||
signUpController(
|
||||
ctx.container.get<ISignUpUseCase>(AUTH_SYMBOLS.ISignUpUseCase),
|
||||
),
|
||||
);
|
||||
|
||||
bind<ISignOutController>(AUTH_SYMBOLS.ISignOutController).toDynamicValue((ctx) =>
|
||||
signOutController(
|
||||
ctx.container.get<ISignOutUseCase>(AUTH_SYMBOLS.ISignOutUseCase),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
export const AUTH_SYMBOLS = {
|
||||
IUsersRepository: Symbol.for("auth:IUsersRepository"),
|
||||
IAuthenticationService: Symbol.for("auth:IAuthenticationService"),
|
||||
// Use cases
|
||||
ISignInUseCase: Symbol.for("auth:ISignInUseCase"),
|
||||
ISignUpUseCase: Symbol.for("auth:ISignUpUseCase"),
|
||||
ISignOutUseCase: Symbol.for("auth:ISignOutUseCase"),
|
||||
// Controllers
|
||||
ISignInController: Symbol.for("auth:ISignInController"),
|
||||
ISignUpController: Symbol.for("auth:ISignUpController"),
|
||||
ISignOutController: Symbol.for("auth:ISignOutController"),
|
||||
} as const;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, vi, beforeEach } from "vitest";
|
||||
import { UsersRepository } from "@/infrastructure/repositories/users.repository";
|
||||
import { usersRepositoryContract } from "@/__contracts__/users-repository.contract";
|
||||
import { stubPayloadConfig } from "@repo/core-testing/payload/stub-config";
|
||||
|
||||
vi.mock("payload", () => ({ getPayload: vi.fn() }));
|
||||
|
||||
function buildPayloadStub() {
|
||||
const store = new Map<string, Record<string, unknown>>();
|
||||
|
||||
return {
|
||||
create: vi.fn(
|
||||
async ({
|
||||
data,
|
||||
}: {
|
||||
collection: string;
|
||||
data: Record<string, unknown>;
|
||||
overrideAccess?: boolean;
|
||||
}) => {
|
||||
const doc = { ...data };
|
||||
store.set(String(doc.id), doc);
|
||||
return doc;
|
||||
},
|
||||
),
|
||||
find: vi.fn(
|
||||
async ({
|
||||
where,
|
||||
}: {
|
||||
collection: string;
|
||||
where?: { username?: { equals: string } };
|
||||
limit?: number;
|
||||
overrideAccess?: boolean;
|
||||
}) => {
|
||||
const all = Array.from(store.values());
|
||||
if (where?.username?.equals) {
|
||||
return { docs: all.filter((u) => u.username === where.username?.equals) };
|
||||
}
|
||||
return { docs: all };
|
||||
},
|
||||
),
|
||||
findByID: vi.fn(
|
||||
async ({ id }: { collection: string; id: string; overrideAccess?: boolean }) => {
|
||||
return store.get(String(id)) ?? null;
|
||||
},
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
describe("UsersRepository", () => {
|
||||
describe("contract", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
usersRepositoryContract.run(async () => {
|
||||
const stub = buildPayloadStub();
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue(stub);
|
||||
return new UsersRepository(stubPayloadConfig);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { getPayload } from "payload";
|
||||
import type { SanitizedConfig } from "payload";
|
||||
import type { IUsersRepository } from "../../application/repositories/users.repository.interface";
|
||||
import { type User } from "../../entities/models/user";
|
||||
|
||||
export class UsersRepository implements IUsersRepository {
|
||||
constructor(private config: SanitizedConfig) {}
|
||||
|
||||
async getUser(id: string): Promise<User | undefined> {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const result = await payload.findByID({
|
||||
collection: "users",
|
||||
id,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return result ? this.toDomain(result as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
async getUserByUsername(username: string): Promise<User | undefined> {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const { docs } = await payload.find({
|
||||
collection: "users",
|
||||
where: { username: { equals: username } },
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return docs[0] ? this.toDomain(docs[0] as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
async createUser(input: User): Promise<User> {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const created = await payload.create({
|
||||
collection: "users",
|
||||
data: {
|
||||
id: input.id,
|
||||
username: input.username,
|
||||
passwordHash: input.passwordHash,
|
||||
},
|
||||
overrideAccess: true,
|
||||
});
|
||||
return this.toDomain(created as Record<string, unknown>);
|
||||
}
|
||||
|
||||
private toDomain(doc: Record<string, unknown>): User {
|
||||
return {
|
||||
id: doc.id as string,
|
||||
username: doc.username as string,
|
||||
passwordHash: doc.passwordHash as string,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { AuthenticationService } from "@/infrastructure/services/authentication.service";
|
||||
import { stubPayloadConfig } from "@repo/core-testing/payload/stub-config";
|
||||
|
||||
describe("AuthenticationService", () => {
|
||||
const service = new AuthenticationService(stubPayloadConfig);
|
||||
|
||||
describe("generateUserId", () => {
|
||||
it("returns a UUID string", () => {
|
||||
const id = service.generateUserId();
|
||||
expect(id).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns unique values", () => {
|
||||
const ids = Array.from({ length: 5 }, () => service.generateUserId());
|
||||
const unique = new Set(ids);
|
||||
expect(unique.size).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hashPassword + verifyPassword", () => {
|
||||
it("round-trips: hash then verify returns true", async () => {
|
||||
const hash = await service.hashPassword("my-secret");
|
||||
const valid = await service.verifyPassword(hash, "my-secret");
|
||||
expect(valid).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false for wrong password", async () => {
|
||||
const hash = await service.hashPassword("my-secret");
|
||||
const valid = await service.verifyPassword(hash, "wrong-password");
|
||||
expect(valid).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for malformed stored hash", async () => {
|
||||
const valid = await service.verifyPassword("not-a-valid-hash", "anything");
|
||||
expect(valid).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deferred methods (NotImplementedError)", () => {
|
||||
const user = {
|
||||
id: "test-id",
|
||||
username: "testuser",
|
||||
passwordHash: "hashed_password",
|
||||
};
|
||||
|
||||
it("createSession throws NotImplementedError", async () => {
|
||||
await expect(service.createSession(user)).rejects.toThrow("NotImplemented");
|
||||
});
|
||||
|
||||
it("validateSession throws NotImplementedError", async () => {
|
||||
await expect(service.validateSession("some-session")).rejects.toThrow("NotImplemented");
|
||||
});
|
||||
|
||||
it("invalidateSession throws NotImplementedError", async () => {
|
||||
await expect(service.invalidateSession("some-session")).rejects.toThrow("NotImplemented");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import crypto from "node:crypto";
|
||||
import type { SanitizedConfig } from "payload";
|
||||
import type { IAuthenticationService } from "../../application/services/authentication.service.interface";
|
||||
import type { Cookie } from "../../entities/models/cookie";
|
||||
import type { Session } from "../../entities/models/session";
|
||||
import type { User } from "../../entities/models/user";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Deferred methods
|
||||
// ---------------------------------------------------------------------------
|
||||
// `createSession`, `validateSession`, and `invalidateSession` require Payload's
|
||||
// internal JWT-based auth session machinery, which does not map cleanly to a
|
||||
// generic session interface without deep integration with Payload's REST/local
|
||||
// API and cookie infrastructure.
|
||||
//
|
||||
// TODO(lazar-conformance §7): Implement these three methods once the session
|
||||
// cookie strategy is settled. Until then they throw NotImplementedError to
|
||||
// keep the production-shaped file in place without silently no-oping.
|
||||
//
|
||||
// The mock (`authentication.service.mock.ts`) handles all test paths.
|
||||
|
||||
class NotImplementedError extends Error {
|
||||
constructor(method: string) {
|
||||
super(`NotImplemented: AuthenticationService.${method} — see refactor log §7`);
|
||||
this.name = "NotImplementedError";
|
||||
}
|
||||
}
|
||||
|
||||
const SALT_LENGTH = 16;
|
||||
const KEY_LENGTH = 64;
|
||||
const ITERATIONS = 100_000;
|
||||
const DIGEST = "sha512";
|
||||
const SEPARATOR = ":";
|
||||
|
||||
export class AuthenticationService implements IAuthenticationService {
|
||||
constructor(private _config: SanitizedConfig) {}
|
||||
|
||||
generateUserId(): string {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
|
||||
async hashPassword(password: string): Promise<string> {
|
||||
const salt = crypto.randomBytes(SALT_LENGTH).toString("hex");
|
||||
const hash = await new Promise<string>((resolve, reject) => {
|
||||
crypto.pbkdf2(password, salt, ITERATIONS, KEY_LENGTH, DIGEST, (err, derivedKey) => {
|
||||
if (err) reject(err);
|
||||
else resolve(derivedKey.toString("hex"));
|
||||
});
|
||||
});
|
||||
return `${salt}${SEPARATOR}${hash}`;
|
||||
}
|
||||
|
||||
async verifyPassword(storedHash: string, password: string): Promise<boolean> {
|
||||
const parts = storedHash.split(SEPARATOR);
|
||||
if (parts.length !== 2) return false;
|
||||
const salt = parts[0]!;
|
||||
const expectedHash = parts[1]!;
|
||||
const actualHash = await new Promise<string>((resolve, reject) => {
|
||||
crypto.pbkdf2(password, salt, ITERATIONS, KEY_LENGTH, DIGEST, (err, derivedKey) => {
|
||||
if (err) reject(err);
|
||||
else resolve(derivedKey.toString("hex"));
|
||||
});
|
||||
});
|
||||
return crypto.timingSafeEqual(
|
||||
Buffer.from(expectedHash, "hex"),
|
||||
Buffer.from(actualHash, "hex"),
|
||||
);
|
||||
}
|
||||
|
||||
// TODO(lazar-conformance §7): Implement using Payload's local.login / JWT session issuance.
|
||||
// Payload creates sessions via its REST auth endpoint; mapping that to a
|
||||
// generic { session: Session; cookie: Cookie } shape requires understanding
|
||||
// the JWT payload structure and the cookie name/attributes Payload uses.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
async createSession(user: User): Promise<{ session: Session; cookie: Cookie }> {
|
||||
throw new NotImplementedError("createSession");
|
||||
}
|
||||
|
||||
// TODO(lazar-conformance §7): Implement using Payload's JWT verify mechanism.
|
||||
// Need to call Payload's local API to verify the token and retrieve the user.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
async validateSession(sessionId: string): Promise<{ user: User; session: Session }> {
|
||||
throw new NotImplementedError("validateSession");
|
||||
}
|
||||
|
||||
// TODO(lazar-conformance §7): Implement by clearing the session token.
|
||||
// Payload does not have a server-side session store by default; invalidation
|
||||
// is typically done client-side by clearing the cookie.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
async invalidateSession(sessionId: string): Promise<{ blankCookie: Cookie }> {
|
||||
throw new NotImplementedError("invalidateSession");
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,7 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { authContainer } from "@/di/container";
|
||||
import { AUTH_SYMBOLS } from "@/di/symbols";
|
||||
import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock";
|
||||
import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock";
|
||||
import type { IUsersRepository } from "@/application/repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "@/application/services/authentication.service.interface";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { authRouter } from "./router";
|
||||
|
||||
describe("authRouter", () => {
|
||||
beforeEach(() => {
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IUsersRepository);
|
||||
}
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService);
|
||||
}
|
||||
const usersRepo = new MockUsersRepository();
|
||||
const authService = new MockAuthenticationService(usersRepo);
|
||||
authContainer
|
||||
.bind<IUsersRepository>(AUTH_SYMBOLS.IUsersRepository)
|
||||
.toConstantValue(usersRepo);
|
||||
authContainer
|
||||
.bind<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService)
|
||||
.toConstantValue(authService);
|
||||
});
|
||||
|
||||
it("exposes signIn, signUp, signOut procedures", () => {
|
||||
const names = Object.keys(authRouter._def.procedures);
|
||||
expect(names).toContain("signIn");
|
||||
@@ -32,7 +9,9 @@ describe("authRouter", () => {
|
||||
expect(names).toContain("signOut");
|
||||
});
|
||||
|
||||
it("signIn returns a cookie", async () => {
|
||||
it("signIn returns a cookie via container-resolved controller", async () => {
|
||||
// The router resolves controllers via the authContainer (default mock bindings).
|
||||
// MockUsersRepository is seeded with alice/password_alice by default.
|
||||
const caller = authRouter.createCaller({});
|
||||
const result = await caller.signIn({
|
||||
username: "alice",
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { z } from "zod";
|
||||
import { router, publicProcedure } from "@repo/core-shared/trpc/init";
|
||||
import { signInController } from "../../interface-adapters/controllers/sign-in.controller";
|
||||
import { signUpController } from "../../interface-adapters/controllers/sign-up.controller";
|
||||
import { signOutController } from "../../interface-adapters/controllers/sign-out.controller";
|
||||
import { authContainer } from "../../di/container";
|
||||
import { AUTH_SYMBOLS } from "../../di/symbols";
|
||||
import type { ISignInController } from "../../interface-adapters/controllers/sign-in.controller";
|
||||
import type { ISignUpController } from "../../interface-adapters/controllers/sign-up.controller";
|
||||
import type { ISignOutController } from "../../interface-adapters/controllers/sign-out.controller";
|
||||
|
||||
export const authRouter = router({
|
||||
signIn: publicProcedure
|
||||
@@ -12,7 +14,10 @@ export const authRouter = router({
|
||||
password: z.string().min(6).max(255),
|
||||
}),
|
||||
)
|
||||
.mutation(({ input }) => signInController(input)),
|
||||
.mutation(({ input }) => {
|
||||
const ctrl = authContainer.get<ISignInController>(AUTH_SYMBOLS.ISignInController);
|
||||
return ctrl(input);
|
||||
}),
|
||||
|
||||
signUp: publicProcedure
|
||||
.input(
|
||||
@@ -22,11 +27,17 @@ export const authRouter = router({
|
||||
confirmPassword: z.string().min(6).max(255),
|
||||
}),
|
||||
)
|
||||
.mutation(({ input }) => signUpController(input)),
|
||||
.mutation(({ input }) => {
|
||||
const ctrl = authContainer.get<ISignUpController>(AUTH_SYMBOLS.ISignUpController);
|
||||
return ctrl(input);
|
||||
}),
|
||||
|
||||
signOut: publicProcedure
|
||||
.input(z.object({ sessionId: z.string() }))
|
||||
.mutation(({ input }) => signOutController(input.sessionId)),
|
||||
.mutation(({ input }) => {
|
||||
const ctrl = authContainer.get<ISignOutController>(AUTH_SYMBOLS.ISignOutController);
|
||||
return ctrl(input.sessionId);
|
||||
}),
|
||||
});
|
||||
|
||||
export type AuthRouter = typeof authRouter;
|
||||
|
||||
@@ -1,51 +1,47 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { authContainer } from "@/di/container";
|
||||
import { AUTH_SYMBOLS } from "@/di/symbols";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { signInController } from "@/interface-adapters/controllers/sign-in.controller";
|
||||
import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock";
|
||||
import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock";
|
||||
import type { IUsersRepository } from "@/application/repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "@/application/services/authentication.service.interface";
|
||||
import { signInUseCase } from "@/application/use-cases/sign-in.use-case";
|
||||
import { InputParseError } from "@/entities/errors/common";
|
||||
import { signInController } from "./sign-in.controller";
|
||||
import { userFactory } from "@/__factories__/user.factory";
|
||||
|
||||
describe("signInController", () => {
|
||||
let usersRepo: MockUsersRepository;
|
||||
let authService: MockAuthenticationService;
|
||||
|
||||
beforeEach(() => {
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IUsersRepository);
|
||||
}
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService);
|
||||
}
|
||||
usersRepo = new MockUsersRepository();
|
||||
authService = new MockAuthenticationService(usersRepo);
|
||||
authContainer
|
||||
.bind<IUsersRepository>(AUTH_SYMBOLS.IUsersRepository)
|
||||
.toConstantValue(usersRepo);
|
||||
authContainer
|
||||
.bind<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService)
|
||||
.toConstantValue(authService);
|
||||
});
|
||||
|
||||
it("returns a cookie on valid credentials", async () => {
|
||||
const cookie = await signInController({
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const seedUser = userFactory.build({
|
||||
username: "alice",
|
||||
password: "password_alice",
|
||||
passwordHash: "hashed_testpassword",
|
||||
});
|
||||
await users.createUser(seedUser);
|
||||
|
||||
const useCase = signInUseCase(users, auth);
|
||||
const controller = signInController(useCase);
|
||||
|
||||
const cookie = await controller({ username: "alice", password: "testpassword" });
|
||||
expect(cookie.name).toBe("session");
|
||||
});
|
||||
|
||||
it("throws InputParseError on missing username", async () => {
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const useCase = signInUseCase(users, auth);
|
||||
const controller = signInController(useCase);
|
||||
|
||||
await expect(
|
||||
signInController({ password: "anything" }),
|
||||
controller({ password: "anything" }),
|
||||
).rejects.toBeInstanceOf(InputParseError);
|
||||
});
|
||||
|
||||
it("throws InputParseError on too-short password", async () => {
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const useCase = signInUseCase(users, auth);
|
||||
const controller = signInController(useCase);
|
||||
|
||||
await expect(
|
||||
signInController({ username: "alice", password: "abc" }),
|
||||
controller({ username: "alice", password: "abc" }),
|
||||
).rejects.toBeInstanceOf(InputParseError);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,20 +2,22 @@ import { z } from "zod";
|
||||
|
||||
import { InputParseError } from "../../entities/errors/common";
|
||||
import type { Cookie } from "../../entities/models/cookie";
|
||||
import { signInUseCase } from "../../application/use-cases/sign-in.use-case";
|
||||
import type { ISignInUseCase } from "../../application/use-cases/sign-in.use-case";
|
||||
|
||||
const inputSchema = z.object({
|
||||
username: z.string().min(3).max(31),
|
||||
password: z.string().min(6).max(255),
|
||||
});
|
||||
|
||||
export async function signInController(
|
||||
input: Partial<z.infer<typeof inputSchema>>,
|
||||
): Promise<Cookie> {
|
||||
export type ISignInController = ReturnType<typeof signInController>;
|
||||
|
||||
export const signInController =
|
||||
(signInUseCase: ISignInUseCase) =>
|
||||
async (input: Partial<z.infer<typeof inputSchema>>): Promise<Cookie> => {
|
||||
const parsed = inputSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new InputParseError("Invalid sign-in input", { cause: parsed.error });
|
||||
}
|
||||
const { cookie } = await signInUseCase(parsed.data);
|
||||
return cookie;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,40 +1,28 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { authContainer } from "@/di/container";
|
||||
import { AUTH_SYMBOLS } from "@/di/symbols";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { signOutController } from "@/interface-adapters/controllers/sign-out.controller";
|
||||
import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock";
|
||||
import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock";
|
||||
import type { IUsersRepository } from "@/application/repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "@/application/services/authentication.service.interface";
|
||||
import { signOutUseCase } from "@/application/use-cases/sign-out.use-case";
|
||||
import { InputParseError } from "@/entities/errors/common";
|
||||
import { signOutController } from "./sign-out.controller";
|
||||
|
||||
describe("signOutController", () => {
|
||||
beforeEach(() => {
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IUsersRepository);
|
||||
}
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService);
|
||||
}
|
||||
const usersRepo = new MockUsersRepository();
|
||||
const authService = new MockAuthenticationService(usersRepo);
|
||||
authContainer
|
||||
.bind<IUsersRepository>(AUTH_SYMBOLS.IUsersRepository)
|
||||
.toConstantValue(usersRepo);
|
||||
authContainer
|
||||
.bind<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService)
|
||||
.toConstantValue(authService);
|
||||
});
|
||||
|
||||
it("returns a blank cookie", async () => {
|
||||
const cookie = await signOutController("session_anything");
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const useCase = signOutUseCase(auth);
|
||||
const controller = signOutController(useCase);
|
||||
|
||||
const cookie = await controller("session_anything");
|
||||
expect(cookie.name).toBe("session");
|
||||
expect(cookie.value).toBe("");
|
||||
});
|
||||
|
||||
it("throws InputParseError when sessionId is missing", async () => {
|
||||
await expect(signOutController(undefined)).rejects.toBeInstanceOf(
|
||||
InputParseError,
|
||||
);
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const useCase = signOutUseCase(auth);
|
||||
const controller = signOutController(useCase);
|
||||
|
||||
await expect(controller(undefined)).rejects.toBeInstanceOf(InputParseError);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { InputParseError } from "../../entities/errors/common";
|
||||
import type { Cookie } from "../../entities/models/cookie";
|
||||
import { signOutUseCase } from "../../application/use-cases/sign-out.use-case";
|
||||
import type { ISignOutUseCase } from "../../application/use-cases/sign-out.use-case";
|
||||
|
||||
export async function signOutController(
|
||||
sessionId: string | undefined,
|
||||
): Promise<Cookie> {
|
||||
export type ISignOutController = ReturnType<typeof signOutController>;
|
||||
|
||||
export const signOutController =
|
||||
(signOutUseCase: ISignOutUseCase) =>
|
||||
async (sessionId: string | undefined): Promise<Cookie> => {
|
||||
if (!sessionId) {
|
||||
throw new InputParseError("Must provide a session ID");
|
||||
}
|
||||
const { blankCookie } = await signOutUseCase(sessionId);
|
||||
return blankCookie;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,36 +1,19 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { authContainer } from "@/di/container";
|
||||
import { AUTH_SYMBOLS } from "@/di/symbols";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { signUpController } from "@/interface-adapters/controllers/sign-up.controller";
|
||||
import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock";
|
||||
import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock";
|
||||
import type { IUsersRepository } from "@/application/repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "@/application/services/authentication.service.interface";
|
||||
import { signUpUseCase } from "@/application/use-cases/sign-up.use-case";
|
||||
import { InputParseError } from "@/entities/errors/common";
|
||||
import { signUpController } from "./sign-up.controller";
|
||||
import { userFactory } from "@/__factories__/user.factory";
|
||||
|
||||
describe("signUpController", () => {
|
||||
let usersRepo: MockUsersRepository;
|
||||
let authService: MockAuthenticationService;
|
||||
|
||||
beforeEach(() => {
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IUsersRepository);
|
||||
}
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService);
|
||||
}
|
||||
usersRepo = new MockUsersRepository();
|
||||
authService = new MockAuthenticationService(usersRepo);
|
||||
authContainer
|
||||
.bind<IUsersRepository>(AUTH_SYMBOLS.IUsersRepository)
|
||||
.toConstantValue(usersRepo);
|
||||
authContainer
|
||||
.bind<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService)
|
||||
.toConstantValue(authService);
|
||||
});
|
||||
|
||||
it("creates a new user when passwords match", async () => {
|
||||
const result = await signUpController({
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const useCase = signUpUseCase(users, auth);
|
||||
const controller = signUpController(useCase);
|
||||
|
||||
const result = await controller({
|
||||
username: "carol",
|
||||
password: "secret_password",
|
||||
confirmPassword: "secret_password",
|
||||
@@ -39,12 +22,30 @@ describe("signUpController", () => {
|
||||
});
|
||||
|
||||
it("throws InputParseError when passwords do not match", async () => {
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
const useCase = signUpUseCase(users, auth);
|
||||
const controller = signUpController(useCase);
|
||||
|
||||
await expect(
|
||||
signUpController({
|
||||
controller({
|
||||
username: "dave",
|
||||
password: "secret_password",
|
||||
confirmPassword: "different_password",
|
||||
}),
|
||||
).rejects.toBeInstanceOf(InputParseError);
|
||||
});
|
||||
|
||||
it("throws InputParseError when username is too short", async () => {
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
// Pre-seed so we don't hit the taken-username error
|
||||
await users.createUser(userFactory.build({ username: "alice" }));
|
||||
const useCase = signUpUseCase(users, auth);
|
||||
const controller = signUpController(useCase);
|
||||
|
||||
await expect(
|
||||
controller({ username: "ab", password: "secret_password", confirmPassword: "secret_password" }),
|
||||
).rejects.toBeInstanceOf(InputParseError);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { InputParseError } from "../../entities/errors/common";
|
||||
import { signUpUseCase } from "../../application/use-cases/sign-up.use-case";
|
||||
import type { ISignUpUseCase } from "../../application/use-cases/sign-up.use-case";
|
||||
|
||||
const inputSchema = z
|
||||
.object({
|
||||
@@ -24,12 +24,16 @@ const inputSchema = z
|
||||
}
|
||||
});
|
||||
|
||||
export async function signUpController(
|
||||
export type ISignUpController = ReturnType<typeof signUpController>;
|
||||
|
||||
export const signUpController =
|
||||
(signUpUseCase: ISignUpUseCase) =>
|
||||
async (
|
||||
input: Partial<z.infer<typeof inputSchema>>,
|
||||
): Promise<ReturnType<typeof signUpUseCase>> {
|
||||
): Promise<Awaited<ReturnType<ISignUpUseCase>>> => {
|
||||
const parsed = inputSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new InputParseError("Invalid sign-up input", { cause: parsed.error });
|
||||
}
|
||||
return await signUpUseCase(parsed.data);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,36 +1,27 @@
|
||||
// Feature-level test: sign-up, then sign-in with the new credentials, then sign-out.
|
||||
// Constructs the full chain via direct injection (no container rebinding).
|
||||
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { authContainer } from "../src/di/container";
|
||||
import { AUTH_SYMBOLS } from "../src/di/symbols";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { MockUsersRepository } from "../src/infrastructure/repositories/users.repository.mock";
|
||||
import { MockAuthenticationService } from "../src/infrastructure/services/authentication.service.mock";
|
||||
import type { IUsersRepository } from "../src/application/repositories/users.repository.interface";
|
||||
import type { IAuthenticationService } from "../src/application/services/authentication.service.interface";
|
||||
import { authRouter } from "../src/integrations/api/router";
|
||||
import { signInUseCase } from "../src/application/use-cases/sign-in.use-case";
|
||||
import { signUpUseCase } from "../src/application/use-cases/sign-up.use-case";
|
||||
import { signOutUseCase } from "../src/application/use-cases/sign-out.use-case";
|
||||
import { signInController } from "../src/interface-adapters/controllers/sign-in.controller";
|
||||
import { signUpController } from "../src/interface-adapters/controllers/sign-up.controller";
|
||||
import { signOutController } from "../src/interface-adapters/controllers/sign-out.controller";
|
||||
|
||||
describe("auth feature: sign-up → sign-in → sign-out", () => {
|
||||
beforeEach(() => {
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IUsersRepository);
|
||||
}
|
||||
if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) {
|
||||
authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService);
|
||||
}
|
||||
const usersRepo = new MockUsersRepository();
|
||||
const authService = new MockAuthenticationService(usersRepo);
|
||||
authContainer
|
||||
.bind<IUsersRepository>(AUTH_SYMBOLS.IUsersRepository)
|
||||
.toConstantValue(usersRepo);
|
||||
authContainer
|
||||
.bind<IAuthenticationService>(AUTH_SYMBOLS.IAuthenticationService)
|
||||
.toConstantValue(authService);
|
||||
});
|
||||
|
||||
it("a new user can sign up, then sign in, then sign out", async () => {
|
||||
const caller = authRouter.createCaller({});
|
||||
// Construct the full chain via direct injection
|
||||
const users = new MockUsersRepository([]);
|
||||
const auth = new MockAuthenticationService(users);
|
||||
|
||||
const signUpResult = await caller.signUp({
|
||||
const signIn = signInController(signInUseCase(users, auth));
|
||||
const signUp = signUpController(signUpUseCase(users, auth));
|
||||
const signOut = signOutController(signOutUseCase(auth));
|
||||
|
||||
const signUpResult = await signUp({
|
||||
username: "newperson",
|
||||
password: "verysecret",
|
||||
confirmPassword: "verysecret",
|
||||
@@ -38,15 +29,13 @@ describe("auth feature: sign-up → sign-in → sign-out", () => {
|
||||
expect(signUpResult.user.username).toBe("newperson");
|
||||
const userId = signUpResult.user.id;
|
||||
|
||||
const signInCookie = await caller.signIn({
|
||||
const signInCookie = await signIn({
|
||||
username: "newperson",
|
||||
password: "verysecret",
|
||||
});
|
||||
expect(signInCookie.value).toBe("session_" + userId);
|
||||
|
||||
const signOutResult = await caller.signOut({
|
||||
sessionId: signInCookie.value,
|
||||
});
|
||||
const signOutResult = await signOut(signInCookie.value);
|
||||
expect(signOutResult.value).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user