Kurs NestJS · Moduł 4: Uwierzytelnianie

PROJEKT: System autentyfikacji dla legionu rzymskich kohort

6 min czytania ·
W tej lekcji4

legacie bezpieczeństwa! Konsul Caesar.js powierza ci największe wyzwanie - stworzenie kompletnego systemu autentyfikacji dla całego legionu rzymskich kohort. To będzie prawdziwy Fort Knox Imperium, łączący wszystkie umiejętności, które poznałeś w poprzednich modułach!

Specyfikacja Projektu

Wymagania funkcjonalne

Twój system musi obsługiwać:

  1. Rejestracja i logowanie
  • Email/hasło z walidacją siły hasła
  • Weryfikacja email
  • Social login (Google, GitHub, Facebook)
  • Two-Factor Authentication (2FA)
  1. Zarządzanie sesjami
  • JWT Access Tokens (15 min)
  • Refresh Tokens (7 dni) z rotacją
  • Multi-device support
  • Session management
  1. Bezpieczeństwo
  • Rate limiting
  • Password hashing (bcrypt)
  • Account lockout po nieudanych próbach
  • Suspicious activity detection
  1. Administracja
  • Role-based access control
  • User management
  • Audit logging
  • Security monitoring

Implementacja

1. Główny kontroler autentyfikacji

// 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 próby na 5 minut
 @ApiOperation({ summary: 'Rejestracja nowego legionariusza' })
 async register(
 @Body() registerDto: RegisterDto,
 @Headers('user-agent') userAgent: string,
 @Ip() ipAddress: string,
 ) {
 // Sprawdź czy IP nie jest zablokowany
 await this.securityService.checkIpBlacklist(ipAddress);

 // Rejestracja
 const user = await this.authService.register(registerDto);

 // Logowanie bezpieczeństwa
 await this.securityService.logSecurityEvent({
 type: 'user_registered',
 userId: user.id,
 ipAddress,
 userAgent,
 details: { email: user.email },
 });

 return {
 message: 'Legionariusz został zarejestrowany! Sprawdź email aby aktywować konto.',
 user: {
 id: user.id,
 email: user.email,
 emailVerified: user.emailVerified,
 },
 };
 }

 @Post('login')
 @Throttle(5, 300) // 5 prób na 5 minut
 @UseGuards(LocalAuthGuard)
 @ApiOperation({ summary: 'Logowanie legionariusza' })
 async login(
 @Request() req,
 @Body() loginDto: LoginDto,
 @Headers('user-agent') userAgent: string,
 @Ip() ipAddress: string,
 ) {
 const user = req.user;

 // Sprawdź czy konto nie jest zablokowane
 await this.authService.checkAccountLockout(user.id);

 // Sprawdź czy wymagana jest 2FA
 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('Nieprawidłowy kod 2FA!');
 }
 }

 // Generuj tokeny
 const tokens = await this.authService.generateAuthTokens(
 user,
 userAgent,
 ipAddress,
 );

 // Aktualizuj dane logowania
 await this.authService.updateLoginInfo(user.id, ipAddress);

 return {
 message: 'Witaj w legionie, legionisto!',
 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
 ? 'Wylogowano ze wszystkich urządzeń'
 : 'Wylogowano pomyślnie',
 };
 }

 @Post('forgot-password')
 @Throttle(3, 3600) // 3 próby na godzinę
 async forgotPassword(
 @Body() forgotDto: ForgotPasswordDto,
 @Ip() ipAddress: string,
 ) {
 await this.passwordService.sendPasswordResetEmail(
 forgotDto.email,
 ipAddress,
 );

 return {
 message: 'Jeśli konto istnieje, instrukcje zostały wysłane na email.',
 };
 }
}

2. Serwis główny autentyfikacji

// 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> {
 // Sprawdź czy user już istnieje
 const existingUser = await this.usersRepository.findOne({
 where: { email: registerDto.email },
 });

 if (existingUser) {
 throw new ConflictException('Legionariusz z tym emailem już istnieje w legionie!');
 }

 // Hashuj hasło
 const hashedPassword = await this.passwordService.hashPassword(
 registerDto.password,
 );

 // Utwórz użytkownika
 const user = this.usersRepository.create({
 email: registerDto.email,
 firstName: registerDto.firstName,
 lastName: registerDto.lastName,
 password: hashedPassword,
 role: 'legionary', // Domyślna rola
 emailVerified: false,
 createdAt: new Date(),
 });

 const savedUser = await this.usersRepository.save(user);

 // Wyślij email weryfikacyjny
 await this.sendEmailVerification(savedUser);

 return savedUser;
 }

 async validateUser(email: string, password: string): Promise<User | null> {
 // Znajdź użytkownika
 const user = await this.usersRepository.findOne({
 where: { email },
 select: ['id', 'email', 'password', 'firstName', 'lastName', 'role',
 'emailVerified', 'twoFactorEnabled', 'accountLocked', 'lockoutUntil'],
 });

 if (!user) {
 return null;
 }

 // Sprawdź blokadę konta
 if (user.accountLocked && user.lockoutUntil && user.lockoutUntil > new Date()) {
 throw new UnauthorizedException(
 `Konto zablokowane do ${user.lockoutUntil.toLocaleString()}`
 );
 }

 // Sprawdź hasło
 const isPasswordValid = await this.passwordService.verifyPassword(
 password,
 user.password,
 );

 if (!isPasswordValid) {
 await this.handleFailedLogin(user.id);
 return null;
 }

 // Reset licznika nieudanych prób
 await this.resetFailedLoginAttempts(user.id);

 // Usuń hasło z obiektu
 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; // minut

 // Pobierz liczbę nieudanych prób z ostatnich 15 minut
 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(`Konto ${userId} zostało zablokowane po ${failedAttempts} nieudanych próbach`);
 }
 }

 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,
 });
 }
}

