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:
22
backend-api/src/app.controller.spec.ts
Normal file
22
backend-api/src/app.controller.spec.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
describe('AppController', () => {
|
||||
let appController: AppController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const app: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
}).compile();
|
||||
|
||||
appController = app.get<AppController>(AppController);
|
||||
});
|
||||
|
||||
describe('root', () => {
|
||||
it('should return "Hello World!"', () => {
|
||||
expect(appController.getHello()).toBe('Hello World!');
|
||||
});
|
||||
});
|
||||
});
|
||||
12
backend-api/src/app.controller.ts
Normal file
12
backend-api/src/app.controller.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(private readonly appService: AppService) {}
|
||||
|
||||
@Get()
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
}
|
||||
48
backend-api/src/app.module.ts
Normal file
48
backend-api/src/app.module.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import appConfig from './config/app.config';
|
||||
import databaseConfig from './config/database.config';
|
||||
import jwtConfig from './config/jwt.config';
|
||||
import { SupabaseService } from './config/supabase.service';
|
||||
import { JwtStrategy } from './auth/strategies/jwt.strategy';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import * as Joi from 'joi';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
load: [appConfig, databaseConfig, jwtConfig],
|
||||
validationSchema: Joi.object({
|
||||
NODE_ENV: Joi.string()
|
||||
.valid('development', 'production', 'test')
|
||||
.default('development'),
|
||||
PORT: Joi.number().default(3000),
|
||||
SUPABASE_URL: Joi.string().required(),
|
||||
SUPABASE_ANON_KEY: Joi.string().required(),
|
||||
SUPABASE_SERVICE_KEY: Joi.string().required(),
|
||||
JWT_SECRET: Joi.string().min(32).required(),
|
||||
}),
|
||||
}),
|
||||
PassportModule.register({ defaultStrategy: 'jwt' }),
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (configService: ConfigService) => ({
|
||||
secret: configService.get<string>('jwt.secret'),
|
||||
signOptions: {
|
||||
expiresIn: '7d' as const,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
AuthModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService, SupabaseService, JwtStrategy],
|
||||
exports: [SupabaseService, JwtModule],
|
||||
})
|
||||
export class AppModule {}
|
||||
8
backend-api/src/app.service.ts
Normal file
8
backend-api/src/app.service.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(data: unknown, ctx: ExecutionContext) => {
|
||||
const request = ctx.switchToHttp().getRequest();
|
||||
return request.user;
|
||||
},
|
||||
);
|
||||
11
backend-api/src/config/app.config.ts
Normal file
11
backend-api/src/config/app.config.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { registerAs } from '@nestjs/config';
|
||||
|
||||
export default registerAs('app', () => ({
|
||||
env: process.env.NODE_ENV || 'development',
|
||||
port: parseInt(process.env.PORT || '3000', 10),
|
||||
apiPrefix: process.env.API_PREFIX || '/api',
|
||||
cors: {
|
||||
origin: process.env.CORS_ORIGIN?.split(',') || ['http://localhost:3000'],
|
||||
credentials: true,
|
||||
},
|
||||
}));
|
||||
8
backend-api/src/config/database.config.ts
Normal file
8
backend-api/src/config/database.config.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { registerAs } from '@nestjs/config';
|
||||
|
||||
export default registerAs('database', () => ({
|
||||
supabaseUrl: process.env.SUPABASE_URL,
|
||||
supabaseAnonKey: process.env.SUPABASE_ANON_KEY,
|
||||
supabaseServiceKey: process.env.SUPABASE_SERVICE_KEY,
|
||||
databaseUrl: process.env.DATABASE_URL,
|
||||
}));
|
||||
6
backend-api/src/config/jwt.config.ts
Normal file
6
backend-api/src/config/jwt.config.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { registerAs } from '@nestjs/config';
|
||||
|
||||
export default registerAs('jwt', () => ({
|
||||
secret: process.env.JWT_SECRET,
|
||||
expiresIn: process.env.JWT_EXPIRATION || '7d',
|
||||
}));
|
||||
40
backend-api/src/config/supabase.service.ts
Normal file
40
backend-api/src/config/supabase.service.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { createClient } from '@supabase/supabase-js';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class SupabaseService {
|
||||
private supabaseClient;
|
||||
|
||||
constructor(private configService: ConfigService) {
|
||||
const supabaseUrl = this.configService.get<string>('database.supabaseUrl');
|
||||
const supabaseKey = this.configService.get<string>('database.supabaseServiceKey');
|
||||
|
||||
if (!supabaseUrl || !supabaseKey) {
|
||||
throw new Error('SUPABASE_URL and SUPABASE_SERVICE_KEY must be defined');
|
||||
}
|
||||
|
||||
this.supabaseClient = createClient(supabaseUrl, supabaseKey);
|
||||
}
|
||||
|
||||
getClient() {
|
||||
return this.supabaseClient;
|
||||
}
|
||||
|
||||
// Helper para criar usuario
|
||||
async createUser(email: string, password: string) {
|
||||
const { data, error } = await this.supabaseClient.auth.admin.createUser({
|
||||
email,
|
||||
password,
|
||||
email_confirm: true,
|
||||
});
|
||||
|
||||
if (error) throw error;
|
||||
return data.user;
|
||||
}
|
||||
|
||||
// Helper para fazer queries
|
||||
async query(table: string, method: 'select' | 'insert' | 'update' | 'delete' = 'select') {
|
||||
return this.supabaseClient.from(table)[method]();
|
||||
}
|
||||
}
|
||||
32
backend-api/src/main.ts
Normal file
32
backend-api/src/main.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
|
||||
// Validação global
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
|
||||
// CORS
|
||||
app.enableCors({
|
||||
origin: process.env.CORS_ORIGIN?.split(',') || 'http://localhost:3000',
|
||||
credentials: true,
|
||||
});
|
||||
|
||||
// API Prefix
|
||||
const port = process.env.PORT ?? 3000;
|
||||
const apiPrefix = process.env.API_PREFIX ?? '/api';
|
||||
|
||||
app.setGlobalPrefix(apiPrefix);
|
||||
await app.listen(port, '0.0.0.0', () => {
|
||||
console.log(`🚀 Server running on http://localhost:${port}${apiPrefix}`);
|
||||
});
|
||||
}
|
||||
bootstrap();
|
||||
9
backend-api/src/users/dto/create-user.dto.ts
Normal file
9
backend-api/src/users/dto/create-user.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { IsString, IsEmail } from 'class-validator';
|
||||
|
||||
export class CreateUserDto {
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@IsString()
|
||||
name?: string;
|
||||
}
|
||||
Reference in New Issue
Block a user