Browse Source

chore(api): update auth guards

pull/1/head
isra el 3 years ago
parent
commit
1aa237f255
  1. 6
      api/src/auth/auth.controller.ts
  2. 6
      api/src/auth/auth.service.ts
  3. 4
      api/src/auth/guards/auth.guard.ts
  4. 38
      api/src/auth/guards/can-modify-api-key.guard.ts
  5. 2
      api/src/gateway/gateway.controller.ts

6
api/src/auth/auth.controller.ts

@ -12,8 +12,9 @@ import {
} from '@nestjs/common' } from '@nestjs/common'
import { ApiBearerAuth, ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger' import { ApiBearerAuth, ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger'
import { LoginInputDTO, RegisterInputDTO } from './auth.dto' import { LoginInputDTO, RegisterInputDTO } from './auth.dto'
import { AuthGuard } from './auth.guard'
import { AuthGuard } from './guards/auth.guard'
import { AuthService } from './auth.service' import { AuthService } from './auth.service'
import { CanModifyApiKey } from './guards/can-modify-api-key.guard'
@ApiTags('auth') @ApiTags('auth')
@Controller('auth') @Controller('auth')
@ -69,8 +70,7 @@ export class AuthController {
return { data } return { data }
} }
// TODO: Add a guard to check if the user is the owner of the api key
@UseGuards(AuthGuard)
@UseGuards(AuthGuard, CanModifyApiKey)
@ApiOperation({ summary: 'Generate Api Key' }) @ApiOperation({ summary: 'Generate Api Key' })
@ApiBearerAuth() @ApiBearerAuth()
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)

6
api/src/auth/auth.service.ts

@ -115,10 +115,14 @@ export class AuthService {
return this.apiKeyModel.find({ user: currentUser._id }) return this.apiKeyModel.find({ user: currentUser._id })
} }
async findApiKeys(params) {
async findApiKey(params) {
return this.apiKeyModel.findOne(params) return this.apiKeyModel.findOne(params)
} }
async findApiKeyById(apiKeyId: string) {
return this.apiKeyModel.findById(apiKeyId)
}
async deleteApiKey(apiKeyId: string) { async deleteApiKey(apiKeyId: string) {
const apiKey = await this.apiKeyModel.findOne({ _id: apiKeyId }) const apiKey = await this.apiKeyModel.findOne({ _id: apiKeyId })
if (!apiKey) { if (!apiKey) {

4
api/src/auth/auth.guard.ts → api/src/auth/guards/auth.guard.ts

@ -7,7 +7,7 @@ import {
} from '@nestjs/common' } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt' import { JwtService } from '@nestjs/jwt'
import { UsersService } from 'src/users/users.service' import { UsersService } from 'src/users/users.service'
import { AuthService } from './auth.service'
import { AuthService } from '../auth.service'
import * as bcrypt from 'bcryptjs' import * as bcrypt from 'bcryptjs'
@Injectable() @Injectable()
@ -34,7 +34,7 @@ export class AuthGuard implements CanActivate {
const apiKeyStr = request.query.apiKey const apiKeyStr = request.query.apiKey
if (apiKeyStr) { if (apiKeyStr) {
var regex = new RegExp(`^${apiKeyStr.substr(0, 17)}`, 'g') var regex = new RegExp(`^${apiKeyStr.substr(0, 17)}`, 'g')
const apiKey = await this.authService.findApiKeys({
const apiKey = await this.authService.findApiKey({
apiKey: { $regex: regex }, apiKey: { $regex: regex },
}) })

38
api/src/auth/guards/can-modify-api-key.guard.ts

@ -0,0 +1,38 @@
import {
CanActivate,
ExecutionContext,
HttpException,
HttpStatus,
Injectable,
} from '@nestjs/common'
import mongoose from 'mongoose'
import { UserRole } from 'src/users/user-roles.enum'
import { AuthService } from '../auth.service'
@Injectable()
export class CanModifyApiKey implements CanActivate {
constructor(private authService: AuthService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest()
const apiKeyId = request.params.id
const userId = request.user?.id
const isValidId = mongoose.Types.ObjectId.isValid(apiKeyId)
if (!isValidId) {
throw new HttpException({ error: 'Invalid id' }, HttpStatus.BAD_REQUEST)
}
const apiKey = await this.authService.findApiKeyById(apiKeyId)
if (
!!userId &&
(apiKey?.user == userId.toString() ||
request.user?.role == UserRole.ADMIN)
) {
return true
}
throw new HttpException({ error: 'Unauthorized' }, HttpStatus.UNAUTHORIZED)
}
}

2
api/src/gateway/gateway.controller.ts

@ -9,7 +9,7 @@ import {
Get, Get,
} from '@nestjs/common' } from '@nestjs/common'
import { ApiBearerAuth, ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger' import { ApiBearerAuth, ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger'
import { AuthGuard } from 'src/auth/auth.guard'
import { AuthGuard } from 'src/auth/guards/auth.guard'
import { RegisterDeviceInputDTO, SendSMSInputDTO } from './gateway.dto' import { RegisterDeviceInputDTO, SendSMSInputDTO } from './gateway.dto'
import { GatewayService } from './gateway.service' import { GatewayService } from './gateway.service'
import { CanModifyDevice } from './guards/can-modify-device.guard' import { CanModifyDevice } from './guards/can-modify-device.guard'

Loading…
Cancel
Save