mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-17 05:10:31 +00:00
feat: api keys
This commit is contained in:
13
packages/server/src/modules/Auth/api-key/AuthApiKey.guard.ts
Normal file
13
packages/server/src/modules/Auth/api-key/AuthApiKey.guard.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class ApiKeyAuthGuard extends AuthGuard('apiKey') {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
canActivate(context: ExecutionContext) {
|
||||
return super.canActivate(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { HeaderAPIKeyStrategy } from 'passport-headerapikey';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthApiKeyAuthorizeService } from '../commands/AuthApiKeyAuthorization.service';
|
||||
|
||||
@Injectable()
|
||||
export class ApiKeyStrategy extends PassportStrategy(
|
||||
HeaderAPIKeyStrategy,
|
||||
'apiKey',
|
||||
) {
|
||||
constructor(
|
||||
private readonly authApiKeyAuthorizeService: AuthApiKeyAuthorizeService,
|
||||
) {
|
||||
super(
|
||||
{
|
||||
header: 'x-api-key',
|
||||
prefix: '',
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
validate(apiKey: string): unknown {
|
||||
return this.authApiKeyAuthorizeService.authorize(apiKey);
|
||||
}
|
||||
}
|
||||
23
packages/server/src/modules/Auth/api-key/MixedAuth.guard.ts
Normal file
23
packages/server/src/modules/Auth/api-key/MixedAuth.guard.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../guards/jwt.guard';
|
||||
import { ApiKeyAuthGuard } from './AuthApiKey.guard';
|
||||
|
||||
// mixed-auth.guard.ts
|
||||
@Injectable()
|
||||
export class MixedAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private jwtGuard: JwtAuthGuard,
|
||||
private apiKeyGuard: ApiKeyAuthGuard,
|
||||
) {}
|
||||
|
||||
canActivate(context: ExecutionContext) {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const apiKey = request.headers['x-api-key'];
|
||||
|
||||
if (apiKey) {
|
||||
return this.apiKeyGuard.canActivate(context);
|
||||
} else {
|
||||
return this.jwtGuard.canActivate(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user