feat: add error handling to player creation and update gitignore for agent

This commit is contained in:
Erik Silva
2026-01-24 14:18:40 -03:00
commit 416bd83ea7
93 changed files with 16861 additions and 0 deletions

72
src/lib/auth.ts Normal file
View File

@@ -0,0 +1,72 @@
import { cookies, headers } from 'next/headers'
import { prisma } from '@/lib/prisma'
export async function getActiveGroup() {
console.log('--- [AUTH CHECK START] ---')
const headerStore = await headers()
const slug = headerStore.get('x-current-slug')?.toLowerCase()
const cookieStore = await cookies()
const groupSession = cookieStore.get('group_session')?.value
const groupId = cookieStore.get('group_id')?.value
console.log(`Contexto Slug: ${slug || 'Nenhum'}`)
console.log(`Cookies: Session=${groupSession ? 'OK' : 'MISSING'}, ID=${groupId || 'MISSING'}`)
let loggedId: string | null = null
if (groupSession) {
try {
const data = JSON.parse(groupSession)
loggedId = data.id
console.log(`ID recuperado do JSON: ${loggedId}`)
} catch (e) {
console.error('[AUTH CHECK] Falha ao ler JSON da sessão')
}
}
if (!loggedId && groupId) loggedId = groupId
if (!loggedId) {
console.log(`[AUTH CHECK] Nenhum usuário logado.`)
return null
}
if (slug) {
const group = await prisma.group.findUnique({
where: { slug },
include: {
players: true,
matches: {
include: {
teams: { include: { players: { include: { player: true } } } },
attendances: { include: { player: true } }
},
orderBy: { date: 'desc' }
}
}
})
if (group && group.id === loggedId) {
if ((group as any).status === 'FROZEN') {
console.log(`[AUTH CHECK] Pelada ${slug} está CONGELADA. Acesso negado.`)
return null
}
console.log(`[AUTH CHECK] Sucesso: Acesso liberado para ${slug}`)
return group
}
console.log(`[AUTH CHECK] Falha: Token pertence ao grupo ${loggedId}, mas tentando acessar ${group?.id} (${slug})`)
return null
}
if (loggedId) {
console.log(`[AUTH CHECK] Acesso direto via ID: ${loggedId}`)
return await prisma.group.findUnique({
where: { id: loggedId },
include: { players: true }
})
}
return null
}

48
src/lib/minio.ts Normal file
View File

@@ -0,0 +1,48 @@
import * as Minio from 'minio'
export const minioClient = new Minio.Client({
endPoint: process.env.MINIO_ENDPOINT || '127.0.0.1',
port: parseInt(process.env.MINIO_PORT || '9100'),
useSSL: process.env.MINIO_USE_SSL === 'true',
accessKey: process.env.MINIO_ACCESS_KEY || 'temfut_admin',
secretKey: process.env.MINIO_SECRET_KEY || 'temfut_secret_2026',
})
export const BUCKET_NAME = process.env.MINIO_BUCKET || 'temfut'
export const ensureBucket = async () => {
console.log('--- ENSURE BUCKET START ---')
try {
console.log('Checking if bucket exists:', BUCKET_NAME)
const exists = await minioClient.bucketExists(BUCKET_NAME)
console.log('Bucket exists:', exists)
if (!exists) {
console.log(`Creating bucket: ${BUCKET_NAME}`)
await minioClient.makeBucket(BUCKET_NAME, 'us-east-1')
}
// Set bucket policy to public for viewing images (Idempotent)
const policy = {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: { AWS: ['*'] },
Action: ['s3:GetBucketLocation', 's3:ListBucket'],
Resource: [`arn:aws:s3:::${BUCKET_NAME}`],
},
{
Effect: 'Allow',
Principal: { AWS: ['*'] },
Action: ['s3:GetObject'],
Resource: [`arn:aws:s3:::${BUCKET_NAME}/*`],
},
],
}
await minioClient.setBucketPolicy(BUCKET_NAME, JSON.stringify(policy))
console.log('Bucket policy set to public.')
} catch (error) {
console.error('ERROR IN ENSURE_BUCKET:', error)
throw error
}
}

9
src/lib/prisma.ts Normal file
View File

@@ -0,0 +1,9 @@
import { PrismaClient } from '@prisma/client'
const globalForPrisma = global as unknown as { prisma: PrismaClient }
export const prisma =
globalForPrisma.prisma ||
new PrismaClient()
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma

31
src/lib/upload.ts Normal file
View File

@@ -0,0 +1,31 @@
import { minioClient, BUCKET_NAME, ensureBucket } from '@/lib/minio'
import { v4 as uuidv4 } from 'uuid'
export async function uploadFile(file: File): Promise<string> {
console.log('--- START UPLOAD ---')
console.log('File name:', file.name)
console.log('File size:', file.size)
await ensureBucket()
const buffer = Buffer.from(await file.arrayBuffer())
const sanitizedName = file.name.replace(/[^a-zA-Z0-9.]/g, '-')
const fileName = `${uuidv4()}-${sanitizedName}`
console.log('Uploading to bucket:', BUCKET_NAME)
console.log('Generated fileName:', fileName)
try {
await minioClient.putObject(BUCKET_NAME, fileName, buffer, buffer.length, {
'Content-Type': file.type,
})
console.log('Upload successful!')
} catch (error) {
console.error('CRITICAL MINIO ERROR:', error)
throw error
}
// Return the proxied URL through Nginx to avoid DNS resolution errors in the browser
// Return the relative URL. Next.js proxy will handle the rest.
return `/storage/${BUCKET_NAME}/${fileName}`
}