import { CanActivate, ExecutionContext, Injectable, ForbiddenException } from '@nestjs/common';

@Injectable()
export class MtlsGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();

    // 在Kong网关层完成mTLS验证后，通过header传递证书信息
    const clientCert = request.headers['x-client-cert-dn'];
    const clientCertVerified = request.headers['x-client-cert-verified'];

    if (clientCertVerified !== 'SUCCESS' || !clientCert) {
      throw new ForbiddenException('mTLS client certificate required');
    }

    request.clientCertDN = clientCert;
    return true;
  }
}
