Skip to content

Commit

Permalink
feat: adding knownError flag
Browse files Browse the repository at this point in the history
* feat: adding knownError flag
  • Loading branch information
YazeedLoonat committed May 15, 2023
1 parent 915fad3 commit 1dd9abb
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 14 deletions.
6 changes: 5 additions & 1 deletion backend/core/src/auth/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
ValidationPipe,
Body,
Get,
BadRequestException,
} from "@nestjs/common"
import { LocalMfaAuthGuard } from "../guards/local-mfa-auth.guard"
import { AuthService } from "../services/auth.service"
Expand Down Expand Up @@ -84,7 +85,10 @@ export class AuthController {
@Response({ passthrough: true }) res: ExpressResponse
): Promise<StatusDto> {
if (!req?.cookies[REFRESH_COOKIE_NAME]) {
throw new Error("No refresh token sent with request")
throw new BadRequestException({
message: "No refresh token sent with request",
knownError: true,
})
}
return mapTo(
StatusDto,
Expand Down
5 changes: 4 additions & 1 deletion backend/core/src/auth/passport-strategies/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ export class JwtStrategy extends PassportStrategy(Strategy) {

if (user && UserService.isPasswordOutdated(user)) {
throw new HttpException(
USER_ERRORS.PASSWORD_OUTDATED.message,
{
message: USER_ERRORS.PASSWORD_OUTDATED.message,
knownError: true,
},
USER_ERRORS.PASSWORD_OUTDATED.status
)
}
Expand Down
14 changes: 11 additions & 3 deletions backend/core/src/auth/passport-strategies/local-mfa.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,20 @@ export class LocalMfaStrategy extends PassportStrategy(Strategy, "localMfa") {

if (!user.confirmedAt) {
throw new HttpException(
USER_ERRORS.ACCOUNT_NOT_CONFIRMED.message,
{
message: USER_ERRORS.ACCOUNT_NOT_CONFIRMED.message,
knownError: true,
},
USER_ERRORS.ACCOUNT_NOT_CONFIRMED.status
)
}

if (UserService.isPasswordOutdated(user)) {
throw new HttpException(
USER_ERRORS.PASSWORD_OUTDATED.message,
{
message: USER_ERRORS.PASSWORD_OUTDATED.message,
knownError: true,
},
USER_ERRORS.PASSWORD_OUTDATED.status
)
}
Expand All @@ -85,7 +91,7 @@ export class LocalMfaStrategy extends PassportStrategy(Strategy, "localMfa") {
if (!loginDto.mfaCode || !user.mfaCode || !user.mfaCodeUpdatedAt) {
user.failedLoginAttemptsCount = 0
await this.userRepository.save(user)
throw new UnauthorizedException({ name: "mfaCodeIsMissing" })
throw new UnauthorizedException({ name: "mfaCodeIsMissing", knownError: true })
} else if (
new Date(
user.mfaCodeUpdatedAt.getTime() + this.configService.get<number>("MFA_CODE_VALID_MS")
Expand Down Expand Up @@ -117,6 +123,7 @@ export class LocalMfaStrategy extends PassportStrategy(Strategy, "localMfa") {
this.configService.get<number>("AUTH_LOCK_LOGIN_AFTER_FAILED_ATTEMPTS") +
1 -
user.failedLoginAttemptsCount,
knownError: true,
})
} else if (mfaAuthSuccessful) {
return user
Expand All @@ -127,6 +134,7 @@ export class LocalMfaStrategy extends PassportStrategy(Strategy, "localMfa") {
this.configService.get<number>("AUTH_LOCK_LOGIN_AFTER_FAILED_ATTEMPTS") +
1 -
user.failedLoginAttemptsCount,
knownError: true,
})
}
}
Expand Down
9 changes: 5 additions & 4 deletions backend/core/src/auth/services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable } from "@nestjs/common"
import { BadRequestException, Injectable } from "@nestjs/common"
import { JwtService } from "@nestjs/jwt"
import { InjectRepository } from "@nestjs/typeorm"
import { Repository } from "typeorm"
Expand Down Expand Up @@ -66,9 +66,10 @@ export class AuthService {
res.clearCookie(REFRESH_COOKIE_NAME, REFRESH_COOKIE_OPTIONS)
res.clearCookie(ACCESS_TOKEN_AVAILABLE_NAME, ACCESS_TOKEN_AVAILABLE_OPTIONS)

throw new Error(
"Someone is attempting to use an outdated refresh token to generate new tokens"
)
throw new BadRequestException({
message: "Someone is attempting to use an outdated refresh token to generate new tokens",
knownError: true,
})
}
}

Expand Down
11 changes: 8 additions & 3 deletions backend/core/src/auth/services/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,10 @@ export class UserService {
try {
token = decode(dto.token, process.env.APP_SECRET)
} catch (e) {
throw new HttpException(USER_ERRORS.TOKEN_EXPIRED.message, USER_ERRORS.TOKEN_EXPIRED.status)
throw new HttpException(
{ message: USER_ERRORS.TOKEN_EXPIRED.message, knownError: true },
USER_ERRORS.TOKEN_EXPIRED.status
)
}

const user = await this.userRepository.findById(token.id)
Expand Down Expand Up @@ -283,7 +286,6 @@ export class UserService {
await this.setHitConfirmationURl(user, dto.token)
return true
} catch (e) {
console.error("isUserConfirmationTokenValid error = ", e)
try {
const user = await this.userRepository.findByConfirmationToken(dto.token)
await this.setHitConfirmationURl(user, dto.token)
Expand Down Expand Up @@ -368,7 +370,10 @@ export class UserService {
})
} else {
// existing user && ((partner user -> trying to recreate user) || (public user -> trying to recreate a public user))
throw new HttpException(USER_ERRORS.EMAIL_IN_USE.message, USER_ERRORS.EMAIL_IN_USE.status)
throw new HttpException(
{ message: USER_ERRORS.EMAIL_IN_USE.message, knownError: true },
USER_ERRORS.EMAIL_IN_USE.status
)
}
}
const newUser = await this.userRepository.save(dto)
Expand Down
9 changes: 7 additions & 2 deletions backend/core/src/shared/filters/catch-all-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@ import { BaseExceptionFilter } from "@nestjs/core"
@Catch()
export class CatchAllFilter extends BaseExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
console.error({ message: exception?.response?.message, stack: exception.stack, exception })
if (exception?.response?.knownError) {
delete exception.response.knownError
} else {
console.error({ message: exception?.response?.message, stack: exception.stack, exception })
}

if (exception.name === "EntityNotFound") {
const response = host.switchToHttp().getResponse()
response.status(404).json({ message: exception.message })
} else if (exception.message === "tokenExpired") {
const response = host.switchToHttp().getResponse()
response.status(404).json({ message: exception.message })
} else if (exception.response === "emailInUse") {
} else if (exception?.response?.message === "emailInUse") {
const response = host.switchToHttp().getResponse()
response.status(409).json({ message: "That email is already in use" })
} else {
Expand Down

0 comments on commit 1dd9abb

Please sign in to comment.