Welcome back! In the previous lesson, you introduced authenticated user context. Bearer tokens now resolve to persisted users, ticket ownership comes from the authenticated user rather than the request body, and every protected handler can access the current user’s ID and role.
In this lesson, you’ll add authorization—the rules that determine what an authenticated customer, agent, or administrator may do. You’ll combine reusable role middleware, ticket-specific ownership checks, and PostgreSQL filtering so customers can see only their own tickets while agents and administrators can work across the full ticket collection.
Authentication, Roles, and Ownership
The access policy now has three layers:
text
Authentication ↓Which persisted user sent the request?Role authorization ↓Is this user's role allowed to perform the operation?Resource authorization ↓May this user access this particular ticket?
These layers produce different failures:
text
Missing or invalid credentials → 401 UNAUTHORIZEDValid user without required permission → 403 FORBIDDENRequested ticket does not exist → 404 TICKET_NOT_FOUND
Keeping these meanings separate helps clients understand whether they need to authenticate, use a different account, or correct the requested resource.
The Ticket Access Policy
The completed ticket API applies the following rules:
Operation
Customer
Agent
Admin
List tickets
Own tickets only
All tickets
All tickets
Create ticket
Yes
Yes
Yes
View ticket
Own tickets only
Any ticket
Any ticket
View or add comments
Own tickets only
Any ticket
Any ticket
View statistics
No
Yes
Yes
Generic ticket PATCH
No
Yes
Yes
Delete ticket
No
No
Yes
A customer’s ownership is determined by comparing the ticket’s requesterId with the authenticated user’s id.
Agents and administrators are not restricted by ticket ownership. Their permissions are instead controlled by role-specific middleware on operations such as statistics, updates, and deletion.
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Adding Requester Filtering to the Domain Contract
Customer collection access is enforced at the database-query level. The repository options in src/domain/ticket.ts now include an optional requester filter.
requesterId is optional because agents and administrators may list the full collection. Their repository calls omit this property.
Customer requests include the authenticated user’s ID. The repository then limits the SQL result to tickets owned by that user.
Existing filters remain independent. A customer can still combine ownership with status, priority, and text search.
The requester filter is not accepted from a query parameter. The route adds it from authenticated server context, so clients cannot request another customer’s collection by changing the URL.
This distinction is essential: query parameters describe how the current user wants to filter permitted data, while the authenticated identity defines which data they are permitted to see.
Applying Ownership Inside PostgreSQL
Authorizing Roles
Generic role checks live in src/middleware/authorize.ts. The authorizeRoles() function is a middleware factory that accepts one or more allowed roles.
export const authorizeRoles = (...allowedRoles: UserRole[]): RequestHandler => (_request, response, next) => { const user = response.locals.user as User | undefined; if (!user) { next( new AppError( 401, "UNAUTHORIZED", "Authentication is required.", ), ); return; } if (!allowedRoles.includes(user.role)) { next( new AppError( 403, "FORBIDDEN", "You do not have permission to perform this action.", ), ); return; } next(); };
authorizeRoles() does not read the Authorization header or query PostgreSQL for the token again. Authentication has already resolved the user and stored it in response.locals.user.
The missing-user branch is defensive. In the production router, authenticate runs first, but this check prevents authorization middleware from silently operating without identity context.
allowedRoles.includes(user.role) supports either one accepted role or several. The same factory can enforce admin-only or agent-and-admin access.
An authenticated user with the wrong role receives 403 FORBIDDEN, not 401. Their identity is valid; their permission is insufficient.
next() runs only after the current role appears in the allowed list.
Examples include:
authorizeRoles("agent", "admin")
and:
authorizeRoles("admin")
Separating Role Checks from Resource Checks
authorizeRoles() answers a general question:
Is this user’s role allowed to perform this type of action?
It does not answer:
Does this customer own the particular ticket in the URL?
That second responsibility belongs to requireTicketAccess.
Separating them keeps the middleware reusable:
Statistics require a role check but no particular ticket.
Generic updates require a role check.
Deletion requires a stricter role check.
Ticket detail and comments require ownership-aware resource access.
Loading and Authorizing One Ticket
The ticket-specific middleware also lives in src/middleware/authorize.ts.
The middleware reads the target from the route parameter rather than the request body or query string.
It loads the current PostgreSQL row before applying ownership rules.
A missing row produces 404 TICKET_NOT_FOUND.
The repository lookup remains parameterized through findTicketById().
After loading the ticket, the middleware checks the authenticated user.
const user = response.locals.user as User | undefined;if (!user) { next( new AppError( 401, "UNAUTHORIZED", "Authentication is required.", ), ); return;}
The router normally guarantees this context through authenticate.
Keeping the defensive branch makes requireTicketAccess safe if it is accidentally mounted elsewhere without authentication.
Customer ownership is then enforced explicitly.
if ( user.role === "customer" && ticket.requesterId !== user.id) { next( new AppError( 403, "FORBIDDEN", "You cannot access another customer's ticket.", ), ); return;}
Ownership restrictions apply only to customers.
A customer may access the ticket when ticket.requesterId === user.id.
Agents and administrators bypass this comparison and may access any existing ticket.
The ticket is loaded before ownership is tested, preserving a clear distinction between a missing resource and a real resource the user may not access.
Once all checks succeed, the authorized resource is stored for downstream handlers.
response.locals.ticket = ticket;next();
Later handlers can reuse the loaded ticket rather than querying PostgreSQL again.
This prevents duplicate work and ensures the route returns the same representation that was used for the access decision.
Mounting Authentication Once
The ticket router now applies authentication at the router level in src/routes/ticket-routes.ts.
The order ensures authentication establishes identity once, authorization blocks disallowed actions, and repositories run only when earlier policy checks succeed.
Testing Customer Collection Scoping
Keep the API Simulator base URL set to:
http://localhost:4000
In the Authorization tab, select Bearer Token and enter:
customer-token-1
Send:
GET /api/tickets
Every returned object should contain:
{ "requesterId": "usr_customer_1"}
You can combine the access rule with normal filters:
GET /api/tickets?status=open&priority=high&sortBy=createdAt&order=desc
The result includes only matching tickets owned by usr_customer_1.
Switch to:
agent-token-1
Send the collection request again. The agent should receive the full matching collection because no requester filter is added.
Testing Ticket Ownership
With customer-token-1, request:
GET /api/tickets/tkt_1002
If tkt_1002 belongs to usr_customer_2, the response should be:
403 FORBIDDEN
Switch to:
customer-token-2
Send the same request again. The ticket should now be accessible because its requester matches the authenticated user.
With agent-token-1 or the admin token, the same ticket is accessible regardless of requester ownership.
Testing Statistics Permissions
Use a customer token and request:
GET /api/tickets/stats
The API should return:
403 FORBIDDEN
Switch to:
agent-token-1
The same request should return 200 with the global status counts.
An administrator is also allowed.
Testing the Mutation Role Matrix
Create a disposable ticket using a customer token:
POST /api/tickets
{ "title": "Authorization lifecycle check", "description": "Used to verify ticket role policies.", "priority": "medium"}
Copy the returned ticket ID.
Using the customer token, try:
PATCH /api/tickets/<new-id>
{ "priority": "high"}
The response should be 403 FORBIDDEN. Customers cannot use the generic patch route, even for their own tickets.
Switch to agent-token-1 and send the same patch. It should return 200.
Keep the agent token and try:
DELETE /api/tickets/<new-id>
The response should be 403 FORBIDDEN.
Switch to the administrator token and repeat the delete. It should return:
204 No Content
Testing Nested Comment Access
With customer-token-1, request comments for a ticket owned by that customer:
GET /api/tickets/<owned-ticket-id>/comments
The request should succeed.
Now request comments for another customer’s ticket:
GET /api/tickets/tkt_1002/comments
The parent requireTicketAccess middleware should return 403 FORBIDDEN before listComments() runs.
Agents and administrators may list or create comments on any existing ticket.
A customer can create a comment on an owned ticket with:
POST /api/tickets/<owned-ticket-id>/comments
{ "message": "This comment inherits the parent access decision."}
The authorId in the response should match the authenticated customer.
Comparing 401, 403, and 404
Remove the Authorization header and request:
GET /api/tickets/tkt_1001
The router-wide authentication middleware returns:
401 UNAUTHORIZED
Use a valid customer token but request another customer’s ticket:
GET /api/tickets/tkt_1002
The access middleware returns:
403 FORBIDDEN
Use any valid token and request a well-formed ID that does not exist:
GET /api/tickets/tkt_missing
The access middleware returns:
404 TICKET_NOT_FOUND
These responses represent three different situations:
401 → The API cannot establish an authenticated user.403 → The API knows the user but denies the action.404 → The requested ticket row does not exist.
Recap
You’ve connected authentication, role authorization, ticket ownership, and SQL filtering into one coherent access policy.
authorizeRoles() provides reusable checks for operations such as statistics, generic updates, and deletion. requireTicketAccess loads a ticket once, distinguishes missing resources from forbidden customer access, and stores the authorized representation in response.locals.ticket.
The collection repository now accepts a server-controlled requesterId filter. Customer requests are restricted directly in PostgreSQL, while agents and administrators can query the full collection. Nested comment routes inherit both authentication and ticket-access decisions from their parent router instead of repeating them.
The API can now answer both essential security questions: who is making the request, and whether that user may access the requested operation or resource.
When requesterId exists, it becomes the first parameterized condition. For a customer request, it commonly produces requester_id = $1.
The authenticated user ID remains in the values array. It is never interpolated into the SQL string.
Later filters continue numbering from the current array length. If both requester and status are present, status becomes $2.
Conditions compose with AND, so a customer filtering by high priority receives only high-priority tickets that they own.
The text-search condition follows the same parameterized pattern.
TypeScript
if (options.q) { values.push(`%${options.q}%`); conditions.push( `(title ILIKE $${values.length} OR description ILIKE $${values.length})`, );}
One search value is reused for both title and description.
Ownership remains part of the same WHERE clause, so search cannot reveal another customer’s ticket.
The final query uses all active conditions.
const whereClause = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";const result = await query<TicketListRow>( `SELECT id, title, description, status, priority, requester_id, assignee_id, created_at, updated_at, COUNT(*) OVER()::int AS total_count FROM tickets ${whereClause} ORDER BY ${sortExpression} ${direction}, id ASC`, values,);
Filtering in PostgreSQL avoids loading all tickets and removing unauthorized rows afterward.
COUNT(*) OVER() counts only the rows visible under the complete filter set. A customer’s X-Total-Count therefore describes their own matching tickets, not the hidden global total.
Agents and administrators omit requesterId, so their query can return tickets from every requester.
TypeScript
export const authorizeRoles = (...allowedRoles: UserRole[]): RequestHandler => (_request, response, next) => { const user = response.locals.user as User | undefined; if (!user) { next( new AppError( 401, "UNAUTHORIZED", "Authentication is required.", ), ); return; } if (!allowedRoles.includes(user.role)) { next( new AppError( 403, "FORBIDDEN", "You do not have permission to perform this action.", ), ); return; } next(); };
const user = response.locals.user as User | undefined;if (!user) { next( new AppError( 401, "UNAUTHORIZED", "Authentication is required.", ), ); return;}
TypeScript
if ( user.role === "customer" && ticket.requesterId !== user.id) { next( new AppError( 403, "FORBIDDEN", "You cannot access another customer's ticket.", ), ); return;}
GET /api/tickets?status=open&priority=high&sortBy=createdAt&order=desc
text
agent-token-1
text
GET /api/tickets/tkt_1002
text
403 FORBIDDEN
text
customer-token-2
text
GET /api/tickets/stats
text
403 FORBIDDEN
text
agent-token-1
text
POST /api/tickets
JSON
{ "title": "Authorization lifecycle check", "description": "Used to verify ticket role policies.", "priority": "medium"}
text
PATCH /api/tickets/<new-id>
JSON
{ "priority": "high"}
text
DELETE /api/tickets/<new-id>
text
204 No Content
text
GET /api/tickets/<owned-ticket-id>/comments
text
GET /api/tickets/tkt_1002/comments
text
POST /api/tickets/<owned-ticket-id>/comments
JSON
{ "message": "This comment inherits the parent access decision."}
text
GET /api/tickets/tkt_1001
text
401 UNAUTHORIZED
text
GET /api/tickets/tkt_1002
text
403 FORBIDDEN
text
GET /api/tickets/tkt_missing
text
404 TICKET_NOT_FOUND
text
401 → The API cannot establish an authenticated user.403 → The API knows the user but denies the action.404 → The requested ticket row does not exist.
TypeScript
const whereClause = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";const result = await query<TicketListRow>( `SELECT id, title, description, status, priority, requester_id, assignee_id, created_at, updated_at, COUNT(*) OVER()::int AS total_count FROM tickets ${whereClause} ORDER BY ${sortExpression} ${direction}, id ASC`, values,);