Naalya Handbook
Permission checks

Building the ability

How AbilityFactoryService turns a JWT into a list of CASL rules, resolveContext loads identity, buildAbility seeds the grants.

The heart of the engine is AbilityFactoryService. Its job is to turn a user's identity into a list of CASL rules, and it does it in two clean steps you should keep separate in your head.

createForUser

The public entry point, createForUser(jwt), does two things in sequence: resolve context (load everything the user's identity needs from the database) then build the ability (turn that context into CASL rules).

apps/server/src/app/auth/ability/ability-factory.service.ts
async createForUser(jwt: JwtPayload): Promise<AppAbility> {
  const ctx = await this.resolveContext(jwt);
  return this.buildAbility(ctx);
}

resolveContext

resolveContext branches on the user's type, because different kinds of user derive their powers from completely different places. Staff get their power from roles in the database; everyone else gets it from who they are.

apps/server/src/app/auth/ability/ability-factory.service.ts
switch (jwt.type) {
  case UserType.STAFF:
    base.roleAssignments = await this.getStaffRoleAssignments(jwt.sub);
    base.departmentAssignments = await this.getStaffDepartmentAssignments(jwt.sub);
    // ...look up staffProfileId
    break;
  case UserType.GUARDIAN:
    // ...guardianProfileId
    base.linkedStudentIds = await this.getLinkedStudentIds(jwt.sub); // verified only
    break;
  case UserType.STUDENT:   /* studentProfileId + campusId from profile */ break;
  case UserType.GUEST:     /* guestProfileId */ break;
  case UserType.PLATFORM_ADMIN:
    // No DB lookups: powers are hardcoded in buildAbility.
    break;
}

The staff branch is the only one that touches role tables. getStaffRoleAssignments pulls every user_x_role row with its role and that role's permissions, and crucially keeps each assignment's scopeLevel and campusId: the raw material for scoping later.

For guardians, getLinkedStudentIds is where a subtle but vital filter lives: it returns only links where isVerified: true. An unverified guardian-student link grants nothing.

buildAbility

buildAbility opens a CASL AbilityBuilder and, again branching on type, calls can(action, resource, conditions?) to register rules. Non-staff users get a fixed, hardcoded set of self-service grants: their abilities are entirely derived from identity and cannot be changed by assigning roles.

Resource.ACADEMIC_REPORT is not in the enum. The student branch grants report_card, and only when releasedAt is present and not after now. Read from buildAbility at a5dff0c208d5193c274d3d1f87787b55344d5d30:

apps/server/src/app/auth/ability/ability-factory.service.ts
case UserType.STUDENT:
  can(Action.READ, Resource.USER, { id: ctx.userId });
  can(Action.READ, Resource.LEDGER, { accountUserId: ctx.userId });
  can(Action.LIST, Resource.ACADEMIC_YEAR);
  can(Action.READ, Resource.ACADEMIC_YEAR);
  can(Action.LIST, Resource.CAMPUS);
  can(Action.READ, Resource.CAMPUS);
  if (ctx.studentProfileId) {
    can(Action.READ, Resource.STUDENT, { id: ctx.studentProfileId });
    can(Action.READ, Resource.GRADE, { studentId: ctx.studentProfileId });
    can(Action.READ, Resource.REPORT_CARD, {
      studentId: ctx.studentProfileId,
      releasedAt: { $exists: true, $ne: null, $gte: new Date(0), $lte: new Date() },
    });
  }
  if (ctx.campusId) {
    can(Action.READ, Resource.CAMPUS, { id: ctx.campusId });
    can(Action.READ, Resource.CAMPUS_TERM, { campusId: ctx.campusId });
    can(Action.LIST, Resource.CAMPUS_TERM, { campusId: ctx.campusId });
    can(Action.LIST, Resource.LIBRARY_CATALOGUE, { campusId: ctx.campusId });
    can(Action.READ, Resource.LIBRARY_CATALOGUE, { campusId: ctx.campusId });
  }
  can(Action.LIST, Resource.NOTICE_BOARD);
  can(Action.READ, Resource.NOTICE_BOARD);
  break;

The comment in that branch says notice-board visibility is decided by NoticeAudienceService, not by these two rules. getFlatPermissions for a student returns read on grade, report_card, and student, list and read on notice_board, and the library pair when campusId is set. It does not repeat every can() above.

A guardian uses $in on verified children. getLinkedStudentIds keeps isVerified: true only. With a non-empty linkedStudentIds, the branch grants read on student, read and list on grade and enrollment, and read on report_card with the same releasedAt window, all keyed by studentId: { $in: ctx.linkedStudentIds }. Ledger read uses accountUserId: { $in: ctx.linkedStudentUserIds }. Guardians also get the applicant rules (create on application, and read, list, update, and delete where userId is their own), list and read on campus, notice_board, and their own user and guardian profile. Campus terms use linkedCampusIds. An empty link list adds none of the child rules.

Staff get the base grants in the branch below, then derived teaching and department grants, then role grants:

apps/server/src/app/auth/ability/ability-factory.service.ts
case UserType.STAFF:
  can(Action.READ, Resource.USER, { id: ctx.userId });
  can(Action.READ, Resource.LEDGER, { accountUserId: ctx.userId });
  if (ctx.staffProfileId) {
    can(Action.LIST, Resource.STAFF);
    can(Action.READ, Resource.STAFF, { id: ctx.staffProfileId });
    can(Action.UPDATE, Resource.STAFF, { id: ctx.staffProfileId });
    can(Action.UPDATE, Resource.USER, { id: ctx.userId });
    can(Action.LIST, Resource.USER);
    can(Action.LIST, Resource.CAMPUS);
    can(Action.READ, Resource.CAMPUS);
    can(Action.LIST, Resource.DEPARTMENT);
    can(Action.LIST, Resource.ROLE);
    can(Action.LIST, Resource.ACADEMIC_YEAR);
    can(Action.READ, Resource.ACADEMIC_YEAR);
    can(Action.LIST, Resource.CAMPUS_TERM);
    can(Action.READ, Resource.CAMPUS_TERM);
    can(Action.LIST, Resource.SUBJECT);
    can(Action.READ, Resource.SUBJECT);
  }
  this.applyDerivedStaffAbilities(ctx.departmentAssignments ?? [], ctx.teachingPairs ?? [], can);
  this.applyStaffAbilities(
    ctx.roleAssignments,
    ctx.departmentAssignments,
    ctx.teachingPairs ?? [],
    ctx.classTeacherPairs ?? [],
    can,
  );
  break;

applyDerivedStaffAbilities grants manage on cbt_exam for each teaching pair, read on the staff member’s own departments, and approve on scheme_of_work for a department head. Role grants still go through applyStaffAbilities. A manage on all inside that method returns immediately.

Finally buildAbility calls build(), runs the rule list through mergeCaslRules, and returns a fresh createMongoAbility. That returned object is the AppAbility: the single source of truth for the rest of the request.

The staff branch is where role-driven power lives

For students and guardians, buildAbility is the whole story: read the branch and you know exactly what they can do. For staff, the interesting part happens inside applyStaffAbilities, which is where assignments become campus-scoped rules.

Where to go next

On this page