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
JavaScript
"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';
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') ? ` ` : '';
const swaggerOperations = config.extras.includes('swagger') ? {
register: `
`,
login: `
`,
profile: `
`
} : { 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}
export class AuthController {
constructor(private readonly authService: AuthService) {}
${swaggerOperations.register}
async register( registerDto: RegisterDto) {
return this.authService.register(registerDto);
}
${swaggerOperations.login}
async login( req, loginDto: LoginDto) {
return this.authService.login(req.user);
}
${swaggerOperations.profile}
async getProfile( 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';
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';
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';
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';
export class LocalAuthGuard extends AuthGuard('local') {}
`,
jwt: `import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
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 {
name: string;
email: string;
password: string;
}
`,
login: `import { IsEmail, IsString } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class LoginDto {
email: string;
password: string;
}
`
};
}
//# sourceMappingURL=auth.js.map