25 lines
795 B
TypeScript
25 lines
795 B
TypeScript
import { Injectable, NestMiddleware, Inject } from '@nestjs/common';
|
|
import { Request, Response, NextFunction } from 'express';
|
|
import { AbilityFactory } from '../ability.factory';
|
|
import { Knex } from 'knex';
|
|
|
|
/**
|
|
* Middleware to build and attach CASL ability to request
|
|
* Must run after authentication middleware
|
|
*/
|
|
@Injectable()
|
|
export class AbilityMiddleware implements NestMiddleware {
|
|
constructor(
|
|
private readonly abilityFactory: AbilityFactory,
|
|
@Inject('KnexConnection') private readonly knex: Knex,
|
|
) {}
|
|
|
|
async use(req: Request & { user?: any; ability?: any }, res: Response, next: NextFunction) {
|
|
if (req.user) {
|
|
// Build ability for authenticated user
|
|
req.ability = await this.abilityFactory.buildForUser(req.user, this.knex);
|
|
}
|
|
next();
|
|
}
|
|
}
|