Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Protect asset create endpoint #263

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion server/src/assets/assets.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
Request,
} from '@nestjs/common';
import { CookieAuthGuard } from '../auth/guards/cookie-auth.guard';
import { IsOrgAuthGuard } from '../auth/guards/is-org-auth.guard';
import { DeleteResult } from 'typeorm';

import type { Request as ExpressRequest } from 'express';
Expand All @@ -28,7 +29,7 @@ import { User } from '../users/entities/user.entity';
export class AssetsController {
constructor(private readonly assetsService: AssetsService) {}

@UseGuards(CookieAuthGuard)
@UseGuards(IsOrgAuthGuard)
@Post()
async create(
@Request() request: ExpressRequest,
Expand Down
4 changes: 3 additions & 1 deletion server/src/assets/assets.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

import { AssetsService } from './assets.service';
import { AssetsController } from './assets.controller';
import { Asset } from './entities/asset.entity';
import { AuthModule } from '../auth/auth.module';
import { UserOrganizationsModule } from '../user-org/user-org.module';

@Module({
imports: [TypeOrmModule.forFeature([Asset]), AuthModule],
imports: [TypeOrmModule.forFeature([Asset]), UserOrganizationsModule, AuthModule],
controllers: [AssetsController],
providers: [AssetsService],
exports: [AssetsService],
Expand Down
2 changes: 1 addition & 1 deletion server/src/assets/dto/create-asset.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class CreateAssetDto {
@IsNotEmpty()
description: string;

@IsOptional()
@IsNotEmpty()
quantity: number;

@IsOptional()
Expand Down
3 changes: 3 additions & 0 deletions server/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { UsersModule } from '../users/users.module';
import { LoginStrategy } from './strategies/login.strategy';
import { CookieStrategy } from './strategies/cookie.strategy';
import { WSCookieStrategy } from './strategies/ws-cookie..strategy';
// import { UserOrganizationsService } from '../user-org/user-org.service';
import { UserOrganizationsModule } from '../user-org/user-org.module';

@Module({
controllers: [AuthController],
Expand All @@ -19,6 +21,7 @@ import { WSCookieStrategy } from './strategies/ws-cookie..strategy';
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '60s' },
}),
UserOrganizationsModule,
],
providers: [AuthService, LoginStrategy, CookieStrategy, WSCookieStrategy],
})
Expand Down
1 change: 0 additions & 1 deletion server/src/auth/guards/cookie-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Observable } from 'rxjs';
import { JwtService } from '@nestjs/jwt';

import { COOKIE_KEY } from '../constants';
Expand Down
46 changes: 46 additions & 0 deletions server/src/auth/guards/is-org-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { JwtService } from '@nestjs/jwt';

import { COOKIE_KEY } from '../constants';
import { CookieStrategy } from '../strategies/cookie.strategy';
import { UserOrganizationsService } from '../../user-org/user-org.service';

import type { User } from '../../users/entities/user.entity';

@Injectable()
export class IsOrgAuthGuard extends AuthGuard() {
constructor(private jwtService: JwtService, private userOrgService: UserOrganizationsService) {
super({ defaultStrategy: CookieStrategy });
}

async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const jwt = request.signedCookies[COOKIE_KEY];

if (!jwt) {
return false;
}

let user: User = {} as User;
try {
user = await this.jwtService.verify(jwt, { secret: process.env.JWT_SECRET });
const userOrgs = await this.userOrgService.getAllByUserId(user.id);

// check that the user has an org to post on behalf of
// check that there is only 1 org (temp)
// temp - only allow posts from users that only have 1 org
// - created relationship as many to many for future fleixbility
// but only want a 1to1 user<>org relationship for now
if (userOrgs.length !== 1) {
return false;
}

request.user = user;

return true;
} catch (_e) {
return false;
}
}
}
11 changes: 11 additions & 0 deletions server/src/user-org/user-org.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,17 @@ export class UserOrganizationsService {
return userOrg;
}

async getAllByUserId(userId: number): Promise<UserOrganization[]> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder that relations do this for us. I.e, we already have a method on the user entity, user.organizations, that does the same thing as this method.

const userOrgs = await this.userOrganizationsRepository.find({
where: {
user: {
id: userId,
},
},
});
return userOrgs;
}

async update(
id: number,
updateUserOrganizationsDto: UpdateUserOrganizationDto,
Expand Down
3 changes: 2 additions & 1 deletion server/test/assets/assets.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { CreateUserDto } from '../../src/users/dto/create-user.dto';
import { UsersModule } from '../../src/users/users.module';
import { UsersService } from '../../src/users/users.service';
import { AuthModule } from '../../src/auth/auth.module';
import { UserOrganizationsModule } from '../../src/user-org/user-org.module';
import * as cookieParser from 'cookie-parser';

describe('AssetsController', () => {
Expand All @@ -28,7 +29,7 @@ describe('AssetsController', () => {

beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [AssetsModule, UsersModule, AuthModule, TypeOrmModule.forRoot(TEST_DB_OPTIONS)],
imports: [AssetsModule, UsersModule, AuthModule, TypeOrmModule.forRoot(TEST_DB_OPTIONS), UserOrganizationsModule],
controllers: [AssetsController],
providers: [{ provide: getRepositoryToken(Asset), useClass: Repository }],
}).compile();
Expand Down