initial: Backend Auth Module + Design System + Complete Documentation
- Setup NestJS with TypeScript, ConfigModule, JWT authentication - Implemented Auth Module with signup, login, logout endpoints - Created DTOs with validation (SignupDto, LoginDto) - JWT Strategy with Passport integration for token validation - JwtAuthGuard for route protection with Bearer tokens - CurrentUser decorator for dependency injection - Supabase integration for user management and auth - Complete API documentation (API.md) with all endpoints - Design System for Web (Next.js + Tailwind) and Mobile (Flutter) - Comprehensive project documentation and roadmap - Environment configuration with Joi schema validation - Ready for Tasks Module and RLS implementation
This commit is contained in:
75
backend-api/src/auth/auth.controller.ts
Normal file
75
backend-api/src/auth/auth.controller.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Body,
|
||||
Get,
|
||||
UseGuards,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { SignupDto } from './dto/signup.dto';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { JwtAuthGuard } from './guards/jwt.guard';
|
||||
import { CurrentUser } from '../common/decorators/current-user.decorator';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
/**
|
||||
* POST /auth/signup
|
||||
* Registrar novo usuário
|
||||
*/
|
||||
@Post('signup')
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
async signup(@Body() signupDto: SignupDto) {
|
||||
return this.authService.signup(signupDto);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /auth/login
|
||||
* Fazer login
|
||||
*/
|
||||
@Post('login')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async login(@Body() loginDto: LoginDto) {
|
||||
return this.authService.login(loginDto);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /auth/logout
|
||||
* Fazer logout
|
||||
*/
|
||||
@Post('logout')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async logout(@CurrentUser() user: any) {
|
||||
return this.authService.logout(user.userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /auth/me
|
||||
* Obter dados do usuário autenticado
|
||||
*/
|
||||
@Get('me')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
async getProfile(@CurrentUser() user: any) {
|
||||
return {
|
||||
userId: user.userId,
|
||||
email: user.email,
|
||||
iat: user.iat,
|
||||
exp: user.exp,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /auth/forgot-password
|
||||
* Solicitar reset de senha
|
||||
*/
|
||||
@Post('forgot-password')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async forgotPassword(@Body('email') email: string) {
|
||||
return this.authService.requestPasswordReset(email);
|
||||
}
|
||||
}
|
||||
11
backend-api/src/auth/auth.module.ts
Normal file
11
backend-api/src/auth/auth.module.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
|
||||
@Module({
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtStrategy],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
145
backend-api/src/auth/auth.service.ts
Normal file
145
backend-api/src/auth/auth.service.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import { Injectable, UnauthorizedException, ConflictException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { SupabaseService } from '../config/supabase.service';
|
||||
import { SignupDto } from './dto/signup.dto';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import * as crypto from 'crypto';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly supabaseService: SupabaseService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Registrar novo usuário
|
||||
*/
|
||||
async signup(signupDto: SignupDto) {
|
||||
try {
|
||||
// Criar usuário no Supabase Auth
|
||||
const user = await this.supabaseService.createUser(
|
||||
signupDto.email,
|
||||
signupDto.password,
|
||||
);
|
||||
|
||||
// Criar registro do usuário na tabela users (opcional)
|
||||
// await this.usersService.create({
|
||||
// id: user.id,
|
||||
// email: user.email,
|
||||
// name: signupDto.name,
|
||||
// });
|
||||
|
||||
// Gerar token JWT
|
||||
const token = this.generateToken(user.id, user.email);
|
||||
|
||||
return {
|
||||
access_token: token,
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
email_confirmed_at: user.email_confirmed_at,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
if (error.message?.includes('already registered')) {
|
||||
throw new ConflictException('Email já está registrado');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fazer login
|
||||
*/
|
||||
async login(loginDto: LoginDto) {
|
||||
try {
|
||||
const supabase = this.supabaseService.getClient();
|
||||
|
||||
const { data, error } = await supabase.auth.signInWithPassword({
|
||||
email: loginDto.email,
|
||||
password: loginDto.password,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw new UnauthorizedException('Email ou senha incorretos');
|
||||
}
|
||||
|
||||
// Gerar token JWT customizado
|
||||
const token = this.generateToken(data.user.id, data.user.email);
|
||||
|
||||
return {
|
||||
access_token: token,
|
||||
user: {
|
||||
id: data.user.id,
|
||||
email: data.user.email,
|
||||
email_confirmed_at: data.user.email_confirmed_at,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
throw new UnauthorizedException('Email ou senha incorretos');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fazer logout (validação do token)
|
||||
*/
|
||||
async logout(userId: string) {
|
||||
// Em um sistema real, você poderia adicionar o token a uma blacklist
|
||||
// Por enquanto, apenas validamos que o usuário tem um token válido
|
||||
return { message: 'Logout realizado com sucesso' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Validar token e retornar dados do usuário
|
||||
*/
|
||||
async validateToken(token: string) {
|
||||
try {
|
||||
const decoded = this.jwtService.verify(token);
|
||||
return decoded;
|
||||
} catch (error) {
|
||||
throw new UnauthorizedException('Token inválido ou expirado');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gerar token JWT
|
||||
*/
|
||||
private generateToken(userId: string, email: string): string {
|
||||
const payload = {
|
||||
sub: userId,
|
||||
email: email,
|
||||
iat: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
|
||||
return this.jwtService.sign(payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recuperar senha (envia email com link de reset)
|
||||
*/
|
||||
async requestPasswordReset(email: string) {
|
||||
try {
|
||||
const supabase = this.supabaseService.getClient();
|
||||
|
||||
const { error } = await supabase.auth.resetPasswordForEmail(email, {
|
||||
redirectTo: `${process.env.FRONTEND_URL || 'http://localhost:3000'}/reset-password`,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return {
|
||||
message: 'Email de recuperação enviado. Verifique sua caixa de entrada.',
|
||||
};
|
||||
} catch (error) {
|
||||
// Não revelar se o email existe ou não por segurança
|
||||
return {
|
||||
message: 'Se o email existir, você receberá um link de recuperação.',
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
10
backend-api/src/auth/dto/login.dto.ts
Normal file
10
backend-api/src/auth/dto/login.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password: string;
|
||||
}
|
||||
13
backend-api/src/auth/dto/signup.dto.ts
Normal file
13
backend-api/src/auth/dto/signup.dto.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class SignupDto {
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password: string;
|
||||
|
||||
@IsString()
|
||||
name?: string;
|
||||
}
|
||||
5
backend-api/src/auth/guards/jwt.guard.ts
Normal file
5
backend-api/src/auth/guards/jwt.guard.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {}
|
||||
24
backend-api/src/auth/strategies/jwt.strategy.ts
Normal file
24
backend-api/src/auth/strategies/jwt.strategy.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(private configService: ConfigService) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: configService.get<string>('jwt.secret'),
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: any) {
|
||||
return {
|
||||
userId: payload.sub,
|
||||
email: payload.email,
|
||||
iat: payload.iat,
|
||||
exp: payload.exp,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user