NestJS course ยท Module 4: Authentication
PROJECT: Authentication system for the Roman legion
In this lesson4
Security legate! Consul Caesar.js entrusts you with the greatest challenge - creating a complete authentication system for the entire legion of Roman war cohorts. This will be a real Fort Knox of the provinces, combining all the skills you learned in the previous modules!
Project Specification
Functional requirements
Your system must support:
- Registration and login
- Email/password with password strength validation
- Email verification
- Social login (Google, GitHub, Facebook)
- Two-Factor Authentication (2FA)
- Session management
- JWT Access Tokens (15 min)
- Refresh Tokens (7 days) with rotation
- Multi-device support
- Session management
- Security
- Rate limiting
- Password hashing (bcrypt)
- Account lockout after failed attempts
- Suspicious activity detection
- Administration
- Role-based access control
- User management
- Audit logging
- Security monitoring
Implementation
1. Main authentication controller
// auth.controller.ts
@Controller('auth')
@ApiTags('Authentication')
export class AuthController {
constructor(
private authService: AuthService,
private passwordService: PasswordService,
private refreshTokenService: RefreshTokenService,
private twoFactorService: TwoFactorService,
private securityService: SecurityService,
) {}
@Post('register')
@Throttle(3, 300) // 3 attempts per 5 minutes
@ApiOperation({ summary: 'Register a new legionary' })
async register(
@Body() registerDto: RegisterDto,
@Headers('user-agent') userAgent: string,
@Ip() ipAddress: string,
) {
// Check if the IP is blacklisted
await this.securityService.checkIpBlacklist(ipAddress);
// Registration
const user = await this.authService.register(registerDto);
// Security logging
await this.securityService.logSecurityEvent({
type: 'user_registered',
userId: user.id,
ipAddress,
userAgent,
details: { email: user.email },
});
return {
message: 'Legionary has been registered! Check your email to activate your account.',
user: {
id: user.id,
email: user.email,
emailVerified: user.emailVerified,
},
};
}
@Post('login')
@Throttle(5, 300) // 5 attempts per 5 minutes
@UseGuards(LocalAuthGuard)
@ApiOperation({ summary: 'Legionary login' })
async login(
@Request() req,
@Body() loginDto: LoginDto,
@Headers('user-agent') userAgent: string,
@Ip() ipAddress: string,
) {
const user = req.user;
// Check if the account is locked
await this.authService.checkAccountLockout(user.id);
// Check if 2FA is required
if (user.twoFactorEnabled) {
if (!loginDto.twoFactorCode) {
return {
requiresTwoFactor: true,
tempToken: await this.twoFactorService.generateTempToken(user.id),
};
}
const isValid2FA = await this.twoFactorService.verifyCode(
user.id,
loginDto.twoFactorCode,
);
if (!isValid2FA) {
await this.securityService.logSecurityEvent({
type: 'invalid_2fa_attempt',
userId: user.id,
ipAddress,
userAgent,
});
throw new UnauthorizedException('Invalid 2FA code!');
}
}
// Generate tokens
const tokens = await this.authService.generateAuthTokens(
user,
userAgent,
ipAddress,
);
// Update login data
await this.authService.updateLoginInfo(user.id, ipAddress);
return {
message: 'Welcome to the system, legionary!',
user: {
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
role: user.role,
emailVerified: user.emailVerified,
twoFactorEnabled: user.twoFactorEnabled,
},
tokens,
};
}
@Post('logout')
@UseGuards(JwtAuthGuard)
async logout(
@Request() req,
@Body() logoutDto: LogoutDto,
@Ip() ipAddress: string,
) {
if (logoutDto.allDevices) {
await this.refreshTokenService.revokeAllUserTokens(
req.user.id,
'user_logout_all',
);
} else if (logoutDto.refreshToken) {
await this.refreshTokenService.revokeTokenByValue(
logoutDto.refreshToken,
'user_logout',
);
}
return {
message: logoutDto.allDevices
? 'Logged out from all devices'
: 'Logged out successfully',
};
}
@Post('forgot-password')
@Throttle(3, 3600) // 3 attempts per hour
async forgotPassword(
@Body() forgotDto: ForgotPasswordDto,
@Ip() ipAddress: string,
) {
await this.passwordService.sendPasswordResetEmail(
forgotDto.email,
ipAddress,
);
return {
message: 'If the account exists, instructions have been sent to the email.',
};
}
}2. Main authentication service
// auth.service.ts
@Injectable()
export class AuthService {
constructor(
@InjectRepository(User) private usersRepository: Repository<User>,
private passwordService: PasswordService,
private refreshTokenService: RefreshTokenService,
private emailService: EmailService,
private jwtService: JwtService,
) {}
async register(registerDto: RegisterDto): Promise<User> {
// Check if the user already exists
const existingUser = await this.usersRepository.findOne({
where: { email: registerDto.email },
});
if (existingUser) {
throw new ConflictException('A legionary with this email already exists in the legion!');
}
// Hash the password
const hashedPassword = await this.passwordService.hashPassword(
registerDto.password,
);
// Create the user
const user = this.usersRepository.create({
email: registerDto.email,
firstName: registerDto.firstName,
lastName: registerDto.lastName,
password: hashedPassword,
role: 'legionary', // Default role
emailVerified: false,
createdAt: new Date(),
});
const savedUser = await this.usersRepository.save(user);
// Send verification email
await this.sendEmailVerification(savedUser);
return savedUser;
}
async validateUser(email: string, password: string): Promise<User | null> {
// Find the user
const user = await this.usersRepository.findOne({
where: { email },
select: ['id', 'email', 'password', 'firstName', 'lastName', 'role',
'emailVerified', 'twoFactorEnabled', 'accountLocked', 'lockoutUntil'],
});
if (!user) {
return null;
}
// Check account lockout
if (user.accountLocked && user.lockoutUntil && user.lockoutUntil > new Date()) {
throw new UnauthorizedException(
`Account locked until ${user.lockoutUntil.toLocaleString()}`
);
}
// Check the password
const isPasswordValid = await this.passwordService.verifyPassword(
password,
user.password,
);
if (!isPasswordValid) {
await this.handleFailedLogin(user.id);
return null;
}
// Reset the failed attempts counter
await this.resetFailedLoginAttempts(user.id);
// Remove the password from the object
delete user.password;
return user;
}
async generateAuthTokens(
user: User,
userAgent: string,
ipAddress: string,
): Promise<{ accessToken: string; refreshToken: string }> {
// Access Token
const accessTokenPayload = {
sub: user.id,
email: user.email,
role: user.role,
emailVerified: user.emailVerified,
};
const accessToken = this.jwtService.sign(accessTokenPayload, {
expiresIn: '15m',
});
// Refresh Token
const refreshToken = await this.refreshTokenService.generateRefreshToken(
user.id,
userAgent,
ipAddress,
);
return { accessToken, refreshToken };
}
private async handleFailedLogin(userId: number): Promise<void> {
const maxAttempts = 5;
const lockoutDuration = 30; // minutes
// Get the number of failed attempts from the last 15 minutes
const since = new Date(Date.now() - 15 * 60 * 1000);
const failedAttempts = await this.getFailedAttemptsCount(userId, since);
if (failedAttempts >= maxAttempts) {
const lockoutUntil = new Date(Date.now() + lockoutDuration * 60 * 1000);
await this.usersRepository.update(userId, {
accountLocked: true,
lockoutUntil,
failedLoginAttempts: failedAttempts,
});
console.warn(`Account ${userId} has been locked after ${failedAttempts} failed attempts`);
}
}
private async resetFailedLoginAttempts(userId: number): Promise<void> {
await this.usersRepository.update(userId, {
accountLocked: false,
lockoutUntil: null,
failedLoginAttempts: 0,
});
}
async updateLoginInfo(userId: number, ipAddress: string): Promise<void> {
await this.usersRepository.update(userId, {
lastLoginAt: new Date(),
lastLoginIp: ipAddress,
});
}
}Tasks to complete
Part 1: Basic implementation (4-6 hours)
- Create all entities with relations
- Implement registration with email validation
- Add login with JWT
- Implement refresh tokens
- Add email verification
Part 2: Security (3-4 hours)
- Add rate limiting
- Implement account lockout
- Add password reset
- Implement security monitoring
- Add audit logging
Part 3: Two-Factor Authentication (2-3 hours)
- Implement TOTP (Google Authenticator)
- Add backup codes
- Create QR codes for configuration
- Add 2FA management in the user panel
Part 4: Social Login (2-3 hours)
- Integrate Google OAuth
- Add GitHub OAuth
- Implement social account linking
- Add connected accounts management
Part 5: Administration and monitoring (2-3 hours)
- Create an admin panel
- Add user management
- Implement security reports
- Add real-time activity monitoring
Part 6: Tests (2-3 hours)
- Write unit tests for all services
- Add integration tests
- Create e2e tests for main flows
- Add performance tests
Evaluation criteria
Functionality - All requirements implemented correctly Security - Best security practices applied Code - Clean, well-organized code following best practices Tests - High test coverage, different test types Documentation - Complete API documentation and installation instructions Performance - Query and performance optimization Monitoring - Security logging and monitoring
This is the greatest challenge in the entire NestJS course! Good luck, security legate. Your legion counts on an impenetrable protection system!
Code for this lesson: src/auth/complete-auth-system.ts
// PROJECT: Complete Authentication System
// Combine all elements into one working system
import { Module, Controller, Post, Get, Body, UseGuards, Request } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
// ============================================
// 1. AuthService - the heart of the system
// ============================================
@Injectable()
class AuthService {
private users: any[] = [];
constructor(private jwtService: JwtService) {}
// TODO: Implement registration
async register(username: string, password: string) {
// TODO: Check whether the user already exists
// TODO: Hash the password (bcrypt)
// TODO: Save the user
// TODO: Return confirmation
return { message: 'TODO: implementation' };
}
// TODO: Implement login
async login(username: string, password: string) {
// TODO: Find the user
// TODO: Check the password
// TODO: Generate a JWT token
// TODO: Return { accessToken, user }
return { accessToken: '', user: {} };
}
// TODO: Implement token validation
async validateToken(payload: any) {
// TODO: Find the user by payload.sub
// TODO: Return user or null
return null;
}
}
// ============================================
// 2. AuthController - endpoints
// ============================================
@Controller('auth')
class AuthController {
constructor(private authService: AuthService) {}
@Post('register')
async register(@Body() body: { username: string; password: string }) {
return this.authService.register(body.username, body.password);
}
@Post('login')
async login(@Body() body: { username: string; password: string }) {
return this.authService.login(body.username, body.password);
}
// TODO: Add @UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@Request() req: any) {
return { user: req.user };
}
}
// ============================================
// 3. AuthModule - configuration
// ============================================
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: 'spqr-secret-imperium',
signOptions: { expiresIn: '24h' },
}),
],
providers: [AuthService],
controllers: [AuthController],
exports: [AuthService],
})
class AuthModule {}
console.log('=== Complete Authentication System ===');
console.log('1. Register: POST /auth/register');
console.log('2. Login: POST /auth/login -> JWT token');
console.log('3. Profile: GET /auth/profile (protected)');
console.log('Combine: AuthService + JwtStrategy + Guards');
Docs entries used in this lesson
Spotted a mistake in this lesson?