Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
355f21b
Passwords also refuse a distinctive word of an institute's name, not …
omerFixesBugs Nov 16, 2026
7016eff
Sprint 1 P1-J plan (docs/plans/sprint-1-p1j-password-hash.md): the ap…
omerFixesBugs Nov 16, 2026
25da8a3
Sprint 1 P2 plan (docs/plans/sprint-1-p2-files.md): institute profile…
omerFixesBugs Nov 16, 2026
995e61e
Test users get phone numbers no other test user of the same database …
omerFixesBugs Nov 16, 2026
356c448
The app login can no longer read users.password_hash (P1-J): SELECT o…
omerFixesBugs Nov 16, 2026
3ca69eb
Every Prisma client leaves users.password_hash out of its reads (P1-J…
omerFixesBugs Nov 16, 2026
30e85f6
Files and the institute profile in the database (P2 task 1): stored_f…
omerFixesBugs Nov 16, 2026
687a83b
CORS_ORIGINS is normalised in env.ts as browsers send Origin (lower-c…
omerFixesBugs Nov 16, 2026
ff8981c
Shared file caps, types and the institute profile schema (P2 task 2):…
omerFixesBugs Nov 16, 2026
917d5eb
The start-up login check also refuses a login with REPLICATION (a rep…
omerFixesBugs Nov 16, 2026
bc6644b
Password login without the hash (P1-J): the API hashes the typed pass…
omerFixesBugs Nov 16, 2026
b0e6315
GET /me/password reads hasPassword from auth_my_password_is_set() (P1…
omerFixesBugs Nov 16, 2026
47fb357
Docs for P1-J: database.md (password_hash not readable by the app, a …
omerFixesBugs Nov 16, 2026
20b29e9
Redis is pinned to one exact version, redis:7.4.11-alpine (the versio…
omerFixesBugs Nov 16, 2026
81bfc26
Docs for the follow-ups: decisions-pending gets the section "Small fo…
omerFixesBugs Nov 16, 2026
9cc9d54
Image processing for uploads (P2 task 3): sharp 0.35.5 (already in th…
omerFixesBugs Nov 16, 2026
b0e010b
FileStore and the per-institute cap (P2 task 4): PostgresFileStore is…
omerFixesBugs Nov 16, 2026
caec9f7
Photo and profile routes (P2 task 5): GET/PUT/DELETE /students/:id/ph…
omerFixesBugs Nov 16, 2026
57cf79f
Web (P2 task 6): Settings → Institute profile (names, EIIN, contact, …
omerFixesBugs Nov 16, 2026
4e4cbb2
Docs for P2 (task 7): docs/files.md, database.md (the three tables an…
omerFixesBugs Nov 16, 2026
724ffb0
The photo dialog's preview URL is made when a file is chosen, not in …
omerFixesBugs Nov 16, 2026
110857d
files.spec: the profile fields by id ("নাম (বাংলা)" is also part of t…
omerFixesBugs Nov 16, 2026
8c3a4f9
After the review (P1-J7): a dedicated login for the password login. j…
omerFixesBugs Nov 16, 2026
72b714b
The password login looks the hash up on its own database login (Login…
omerFixesBugs Nov 16, 2026
06f3236
Docs after the P1-J review: what an injection in an ordinary request …
omerFixesBugs Nov 16, 2026
82f6600
Test phones never wrap and their lock survives races (review of PR #1…
omerFixesBugs Nov 16, 2026
27403c3
The institute-name rule compares passwords and names like the phone r…
omerFixesBugs Nov 16, 2026
7aa31c5
An origin setting with a login, a path, a query or a fragment is no o…
omerFixesBugs Nov 16, 2026
fd6430e
Docs after the review of PR #17: P1-I's title line says it is built h…
omerFixesBugs Nov 16, 2026
9dbee45
P1-J migration after the second review: it first checks that jantrik_…
omerFixesBugs Nov 16, 2026
a980a60
The password login's database login must reach the same database, por…
omerFixesBugs Nov 16, 2026
ff673b8
Docs after the second P1-J review: the server upgrade creates the rol…
omerFixesBugs Nov 16, 2026
13deed2
A file reference is tied to its kind (review R6): UNIQUE (tenant_id, …
omerFixesBugs Nov 16, 2026
cb86722
Uploads hold no database connection while they arrive (review R1): th…
omerFixesBugs Nov 16, 2026
459bcf7
Web after the review: a chosen image is shrunk in the browser to 1600…
omerFixesBugs Nov 16, 2026
944e840
Docs after the review: auth.md (the request pipeline and @OwnTransact…
omerFixesBugs Nov 16, 2026
282c8b6
Review round 2, API: uploads in flight bounded before multer (16 per …
omerFixesBugs Nov 16, 2026
cfd4506
Review round 2, web: the browser asks for the EXIF orientation explic…
omerFixesBugs Nov 16, 2026
73eb83b
Docs for review round 2: auth.md (the upload routes' re-checks, Uploa…
omerFixesBugs Nov 16, 2026
e622e52
The interceptor opens its transaction through an unchecked entry (aro…
omerFixesBugs Nov 16, 2026
3d2c5d5
Review round 3: no upload slot leaks when the client left before Uplo…
omerFixesBugs Nov 16, 2026
de19108
The two new origin tests' development settings also name DATABASE_LOG…
omerFixesBugs Nov 16, 2026
aa0105b
Merge P1-J (#16) into the small follow-ups (#17): the ready resolutio…
omerFixesBugs Nov 16, 2026
b1efceb
Merge remote-tracking branch 'origin/feature/sprint-1-p1j-password-ha…
omerFixesBugs Nov 16, 2026
b5d3697
Merge remote-tracking branch 'origin/feature/sprint-1-p2-files' into …
omerFixesBugs Nov 16, 2026
c857102
Merge remote-tracking branch 'origin/feature/small-followups-after-p1…
omerFixesBugs Nov 16, 2026
9309fa8
Work in progress: a staff guide draft and draft legal texts (terms of…
omerFixesBugs Nov 19, 2026
ed5d56c
Docs only: a plain staff guide draft (signing in, setup, students, gu…
omerFixesBugs Nov 19, 2026
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
Prev Previous commit
Next Next commit
Photo and profile routes (P2 task 5): GET/PUT/DELETE /students/:id/ph…
…oto (the photo is part of the full record: OWNER, ADMIN, a teacher of the student's section), GET /me/children/:id/photo (own children only), the institute profile with its logo (every member), head's signature and seal (OWNER, ADMIN); a replaced image's file is deleted in the same transaction and audited; photoUrl (never written) becomes photoId in every API type

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
omerFixesBugs and claude committed Nov 16, 2026
commit caec9f7ecf7c072924e871d004ebcb04dda10759
4 changes: 4 additions & 0 deletions apps/api/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { AuthModule } from './auth/auth.module.js';
import { DevicesModule } from './devices/devices.module.js';
import { ExamsModule } from './exams/exams.module.js';
import { FeesModule } from './fees/fees.module.js';
import { FilesModule } from './files/files.module.js';
import {
JwtAuthGuard,
ModuleGuard,
Expand All @@ -22,6 +23,7 @@ import { ZodValidationPipe } from './common/zod.js';
import { validateEnv, type Env } from './config/env.js';
import { HealthModule } from './health/health.module.js';
import { ImportsModule } from './imports/imports.module.js';
import { InstituteProfileModule } from './institute/institute-profile.module.js';
import { MeModule } from './me/me.module.js';
import { PrismaModule } from './prisma/prisma.module.js';
import { RedisModule } from './redis/redis.module.js';
Expand Down Expand Up @@ -60,11 +62,13 @@ import { TenantContextInterceptor } from './tenancy/tenant-context.interceptor.j
PrismaModule,
TenancyModule,
AuditModule,
FilesModule,
SmsModule,
AuthModule,
HealthModule,
MeModule,
AppearanceModule,
InstituteProfileModule,
StudentsModule,
SetupModule,
StaffModule,
Expand Down
5 changes: 3 additions & 2 deletions apps/api/src/exams/results/exam-results.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ export class ExamResultsService {
studentCode: true,
nameBn: true,
nameEn: true,
photoUrl: true,
photoFileId: true,
fatherNameBn: true,
fatherNameEn: true,
motherNameBn: true,
Expand Down Expand Up @@ -490,7 +490,8 @@ export class ExamResultsService {
studentCode: st.studentCode,
nameBn: st.nameBn,
nameEn: st.nameEn,
photoUrl: st.photoUrl,
// The photo is part of the full record (as on the student's page).
photoId: sees ? st.photoFileId : null,
fatherNameBn: sees ? st.fatherNameBn : null,
fatherNameEn: sees ? st.fatherNameEn : null,
motherNameBn: sees ? st.motherNameBn : null,
Expand Down
9 changes: 7 additions & 2 deletions apps/api/src/exams/seats/seat-plan.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ export class SeatPlanService {
},
orderBy: [{ section: { name: 'asc' } }, { roll: 'asc' }],
include: {
student: { select: { studentCode: true, nameBn: true, nameEn: true, photoUrl: true } },
student: { select: { studentCode: true, nameBn: true, nameEn: true, photoFileId: true } },
section: { select: { id: true, name: true } },
studyGroup: { select: { id: true, code: true, nameBn: true, nameEn: true } },
room: { select: { name: true } },
Expand Down Expand Up @@ -219,7 +219,12 @@ export class SeatPlanService {
);
return {
candidateId: c.id,
student: c.student,
student: {
studentCode: c.student.studentCode,
nameBn: c.student.nameBn,
nameEn: c.student.nameEn,
photoId: c.student.photoFileId,
},
classLevel: c.examClass.classLevel,
section: c.section,
studyGroup: c.studyGroup,
Expand Down
283 changes: 283 additions & 0 deletions apps/api/src/institute/institute-profile.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,283 @@
import {
Body,
Controller,
Delete,
Get,
Inject,
Injectable,
Module,
Param,
ParseEnumPipe,
Put,
Req,
Res,
UploadedFile,
} from '@nestjs/common';
import type { Prisma } from '@jantrik/db';
import {
INSTITUTE_IMAGE_KIND,
INSTITUTE_IMAGE_SLOTS,
instituteProfileSchema,
type FileRef,
type InstituteImageSlot,
type InstituteProfile,
type InstituteProfileFields,
} from '@jantrik/shared';
import type { Request, Response } from 'express';
import { AuditService } from '../audit/audit.module.js';
import { RequireModule, Roles } from '../common/decorators.js';
import { RequestContext } from '../common/request-context.js';
import { zodDto } from '../common/zod.js';
import { FILE_STORE, type FileStore, type StoredFileMeta } from '../files/file-store.js';
import {
ImageUpload,
ImageUploads,
sendStoredImage,
type UploadedImage,
} from '../files/files.module.js';
import { Db } from '../tenancy/db.service.js';

class InstituteProfileDto extends zodDto(instituteProfileSchema) {}

/** The profile column holding each slot's file. */
const COLUMN = {
logo: 'logoFileId',
signature: 'headSignatureFileId',
seal: 'sealFileId',
} as const satisfies Record<InstituteImageSlot, keyof Prisma.InstituteProfileUncheckedCreateInput>;

const FIELDS = [
'nameBn',
'nameEn',
'shortName',
'eiin',
'addressBn',
'addressEn',
'phone',
'email',
'website',
'headTitleBn',
'headTitleEn',
'headNameBn',
'headNameEn',
'establishedYear',
] as const satisfies readonly (keyof InstituteProfileFields)[];

const BANGLA = /[ঀ-৿]/;

/**
* The institute's own profile (sprint 1 P2, docs/files.md): names, EIIN, contact, the head of the
* institute, and three images. One row per institute, created on the first save or image (no
* backfill). Every change is audited; images through FileStore only.
*/
@Injectable()
export class InstituteProfileService {
constructor(
private readonly db: Db,
private readonly context: RequestContext,
private readonly audit: AuditService,
private readonly uploads: ImageUploads,
@Inject(FILE_STORE) private readonly files: FileStore,
) {}

private row() {
return this.db.tx.instituteProfile.findFirst();
}

async get(): Promise<InstituteProfile> {
const tenant = await this.db.tx.tenant.findFirstOrThrow({
where: { id: this.context.requireTenantId() },
select: { name: true },
});
const row = await this.row();
const ref = async (id: string | null | undefined): Promise<FileRef | null> => {
const meta = id ? await this.files.meta(id) : null;
return meta ? fileRef(meta) : null;
};
const fields = Object.fromEntries(
FIELDS.map((f) => [f, row?.[f] ?? null]),
) as unknown as InstituteProfileFields;
return {
...fields,
saved: row !== null,
registeredName: tenant.name,
logo: await ref(row?.logoFileId),
signature: await ref(row?.headSignatureFileId),
seal: await ref(row?.sealFileId),
storage: await this.files.usage(),
};
}

async update(input: InstituteProfileFields): Promise<InstituteProfile> {
const tenantId = this.context.requireTenantId();
const before = await this.row();
const data = Object.fromEntries(
FIELDS.map((f) => [f, input[f]]),
) as unknown as InstituteProfileFields;
const old = before ? Object.fromEntries(FIELDS.map((f) => [f, before[f]])) : null;
const changed = !old || FIELDS.some((f) => old[f] !== data[f]);
if (changed) {
const row = await this.db.tx.instituteProfile.upsert({
where: { tenantId },
create: { tenantId, ...data },
update: data,
select: { id: true },
});
await this.audit.record({
entity: 'institute_profile',
entityId: row.id,
action: before ? 'UPDATE' : 'CREATE',
...(old ? { oldValues: old } : {}),
newValues: data as unknown as Prisma.InputJsonValue,
});
}
return this.get();
}

/**
* Sets (or replaces) one image; the replaced file is deleted in the same transaction (F10). The
* store holds the institute's file lock from here to commit, so the old id read below is final.
*/
async setImage(slot: InstituteImageSlot, upload: UploadedImage | undefined) {
const stored = await this.uploads.store(INSTITUTE_IMAGE_KIND[slot], upload);
const profile = await this.ensureRow();
const oldId = profile[COLUMN[slot]];
await this.db.tx.instituteProfile.update({
where: { id: profile.id },
data: { [COLUMN[slot]]: stored.id },
select: { id: true },
});
if (oldId) await this.files.delete(oldId);
await this.audit.record({
entity: 'institute_profile',
entityId: profile.id,
action: 'UPDATE',
oldValues: { image: slot, fileId: oldId },
newValues: { image: slot, fileId: stored.id },
});
return this.get();
}

async removeImage(slot: InstituteImageSlot): Promise<InstituteProfile> {
await this.files.lock();
const profile = await this.row();
const oldId = profile?.[COLUMN[slot]];
if (profile && oldId) {
await this.db.tx.instituteProfile.update({
where: { id: profile.id },
data: { [COLUMN[slot]]: null },
select: { id: true },
});
await this.files.delete(oldId);
await this.audit.record({
entity: 'institute_profile',
entityId: profile.id,
action: 'UPDATE',
oldValues: { image: slot, fileId: oldId },
newValues: { image: slot, fileId: null },
});
}
return this.get();
}

/** The image's file id for serving, or null. */
async imageId(slot: InstituteImageSlot): Promise<string | null> {
return (await this.row())?.[COLUMN[slot]] ?? null;
}

/**
* The profile row, created for an image uploaded before the first save (F6) with the
* registered name in the matching script, so the "one name" CHECK holds.
*/
private async ensureRow() {
const existing = await this.row();
if (existing) return existing;
const tenantId = this.context.requireTenantId();
const { name } = await this.db.tx.tenant.findFirstOrThrow({
where: { id: tenantId },
select: { name: true },
});
const names = BANGLA.test(name)
? { nameBn: name.slice(0, 200) }
: { nameEn: name.slice(0, 200) };
const row = await this.db.tx.instituteProfile.create({ data: { tenantId, ...names } });
await this.audit.record({
entity: 'institute_profile',
entityId: row.id,
action: 'CREATE',
newValues: names,
});
return row;
}
}

function fileRef(meta: StoredFileMeta): FileRef {
return {
id: meta.id,
mime: meta.mime,
sizeBytes: meta.sizeBytes,
width: meta.width,
height: meta.height,
};
}

const Slot = () => Param('slot', new ParseEnumPipe(INSTITUTE_IMAGE_SLOTS));

@Controller('institute/profile')
@RequireModule('CORE')
export class InstituteProfileController {
constructor(
private readonly profile: InstituteProfileService,
@Inject(FILE_STORE) private readonly files: FileStore,
) {}

@Get()
@Roles('OWNER', 'ADMIN')
get(): Promise<InstituteProfile> {
return this.profile.get();
}

@Put()
@Roles('OWNER', 'ADMIN')
update(@Body() dto: InstituteProfileDto): Promise<InstituteProfile> {
return this.profile.update(dto as unknown as InstituteProfileFields);
}

/** The logo is the institute's public face: every member may see it, guardians too (F1). */
@Get('logo')
@Roles('OWNER', 'ADMIN', 'TEACHER', 'ACCOUNTANT', 'STAFF', 'GUARDIAN')
async logo(@Req() req: Request, @Res() res: Response): Promise<void> {
await sendStoredImage(this.files, await this.profile.imageId('logo'), req, res);
}

/** The head's signature and the seal could be misused on forged papers: owner and admin (F1). */
@Get(':slot')
@Roles('OWNER', 'ADMIN')
async image(
@Slot() slot: InstituteImageSlot,
@Req() req: Request,
@Res() res: Response,
): Promise<void> {
await sendStoredImage(this.files, await this.profile.imageId(slot), req, res);
}

/** multipart/form-data with `file` (JPEG, PNG or WebP, at most 5 MB). */
@Put(':slot')
@Roles('OWNER', 'ADMIN')
@ImageUpload()
setImage(
@Slot() slot: InstituteImageSlot,
@UploadedFile() file: UploadedImage | undefined,
): Promise<InstituteProfile> {
return this.profile.setImage(slot, file);
}

@Delete(':slot')
@Roles('OWNER', 'ADMIN')
removeImage(@Slot() slot: InstituteImageSlot): Promise<InstituteProfile> {
return this.profile.removeImage(slot);
}
}

@Module({ controllers: [InstituteProfileController], providers: [InstituteProfileService] })
export class InstituteProfileModule {}
Loading