Zadania do wykonania

Część 1: Podstawowa implementacja (4-6 godzin)

  1. Stwórz wszystkie entity z relacjami
  2. Zaimplementuj rejestrację z walidacją email
  3. Dodaj logowanie z JWT
  4. Zaimplementuj refresh tokeny
  5. Dodaj weryfikację email

Część 2: Bezpieczeństwo (3-4 godziny)

  1. Dodaj rate limiting
  2. Zaimplementuj account lockout
  3. Dodaj password reset
  4. Zaimplementuj monitoring bezpieczeństwa
  5. Dodaj audit logging

Część 3: Two-Factor Authentication (2-3 godziny)

  1. Zaimplementuj TOTP (Google Authenticator)
  2. Dodaj backup codes
  3. Stwórz QR codes dla konfiguracji
  4. Dodaj zarządzanie 2FA w panelu użytkownika

Część 4: Social Login (2-3 godziny)

  1. Zintegruj Google OAuth
  2. Dodaj GitHub OAuth
  3. Zaimplementuj łączenie kont społecznościowych
  4. Dodaj zarządzanie połączonymi kontami

Część 5: Administracja i monitoring (2-3 godziny)

  1. Stwórz panel administratora
  2. Dodaj zarządzanie użytkownikami
  3. Zaimplementuj raporty bezpieczeństwa
  4. Dodaj monitoring aktywności w czasie rzeczywistym

Część 6: Testy (2-3 godziny)

  1. Napisz testy jednostkowe dla wszystkich serwisów
  2. Dodaj testy integracyjne
  3. Stwórz testy e2e dla głównych flow
  4. Dodaj testy wydajnościowe

Kryteria oceny

Funkcjonalność - Wszystkie wymagania zaimplementowane poprawnie Bezpieczeństwo - Zastosowane najlepsze praktyki bezpieczeństwa Kod - Czytelny, dobrze zorganizowany kod zgodny z best practices Testy - Wysokie pokrycie testami, różne typy testów Dokumentacja - Kompletna dokumentacja API i instrukcje instalacji Performance - Optymalizacja zapytań i wydajności Monitoring - Logowanie i monitorowanie bezpieczeństwa

To największe wyzwanie w całym kursie NestJS! Powodzenia, legacie bezpieczeństwa. Twój legion liczy na nieprzenikalny system ochrony!

Kod do tej lekcji: src/auth/complete-auth-system.ts
// PROJEKT: Kompletny System Authentication
// Polacz wszystkie elementy w jeden dzialajacy 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 - serce systemu
// ============================================
@Injectable()
class AuthService {
  private users: any[] = [];

  constructor(private jwtService: JwtService) {}

  // TODO: Zaimplementuj rejestracje
  async register(username: string, password: string) {
    // TODO: Sprawdz czy user juz istnieje
    // TODO: Zahashuj haslo (bcrypt)
    // TODO: Zapisz usera
    // TODO: Zwroc potwierdzenie
    return { message: 'TODO: implementacja' };
  }

  // TODO: Zaimplementuj logowanie
  async login(username: string, password: string) {
    // TODO: Znajdz usera
    // TODO: Sprawdz haslo
    // TODO: Wygeneruj JWT token
    // TODO: Zwroc { accessToken, user }
    return { accessToken: '', user: {} };
  }

  // TODO: Zaimplementuj walidacje tokenu
  async validateToken(payload: any) {
    // TODO: Znajdz usera po payload.sub
    // TODO: Zwroc usera lub null
    return null;
  }
}

// ============================================
// 2. AuthController - endpointy
// ============================================
@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: Dodaj @UseGuards(JwtAuthGuard)
  @Get('profile')
  getProfile(@Request() req: any) {
    return { user: req.user };
  }
}

// ============================================
// 3. AuthModule - konfiguracja
// ============================================
@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('=== Kompletny System Authentication ===');
console.log('1. Register: POST /auth/register');
console.log('2. Login: POST /auth/login -> JWT token');
console.log('3. Profile: GET /auth/profile (chroniony)');
console.log('Polacz: AuthService + JwtStrategy + Guards');

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Przydatne artykuły