UNPKG

js-mvc-app

Version:

A CLI tool to scaffold complete Node.js MVC projects with TypeScript, just like Laravel

248 lines (223 loc) 7.94 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getNestJSAuthModule = getNestJSAuthModule; exports.getNestJSAuthController = getNestJSAuthController; exports.getNestJSAuthService = getNestJSAuthService; exports.getNestJSAuthStrategies = getNestJSAuthStrategies; exports.getNestJSAuthGuards = getNestJSAuthGuards; exports.getNestJSAuthDTOs = getNestJSAuthDTOs; function getNestJSAuthModule(config) { return `import { Module } from '@nestjs/common'; import { JwtModule } from '@nestjs/jwt'; import { PassportModule } from '@nestjs/passport'; import { AuthService } from './auth.service'; import { AuthController } from './auth.controller'; import { UsersModule } from '../users/users.module'; import { LocalStrategy } from './strategies/local.strategy'; import { JwtStrategy } from './strategies/jwt.strategy'; @Module({ imports: [ UsersModule, PassportModule, JwtModule.register({ secret: process.env.JWT_SECRET || 'your-secret-key', signOptions: { expiresIn: '24h' }, }), ], controllers: [AuthController], providers: [AuthService, LocalStrategy, JwtStrategy], exports: [AuthService], }) export class AuthModule {} `; } function getNestJSAuthController(config) { const swaggerDecorators = config.extras.includes('swagger') ? ` import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'; ` : ''; const swaggerControllerDecorator = config.extras.includes('swagger') ? `@ApiTags('auth')` : ''; const swaggerOperations = config.extras.includes('swagger') ? { register: ` @ApiOperation({ summary: 'Register a new user' }) @ApiResponse({ status: 201, description: 'User successfully registered' }) @ApiResponse({ status: 400, description: 'Bad request' })`, login: ` @ApiOperation({ summary: 'Login user' }) @ApiResponse({ status: 200, description: 'User successfully logged in' }) @ApiResponse({ status: 401, description: 'Invalid credentials' })`, profile: ` @ApiBearerAuth() @ApiOperation({ summary: 'Get user profile' }) @ApiResponse({ status: 200, description: 'User profile retrieved' }) @ApiResponse({ status: 401, description: 'Unauthorized' })` } : { register: '', login: '', profile: '' }; return `import { Controller, Post, Get, Body, UseGuards, Request } from '@nestjs/common'; import { AuthService } from './auth.service'; import { LocalAuthGuard } from './guards/local-auth.guard'; import { JwtAuthGuard } from './guards/jwt-auth.guard'; import { RegisterDto } from './dto/register.dto'; import { LoginDto } from './dto/login.dto'; ${swaggerDecorators} ${swaggerControllerDecorator} @Controller('auth') export class AuthController { constructor(private readonly authService: AuthService) {} ${swaggerOperations.register} @Post('register') async register(@Body() registerDto: RegisterDto) { return this.authService.register(registerDto); } ${swaggerOperations.login} @UseGuards(LocalAuthGuard) @Post('login') async login(@Request() req, @Body() loginDto: LoginDto) { return this.authService.login(req.user); } ${swaggerOperations.profile} @UseGuards(JwtAuthGuard) @Get('profile') async getProfile(@Request() req) { return this.authService.getProfile(req.user.userId); } } `; } function getNestJSAuthService(config) { const { database } = config; return `import { Injectable, UnauthorizedException, ConflictException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import * as bcrypt from 'bcryptjs'; import { UsersService } from '../users/users.service'; import { RegisterDto } from './dto/register.dto'; import { User } from '../users/entities/user.entity'; @Injectable() export class AuthService { constructor( private readonly usersService: UsersService, private readonly jwtService: JwtService, ) {} async validateUser(email: string, password: string): Promise<any> { const user = await this.usersService.findByEmail(email); if (user && await bcrypt.compare(password, user.password)) { const { password, ...result } = user; return result; } return null; } async register(registerDto: RegisterDto) { const existingUser = await this.usersService.findByEmail(registerDto.email); if (existingUser) { throw new ConflictException('User with this email already exists'); } const hashedPassword = await bcrypt.hash(registerDto.password, 12); const user = await this.usersService.create({ ...registerDto, password: hashedPassword, }); const { password, ...userWithoutPassword } = user; const payload = { email: user.email, sub: ${database === 'mongodb' ? 'user._id' : 'user.id'} }; return { access_token: this.jwtService.sign(payload), user: userWithoutPassword, }; } async login(user: User) { const payload = { email: user.email, sub: ${database === 'mongodb' ? 'user._id' : 'user.id'} }; const { password, ...userWithoutPassword } = user; return { access_token: this.jwtService.sign(payload), user: userWithoutPassword, }; } async getProfile(userId: string) { return this.usersService.findById(userId); } } `; } function getNestJSAuthStrategies(config) { return { local: `import { Strategy } from 'passport-local'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common'; import { AuthService } from '../auth.service'; @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { constructor(private authService: AuthService) { super({ usernameField: 'email' }); } async validate(email: string, password: string): Promise<any> { const user = await this.authService.validateUser(email, password); if (!user) { throw new UnauthorizedException('Invalid credentials'); } return user; } } `, jwt: `import { ExtractJwt, Strategy } from 'passport-jwt'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable } from '@nestjs/common'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: process.env.JWT_SECRET || 'your-secret-key', }); } async validate(payload: any) { return { userId: payload.sub, email: payload.email }; } } ` }; } function getNestJSAuthGuards() { return { local: `import { Injectable } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Injectable() export class LocalAuthGuard extends AuthGuard('local') {} `, jwt: `import { Injectable } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Injectable() export class JwtAuthGuard extends AuthGuard('jwt') {} ` }; } function getNestJSAuthDTOs() { return { register: `import { IsEmail, IsString, MinLength, MaxLength } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; export class RegisterDto { @ApiProperty({ example: 'John Doe' }) @IsString() @MinLength(2) @MaxLength(50) name: string; @ApiProperty({ example: 'john@example.com' }) @IsEmail() email: string; @ApiProperty({ example: 'password123' }) @IsString() @MinLength(6) password: string; } `, login: `import { IsEmail, IsString } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; export class LoginDto { @ApiProperty({ example: 'john@example.com' }) @IsEmail() email: string; @ApiProperty({ example: 'password123' }) @IsString() password: string; } ` }; } //# sourceMappingURL=auth.js.map