feat(api): add authentication and identity guards
This commit is contained in:
1 parent
fb59e7721e
commit
c07438eb54
16 files changed
+592
No files matched your search
@@ -0,0 +1,55 @@
|
||||
import { ExecutionContext } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { IdentityDocument, UserDocument } from '../global/database/schema';
|
||||
import { UserResolverGuard } from './user-resolver.guard';
|
||||
import './auth-request';
|
||||
|
||||
function createContext(request: Record<string, unknown>): ExecutionContext {
|
||||
return {
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => request,
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
}
|
||||
|
||||
describe('UserResolverGuard', () => {
|
||||
it('resolves the community membership before role guards run', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const identityId = new mongoose.Types.ObjectId();
|
||||
const user = { _id: new mongoose.Types.ObjectId() } as UserDocument;
|
||||
const findOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(user),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue({ findOne }),
|
||||
} as unknown as ConnectionService;
|
||||
const request = {
|
||||
params: { communityId: communityId.toString() },
|
||||
identity: { _id: identityId } as IdentityDocument,
|
||||
};
|
||||
const guard = new UserResolverGuard(connectionService);
|
||||
|
||||
await expect(guard.canActivate(createContext(request))).resolves.toBe(true);
|
||||
|
||||
expect(findOne).toHaveBeenCalledWith({
|
||||
communityId,
|
||||
identityId,
|
||||
});
|
||||
expect(request.user).toBe(user);
|
||||
});
|
||||
|
||||
it('skips lookup when there is no resolved identity', async () => {
|
||||
const connectionService = {
|
||||
getModel: jest.fn(),
|
||||
} as unknown as ConnectionService;
|
||||
const request = {
|
||||
params: { communityId: new mongoose.Types.ObjectId().toString() },
|
||||
};
|
||||
const guard = new UserResolverGuard(connectionService);
|
||||
|
||||
await expect(guard.canActivate(createContext(request))).resolves.toBe(true);
|
||||
|
||||
expect(connectionService.getModel).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user