@nestjs/common#ForbiddenException TypeScript Examples
The following examples show how to use
@nestjs/common#ForbiddenException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: content.controller.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Put('/:entryUuid')
@AuditLog('content/update')
public async update(
@Param('contentTypeUuid') contentTypeUuid: string,
@Param('entryUuid') uuid: string,
@Body() content: any,
@Request() req,
): Promise<any> {
if (!await this.permissionService.hasPermission(req.user?.uuid || req.headers.authorization, [`content/${contentTypeUuid}/update`])) {
throw new ForbiddenException(`Missing permissions: content/${contentTypeUuid}/update`)
}
return this.contentService.update(contentTypeUuid, uuid, {
...content,
updatedByUuid: req.user?.uuid
});
}
Example #2
Source File: collections.service.ts From aqualink-app with MIT License | 6 votes |
async findOne(
collectionId: number,
publicOnly: boolean = false,
): Promise<Collection> {
const collection = await this.collectionRepository.findOne({
where: { id: collectionId },
relations: [
'sites',
'sites.historicalMonthlyMean',
'sites.region',
'user',
],
});
if (!collection) {
throw new NotFoundException(
`Collection with ID ${collectionId} not found.`,
);
}
if (publicOnly && !collection.isPublic) {
throw new ForbiddenException(
`You are not allowed to access this collection with ${collectionId}`,
);
}
if (collection.sites.length === 0) {
return collection;
}
return this.processCollection(collection, collection.sites);
}
Example #3
Source File: require-ssl.middleware.ts From ironfish-api with Mozilla Public License 2.0 | 6 votes |
use(req: Request, _res: Response, next: NextFunction): void {
if (
this.config.get<string>('NODE_ENV') !== 'development' &&
req.headers['x-forwarded-proto'] !== 'https'
) {
throw new ForbiddenException({
message: '"https" is required to access the Iron Fish API',
});
}
next();
}
Example #4
Source File: auth.service.ts From mamori-i-japan-api with BSD 2-Clause "Simplified" License | 6 votes |
async adminUserlogin(requestAdminUser: RequestAdminUser): Promise<void> {
const adminObj = await this.adminsService.findOneAdminByIdInternal(requestAdminUser.uid)
if (!adminObj) {
throw new ForbiddenException('User Id does not belong to an admin')
}
if (adminObj.email !== requestAdminUser.email) {
throw new ForbiddenException('Email in access token does not match with admin in firestore')
}
// If custom claim does not exist, then add it because above validation has passed.
await this.upsertAdminCustomClaims(requestAdminUser, adminObj)
}
Example #5
Source File: topic.controller.ts From Phantom with MIT License | 6 votes |
//add pin to a certain topic
@UseGuards(AuthGuard('jwt'))
@Post('/topic/addPin')
async addPinToAtopic(
@Body('pinId') pinId: string,
@Body('topicName') topicName: string,
) {
let topics = await this.TopicService.addPinToTopic(topicName, pinId);
if (topics) return { message: 'pin has been added successfully!' };
return new ForbiddenException();
}
Example #6
Source File: auth.controller.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Post('/register')
public async register(@Body() body: any, @Request() req): Promise<any> {
// check if there already is a tenant
if (await this.tenantService.findOne()) {
throw new ForbiddenException('The installation process has already concluded')
}
if (await this.userService.findOne({ email: body.email })) {
throw new ForbiddenException('Please use a unique email')
}
const user = await this.userService.create({
uuid: uuid.v4(),
password: bcryptjs.hashSync(body.password),
email: body.email,
username: body.username,
updatedAt: new Date(),
createdAt: new Date(),
avatar: this.configService.get('app.frontendBaseUrl') + '/assets/img/logo-alternative.png',
});
req.login(user, () => {});
return { ok: true };
}
Example #7
Source File: plugin-newsletter.controller.ts From Cromwell with MIT License | 6 votes |
/**
* The same method as pluginNewsletterStats in PluginNewsletterResolver.
* Added for documentation purposes of custom Controllers.
* */
@Get('stats')
/** You can restrict route by assigning JwtAuthGuard and passing allowed roles as a decorator: */
@UseGuards(JwtAuthGuard)
@Roles('administrator', 'guest', 'author')
@ApiOperation({ description: 'Get newsletters count' })
@ApiResponse({
status: 200,
type: String,
})
@ApiForbiddenResponse({ description: 'Forbidden.' })
async getStats(@Request() request: TRequestWithUser): Promise<string> {
// Or you can retrieve user info and validate permissions in the method:
const allowedRoles: TUserRole[] = ['administrator', 'guest', 'author'];
if (!allowedRoles.includes(request.user?.role))
throw new ForbiddenException('Forbidden');
return (await getManager().find(PluginNewsletter) ?? []).length + '';
}
Example #8
Source File: content.controller.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Delete('/:entryUuid')
@AuditLog('content/delete')
public async delete(
@Param('contentTypeUuid') contentTypeUuid: string,
@Param('entryUuid') uuid: string,
@Request() req,
): Promise<void> {
if (!await this.permissionService.hasPermission(req.user?.uuid || req.headers.authorization, [`content/${contentTypeUuid}/delete`])) {
throw new ForbiddenException(`Missing permissions: content/${contentTypeUuid}/delete`)
}
return await this.contentService.delete(contentTypeUuid, uuid);
}
Example #9
Source File: auth.service.ts From nestjs-starter with MIT License | 6 votes |
async validateUser(userData: string, password: string): Promise<User> {
// Verify if userData is email or username
const data: { username?: string; email?: string } = {};
!PATTERN_VALID_EMAIL.test(userData) ? (data.username = userData) : (data.email = userData);
const user = await this.usersService.getByUser(data);
if (!user) {
throw new NotFoundException('Your account does not exist');
}
if (!user.enabled) {
throw new ForbiddenException('Account is disabled, contact with administrator');
}
const isMatch = compareSync(password, user.password);
if (!isMatch) {
throw new BadRequestException('Invalid credentials');
}
delete user.password;
return user;
}
Example #10
Source File: user-auth-guard.ts From nestjs-angular-starter with MIT License | 6 votes |
async canActivate(context: ExecutionContext): Promise<boolean> {
// First validate the user
const isUserValidated = await (<Promise<boolean>>(
this.validateAndAppendUserToRequest(context)
));
// If the user is validated, validate it's roles
if (isUserValidated) {
const userHasRoles = this.validateUserRoles(context);
// If the user don't have the required roles
if (!userHasRoles)
throw new ForbiddenException(`You don't have the required roles!`);
return true;
}
return false;
}
Example #11
Source File: oauth2.controller.ts From nestjs-oauth2-server-module with MIT License | 6 votes |
@Post('token')
async token(@Query() request: OAuth2Request): Promise<OAuth2Response> {
const client = await this.clientRepository.findByClientId(request.clientId);
if (!await this.strategyRegistry.validate(request,client)) {
throw new ForbiddenException("You are not allowed to access the given resource");
}
return await this.strategyRegistry.getOauth2Response(request, client);
}
Example #12
Source File: auth.controller.ts From nest-js-boilerplate with MIT License | 6 votes |
@ApiOkResponse({
description: 'User registered/authorized successfully',
})
@ApiInternalServerErrorResponse({
schema: {
type: 'object',
example: {
message: 'string',
details: {},
},
},
description: 'InternalServerError. User was not authorized/registered',
})
@UseGuards(GoogleAuthGuard)
@Get('redirect')
async googleAuthRedirect(@Req() req: ExpressRequest): Promise<any> {
if (!req.user) {
throw new ForbiddenException('No user from google');
}
const {
accessToken,
refreshToken,
...user
} = req.user as UserGooglePayload;
const foundUser = await this.usersService.getVerifiedUserByEmail(user.email as string);
if (!foundUser) {
await this.usersService.createIfDoesNotExist(user as UserDto);
return { message: 'Successfully registered' };
}
return { message: 'Successfully login' };
}
Example #13
Source File: forbidden-exception.filter.ts From nestjs-mercurius with MIT License | 5 votes |
@Catch(ForbiddenException)
export class ForbiddenExceptionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost): any {
const gqlHost = GqlArgumentsHost.create(host);
throw exception;
}
}
Example #14
Source File: user.service.ts From 42_checkIn with GNU General Public License v3.0 | 5 votes |
async checkIsAdmin(adminId: number) {
this.logger.debug('checkIsAdmin start');
this.logger.debug('user _id', adminId);
const admin = await this.userRepository.findOne(adminId);
if (!admin.getIsAdmin()) throw new ForbiddenException();
}
Example #15
Source File: auth.controller.ts From nest-js-boilerplate with MIT License | 5 votes |
@ApiOkResponse({
schema: {
type: 'object',
properties: {
data: {
$ref: getSchemaPath(JwtTokensDto),
},
},
},
description: '200, returns new jwt tokens',
})
@ApiUnauthorizedResponse({
schema: {
type: 'object',
example: {
message: 'string',
},
},
description: '401. Token has been expired',
})
@ApiInternalServerErrorResponse({
schema: {
type: 'object',
example: {
message: 'string',
details: {},
},
},
description: '500. InternalServerError',
})
@ApiBearerAuth()
@Post('refresh-token')
async refreshToken(
@Body() refreshTokenDto: RefreshTokenDto,
): Promise<SuccessResponseInterface | never> {
const decodedUser = this.jwtService.decode(
refreshTokenDto.refreshToken,
) as DecodedUser;
if (!decodedUser) {
throw new ForbiddenException('Incorrect token');
}
const oldRefreshToken:
| string
| null = await this.authService.getRefreshTokenByEmail(decodedUser.email);
// if the old refresh token is not equal to request refresh token then this user is unauthorized
if (!oldRefreshToken || oldRefreshToken !== refreshTokenDto.refreshToken) {
throw new UnauthorizedException(
'Authentication credentials were missing or incorrect',
);
}
const payload = {
id: decodedUser.id,
email: decodedUser.email,
};
return ResponseUtils.success(
'tokens',
await this.authService.login(payload),
);
}
Example #16
Source File: auth.errors.ts From codeclannigeria-backend with MIT License | 5 votes |
authErrors = {
INVALID_LOGIN_ATTEMPT: new UnauthorizedException(
'Email or Password is incorrect'
),
INVALID_TOKEN: new ForbiddenException('Invalid token'),
EXPIRED_TOKEN: new NotFoundException('Token expired')
}
Example #17
Source File: auth.controller.ts From nest-js-boilerplate with MIT License | 5 votes |
@ApiOkResponse({
type: UserEntity,
description: '200, returns a decoded user from access token',
})
@ApiUnauthorizedResponse({
schema: {
type: 'object',
example: {
message: 'string',
},
},
description: '403, says you Unauthorized',
})
@ApiInternalServerErrorResponse({
schema: {
type: 'object',
example: {
message: 'string',
details: {},
},
},
description: '500. InternalServerError',
})
@ApiBearerAuth()
@UseGuards(JwtAccessGuard)
@Get('token')
async getUserByAccessToken(
@AuthBearer() token: string,
): Promise<SuccessResponseInterface | never> {
const decodedUser: DecodedUser | null = await this.authService.verifyToken(
token,
this.configService.get<string>('ACCESS_TOKEN') || '<%= config.accessTokenSecret %>',
);
if (!decodedUser) {
throw new ForbiddenException('Incorrect token');
}
const { exp, iat, ...user } = decodedUser;
return ResponseUtils.success(
'users',
user,
);
}
Example #18
Source File: topic.controller.ts From Phantom with MIT License | 5 votes |
@Put('/edit')
async addImageToTopic(@Body('topics') topics: Array<object>) {
let topic = await this.TopicService.editTopic(topics);
if (topic) return topic;
return new ForbiddenException();
}
Example #19
Source File: user-password-not-valid.exception.ts From bank-server with MIT License | 5 votes |
export class UserPasswordNotValidException extends ForbiddenException {
constructor(error?: string) {
super('error.user_password_not_valid', error);
}
}
Example #20
Source File: auth.controller.ts From nest-js-boilerplate with MIT License | 5 votes |
@ApiNoContentResponse({
description: 'no content',
})
@ApiUnauthorizedResponse({
schema: {
type: 'object',
example: {
message: 'string',
},
},
description: 'Token has been expired',
})
@ApiInternalServerErrorResponse({
schema: {
type: 'object',
example: {
message: 'string',
details: {},
},
},
description: '500. InternalServerError',
})
@ApiBearerAuth()
@UseGuards(JwtAccessGuard)
@Delete('logout/:token')
@HttpCode(HttpStatus.NO_CONTENT)
async logout(@Param('token') token: string): Promise<{} | never> {
const decodedUser: DecodedUser | null = await this.authService.verifyToken(
token,
this.configService.get<string>('ACCESS_TOKEN') || '<%= config.accessTokenSecret %>',
);
if (!decodedUser) {
throw new ForbiddenException('Incorrect token');
}
const deletedUsersCount = await this.authService.deleteTokenByEmail(
decodedUser.email,
);
if (deletedUsersCount === 0) {
throw new NotFoundException();
}
return {};
}