forked from git.gladyson/openmonetis
refactor: migrate from ESLint to Biome and extract SQL queries to data.ts
- Replace ESLint with Biome for linting and formatting - Configure Biome with tabs, double quotes, and organized imports - Move all SQL/Drizzle queries from page.tsx files to data.ts files - Create new data.ts files for: ajustes, dashboard, relatorios/categorias - Update existing data.ts files: extrato, fatura (add lancamentos queries) - Remove all drizzle-orm imports from page.tsx files - Update README.md with new tooling info Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,81 +5,88 @@
|
||||
* Usado pelo app Android quando o access token expira.
|
||||
*/
|
||||
|
||||
import { refreshAccessToken, extractBearerToken, verifyJwt, hashToken } from "@/lib/auth/api-token";
|
||||
import { db } from "@/lib/db";
|
||||
import { apiTokens } from "@/db/schema";
|
||||
import { eq, and, isNull } from "drizzle-orm";
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import { NextResponse } from "next/server";
|
||||
import { apiTokens } from "@/db/schema";
|
||||
import {
|
||||
extractBearerToken,
|
||||
hashToken,
|
||||
refreshAccessToken,
|
||||
verifyJwt,
|
||||
} from "@/lib/auth/api-token";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
// Extrair refresh token do header
|
||||
const authHeader = request.headers.get("Authorization");
|
||||
const token = extractBearerToken(authHeader);
|
||||
try {
|
||||
// Extrair refresh token do header
|
||||
const authHeader = request.headers.get("Authorization");
|
||||
const token = extractBearerToken(authHeader);
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json(
|
||||
{ error: "Refresh token não fornecido" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
if (!token) {
|
||||
return NextResponse.json(
|
||||
{ error: "Refresh token não fornecido" },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
// Validar refresh token
|
||||
const payload = verifyJwt(token);
|
||||
// Validar refresh token
|
||||
const payload = verifyJwt(token);
|
||||
|
||||
if (!payload || payload.type !== "api_refresh") {
|
||||
return NextResponse.json(
|
||||
{ error: "Refresh token inválido ou expirado" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
if (!payload || payload.type !== "api_refresh") {
|
||||
return NextResponse.json(
|
||||
{ error: "Refresh token inválido ou expirado" },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
// Verificar se token não foi revogado
|
||||
const tokenRecord = await db.query.apiTokens.findFirst({
|
||||
where: and(
|
||||
eq(apiTokens.id, payload.tokenId),
|
||||
eq(apiTokens.userId, payload.sub),
|
||||
isNull(apiTokens.revokedAt)
|
||||
),
|
||||
});
|
||||
// Verificar se token não foi revogado
|
||||
const tokenRecord = await db.query.apiTokens.findFirst({
|
||||
where: and(
|
||||
eq(apiTokens.id, payload.tokenId),
|
||||
eq(apiTokens.userId, payload.sub),
|
||||
isNull(apiTokens.revokedAt),
|
||||
),
|
||||
});
|
||||
|
||||
if (!tokenRecord) {
|
||||
return NextResponse.json(
|
||||
{ error: "Token revogado ou não encontrado" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
if (!tokenRecord) {
|
||||
return NextResponse.json(
|
||||
{ error: "Token revogado ou não encontrado" },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
// Gerar novo access token
|
||||
const result = refreshAccessToken(token);
|
||||
// Gerar novo access token
|
||||
const result = refreshAccessToken(token);
|
||||
|
||||
if (!result) {
|
||||
return NextResponse.json(
|
||||
{ error: "Não foi possível renovar o token" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
if (!result) {
|
||||
return NextResponse.json(
|
||||
{ error: "Não foi possível renovar o token" },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
// Atualizar hash do token e último uso
|
||||
await db
|
||||
.update(apiTokens)
|
||||
.set({
|
||||
tokenHash: hashToken(result.accessToken),
|
||||
lastUsedAt: new Date(),
|
||||
lastUsedIp: request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip"),
|
||||
expiresAt: result.expiresAt,
|
||||
})
|
||||
.where(eq(apiTokens.id, payload.tokenId));
|
||||
// Atualizar hash do token e último uso
|
||||
await db
|
||||
.update(apiTokens)
|
||||
.set({
|
||||
tokenHash: hashToken(result.accessToken),
|
||||
lastUsedAt: new Date(),
|
||||
lastUsedIp:
|
||||
request.headers.get("x-forwarded-for") ||
|
||||
request.headers.get("x-real-ip"),
|
||||
expiresAt: result.expiresAt,
|
||||
})
|
||||
.where(eq(apiTokens.id, payload.tokenId));
|
||||
|
||||
return NextResponse.json({
|
||||
accessToken: result.accessToken,
|
||||
expiresAt: result.expiresAt.toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[API] Error refreshing device token:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Erro ao renovar token" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
return NextResponse.json({
|
||||
accessToken: result.accessToken,
|
||||
expiresAt: result.expiresAt.toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[API] Error refreshing device token:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Erro ao renovar token" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,75 +5,74 @@
|
||||
* Requer sessão web autenticada.
|
||||
*/
|
||||
|
||||
import { auth } from "@/lib/auth/config";
|
||||
import { generateTokenPair, hashToken, getTokenPrefix } from "@/lib/auth/api-token";
|
||||
import { db } from "@/lib/db";
|
||||
import { apiTokens } from "@/db/schema";
|
||||
import { headers } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { apiTokens } from "@/db/schema";
|
||||
import {
|
||||
generateTokenPair,
|
||||
getTokenPrefix,
|
||||
hashToken,
|
||||
} from "@/lib/auth/api-token";
|
||||
import { auth } from "@/lib/auth/config";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
const createTokenSchema = z.object({
|
||||
name: z.string().min(1, "Nome é obrigatório").max(100, "Nome muito longo"),
|
||||
deviceId: z.string().optional(),
|
||||
name: z.string().min(1, "Nome é obrigatório").max(100, "Nome muito longo"),
|
||||
deviceId: z.string().optional(),
|
||||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
// Verificar autenticação via sessão web
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
try {
|
||||
// Verificar autenticação via sessão web
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: "Não autenticado" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: "Não autenticado" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Validar body
|
||||
const body = await request.json();
|
||||
const { name, deviceId } = createTokenSchema.parse(body);
|
||||
// Validar body
|
||||
const body = await request.json();
|
||||
const { name, deviceId } = createTokenSchema.parse(body);
|
||||
|
||||
// Gerar par de tokens
|
||||
const { accessToken, refreshToken, tokenId, expiresAt } = generateTokenPair(
|
||||
session.user.id,
|
||||
deviceId
|
||||
);
|
||||
// Gerar par de tokens
|
||||
const { accessToken, refreshToken, tokenId, expiresAt } = generateTokenPair(
|
||||
session.user.id,
|
||||
deviceId,
|
||||
);
|
||||
|
||||
// Salvar hash do token no banco
|
||||
await db.insert(apiTokens).values({
|
||||
id: tokenId,
|
||||
userId: session.user.id,
|
||||
name,
|
||||
tokenHash: hashToken(accessToken),
|
||||
tokenPrefix: getTokenPrefix(accessToken),
|
||||
expiresAt,
|
||||
});
|
||||
// Salvar hash do token no banco
|
||||
await db.insert(apiTokens).values({
|
||||
id: tokenId,
|
||||
userId: session.user.id,
|
||||
name,
|
||||
tokenHash: hashToken(accessToken),
|
||||
tokenPrefix: getTokenPrefix(accessToken),
|
||||
expiresAt,
|
||||
});
|
||||
|
||||
// Retornar tokens (mostrados apenas uma vez)
|
||||
return NextResponse.json(
|
||||
{
|
||||
accessToken,
|
||||
refreshToken,
|
||||
tokenId,
|
||||
name,
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
message: "Token criado com sucesso. Guarde-o em local seguro, ele não será mostrado novamente.",
|
||||
},
|
||||
{ status: 201 }
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.issues[0]?.message ?? "Dados inválidos" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
// Retornar tokens (mostrados apenas uma vez)
|
||||
return NextResponse.json(
|
||||
{
|
||||
accessToken,
|
||||
refreshToken,
|
||||
tokenId,
|
||||
name,
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
message:
|
||||
"Token criado com sucesso. Guarde-o em local seguro, ele não será mostrado novamente.",
|
||||
},
|
||||
{ status: 201 },
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.issues[0]?.message ?? "Dados inválidos" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
console.error("[API] Error creating device token:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Erro ao criar token" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
console.error("[API] Error creating device token:", error);
|
||||
return NextResponse.json({ error: "Erro ao criar token" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,61 +5,58 @@
|
||||
* Requer sessão web autenticada.
|
||||
*/
|
||||
|
||||
import { auth } from "@/lib/auth/config";
|
||||
import { db } from "@/lib/db";
|
||||
import { apiTokens } from "@/db/schema";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { headers } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import { apiTokens } from "@/db/schema";
|
||||
import { auth } from "@/lib/auth/config";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
interface RouteParams {
|
||||
params: Promise<{ tokenId: string }>;
|
||||
params: Promise<{ tokenId: string }>;
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request, { params }: RouteParams) {
|
||||
try {
|
||||
const { tokenId } = await params;
|
||||
export async function DELETE(_request: Request, { params }: RouteParams) {
|
||||
try {
|
||||
const { tokenId } = await params;
|
||||
|
||||
// Verificar autenticação via sessão web
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
// Verificar autenticação via sessão web
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: "Não autenticado" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: "Não autenticado" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Verificar se token pertence ao usuário
|
||||
const token = await db.query.apiTokens.findFirst({
|
||||
where: and(
|
||||
eq(apiTokens.id, tokenId),
|
||||
eq(apiTokens.userId, session.user.id)
|
||||
),
|
||||
});
|
||||
// Verificar se token pertence ao usuário
|
||||
const token = await db.query.apiTokens.findFirst({
|
||||
where: and(
|
||||
eq(apiTokens.id, tokenId),
|
||||
eq(apiTokens.userId, session.user.id),
|
||||
),
|
||||
});
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json(
|
||||
{ error: "Token não encontrado" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
if (!token) {
|
||||
return NextResponse.json(
|
||||
{ error: "Token não encontrado" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
// Revogar token (soft delete)
|
||||
await db
|
||||
.update(apiTokens)
|
||||
.set({ revokedAt: new Date() })
|
||||
.where(eq(apiTokens.id, tokenId));
|
||||
// Revogar token (soft delete)
|
||||
await db
|
||||
.update(apiTokens)
|
||||
.set({ revokedAt: new Date() })
|
||||
.where(eq(apiTokens.id, tokenId));
|
||||
|
||||
return NextResponse.json({
|
||||
message: "Token revogado com sucesso",
|
||||
tokenId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[API] Error revoking device token:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Erro ao revogar token" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
return NextResponse.json({
|
||||
message: "Token revogado com sucesso",
|
||||
tokenId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[API] Error revoking device token:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Erro ao revogar token" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,49 +5,48 @@
|
||||
* Requer sessão web autenticada.
|
||||
*/
|
||||
|
||||
import { auth } from "@/lib/auth/config";
|
||||
import { db } from "@/lib/db";
|
||||
import { apiTokens } from "@/db/schema";
|
||||
import { eq, desc } from "drizzle-orm";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { headers } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import { apiTokens } from "@/db/schema";
|
||||
import { auth } from "@/lib/auth/config";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
// Verificar autenticação via sessão web
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
try {
|
||||
// Verificar autenticação via sessão web
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: "Não autenticado" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: "Não autenticado" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Buscar tokens ativos do usuário
|
||||
const tokens = await db
|
||||
.select({
|
||||
id: apiTokens.id,
|
||||
name: apiTokens.name,
|
||||
tokenPrefix: apiTokens.tokenPrefix,
|
||||
lastUsedAt: apiTokens.lastUsedAt,
|
||||
lastUsedIp: apiTokens.lastUsedIp,
|
||||
expiresAt: apiTokens.expiresAt,
|
||||
createdAt: apiTokens.createdAt,
|
||||
})
|
||||
.from(apiTokens)
|
||||
.where(eq(apiTokens.userId, session.user.id))
|
||||
.orderBy(desc(apiTokens.createdAt));
|
||||
// Buscar tokens ativos do usuário
|
||||
const tokens = await db
|
||||
.select({
|
||||
id: apiTokens.id,
|
||||
name: apiTokens.name,
|
||||
tokenPrefix: apiTokens.tokenPrefix,
|
||||
lastUsedAt: apiTokens.lastUsedAt,
|
||||
lastUsedIp: apiTokens.lastUsedIp,
|
||||
expiresAt: apiTokens.expiresAt,
|
||||
createdAt: apiTokens.createdAt,
|
||||
})
|
||||
.from(apiTokens)
|
||||
.where(eq(apiTokens.userId, session.user.id))
|
||||
.orderBy(desc(apiTokens.createdAt));
|
||||
|
||||
// Separar tokens ativos e revogados
|
||||
const activeTokens = tokens.filter((t) => !t.expiresAt || new Date(t.expiresAt) > new Date());
|
||||
// Separar tokens ativos e revogados
|
||||
const activeTokens = tokens.filter(
|
||||
(t) => !t.expiresAt || new Date(t.expiresAt) > new Date(),
|
||||
);
|
||||
|
||||
return NextResponse.json({ tokens: activeTokens });
|
||||
} catch (error) {
|
||||
console.error("[API] Error listing device tokens:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Erro ao listar tokens" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ tokens: activeTokens });
|
||||
} catch (error) {
|
||||
console.error("[API] Error listing device tokens:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Erro ao listar tokens" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,75 +7,76 @@
|
||||
* Aceita tokens no formato os_xxx (hash-based, sem expiração).
|
||||
*/
|
||||
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import { NextResponse } from "next/server";
|
||||
import { apiTokens } from "@/db/schema";
|
||||
import { extractBearerToken, hashToken } from "@/lib/auth/api-token";
|
||||
import { db } from "@/lib/db";
|
||||
import { apiTokens } from "@/db/schema";
|
||||
import { eq, and, isNull } from "drizzle-orm";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
// Extrair token do header
|
||||
const authHeader = request.headers.get("Authorization");
|
||||
const token = extractBearerToken(authHeader);
|
||||
try {
|
||||
// Extrair token do header
|
||||
const authHeader = request.headers.get("Authorization");
|
||||
const token = extractBearerToken(authHeader);
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "Token não fornecido" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
if (!token) {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "Token não fornecido" },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
// Validar token os_xxx via hash lookup
|
||||
if (!token.startsWith("os_")) {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "Formato de token inválido" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
// Validar token os_xxx via hash lookup
|
||||
if (!token.startsWith("os_")) {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "Formato de token inválido" },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
// Hash do token para buscar no DB
|
||||
const tokenHash = hashToken(token);
|
||||
// Hash do token para buscar no DB
|
||||
const tokenHash = hashToken(token);
|
||||
|
||||
// Buscar token no banco
|
||||
const tokenRecord = await db.query.apiTokens.findFirst({
|
||||
where: and(
|
||||
eq(apiTokens.tokenHash, tokenHash),
|
||||
isNull(apiTokens.revokedAt)
|
||||
),
|
||||
});
|
||||
// Buscar token no banco
|
||||
const tokenRecord = await db.query.apiTokens.findFirst({
|
||||
where: and(
|
||||
eq(apiTokens.tokenHash, tokenHash),
|
||||
isNull(apiTokens.revokedAt),
|
||||
),
|
||||
});
|
||||
|
||||
if (!tokenRecord) {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "Token inválido ou revogado" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
if (!tokenRecord) {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "Token inválido ou revogado" },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
// Atualizar último uso
|
||||
const clientIp = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim()
|
||||
|| request.headers.get("x-real-ip")
|
||||
|| null;
|
||||
// Atualizar último uso
|
||||
const clientIp =
|
||||
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
|
||||
request.headers.get("x-real-ip") ||
|
||||
null;
|
||||
|
||||
await db
|
||||
.update(apiTokens)
|
||||
.set({
|
||||
lastUsedAt: new Date(),
|
||||
lastUsedIp: clientIp,
|
||||
})
|
||||
.where(eq(apiTokens.id, tokenRecord.id));
|
||||
await db
|
||||
.update(apiTokens)
|
||||
.set({
|
||||
lastUsedAt: new Date(),
|
||||
lastUsedIp: clientIp,
|
||||
})
|
||||
.where(eq(apiTokens.id, tokenRecord.id));
|
||||
|
||||
return NextResponse.json({
|
||||
valid: true,
|
||||
userId: tokenRecord.userId,
|
||||
tokenId: tokenRecord.id,
|
||||
tokenName: tokenRecord.name,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[API] Error verifying device token:", error);
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "Erro ao validar token" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
return NextResponse.json({
|
||||
valid: true,
|
||||
userId: tokenRecord.userId,
|
||||
tokenId: tokenRecord.id,
|
||||
tokenName: tokenRecord.name,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[API] Error verifying device token:", error);
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "Erro ao validar token" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user