Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fb1c502c8 | ||
|
|
d895812235 | ||
|
|
f680764373 | ||
|
|
acc17bf291 | ||
|
|
1b57dcc850 | ||
|
|
77d750992d | ||
|
|
b30cc1a294 | ||
|
|
a7a6680cf8 | ||
|
|
44570ad457 | ||
|
|
8caed06362 | ||
|
|
e3db3d6cd7 | ||
|
|
fb7b29cd94 | ||
|
|
0a11a452b5 | ||
|
|
1d661e2e48 | ||
|
|
2ee956665f | ||
|
|
0d5db42c77 | ||
|
|
21127b8cff | ||
|
|
50a9dc5183 | ||
|
|
a69df1d2d6 |
+1
-2
@@ -9,11 +9,10 @@
|
|||||||
"start:dev": "nest start --watch",
|
"start:dev": "nest start --watch",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "tsc -p tsconfig.test.json --noEmit && node --import tsx --test test/**/*.test.ts",
|
"test": "tsc -p tsconfig.test.json --noEmit && node --import tsx --test test/**/*.test.ts",
|
||||||
"migration:run": "node dist/database/migration-cli.js run && node dist/cli/fresh-start-reset.js --preview",
|
"migration:run": "node dist/database/migration-cli.js run",
|
||||||
"migration:show": "node dist/database/migration-cli.js show",
|
"migration:show": "node dist/database/migration-cli.js show",
|
||||||
"migration:revert": "node dist/database/migration-cli.js revert",
|
"migration:revert": "node dist/database/migration-cli.js revert",
|
||||||
"bootstrap:admin": "node dist/cli/bootstrap-admin.js",
|
"bootstrap:admin": "node dist/cli/bootstrap-admin.js",
|
||||||
"maintenance:fresh-start": "node dist/cli/fresh-start-reset.js",
|
|
||||||
"dev:seed:mendoza-demo": "node dist/cli/dev-seed-mendoza-demo.js"
|
"dev:seed:mendoza-demo": "node dist/cli/dev-seed-mendoza-demo.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import { AuthorizationModule } from '../authorization/authorization.module';
|
|||||||
import { PhaseADataModule } from '../core-data/phase-a-data.module';
|
import { PhaseADataModule } from '../core-data/phase-a-data.module';
|
||||||
import { AuthController } from './auth.controller';
|
import { AuthController } from './auth.controller';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
|
import { MobileAuthController } from './mobile-auth.controller';
|
||||||
|
import { MobileAuthService } from './mobile-auth.service';
|
||||||
import { AccessTokenGuard } from './guards/access-token.guard';
|
import { AccessTokenGuard } from './guards/access-token.guard';
|
||||||
import { CsrfGuard } from './guards/csrf.guard';
|
import { CsrfGuard } from './guards/csrf.guard';
|
||||||
import { AuthConfigService } from '../common/config/auth-config.service';
|
import { AuthConfigService } from '../common/config/auth-config.service';
|
||||||
@@ -18,6 +20,7 @@ const providers = [
|
|||||||
PasswordService,
|
PasswordService,
|
||||||
TokenService,
|
TokenService,
|
||||||
AuthService,
|
AuthService,
|
||||||
|
MobileAuthService,
|
||||||
AccessTokenGuard,
|
AccessTokenGuard,
|
||||||
CsrfGuard,
|
CsrfGuard,
|
||||||
];
|
];
|
||||||
@@ -29,7 +32,7 @@ const providers = [
|
|||||||
AuditModule,
|
AuditModule,
|
||||||
AuthorizationModule,
|
AuthorizationModule,
|
||||||
],
|
],
|
||||||
controllers: [AuthController],
|
controllers: [AuthController, MobileAuthController],
|
||||||
providers,
|
providers,
|
||||||
exports: [
|
exports: [
|
||||||
AuthConfigService,
|
AuthConfigService,
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { IsString, MaxLength, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class MobileRefreshDto {
|
||||||
|
@IsString()
|
||||||
|
@MinLength(32)
|
||||||
|
@MaxLength(256)
|
||||||
|
refreshToken!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
HttpCode,
|
||||||
|
Post,
|
||||||
|
Req,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Throttle } from '@nestjs/throttler';
|
||||||
|
import type {
|
||||||
|
AuthPrincipal,
|
||||||
|
RequestWithContext,
|
||||||
|
} from '../common/http/request-context';
|
||||||
|
import { CurrentAuth } from './decorators/current-auth.decorator';
|
||||||
|
import { Public } from './decorators/public.decorator';
|
||||||
|
import { SkipCsrf } from './decorators/skip-csrf.decorator';
|
||||||
|
import { LoginDto } from './dto/login.dto';
|
||||||
|
import { MobileRefreshDto } from './dto/mobile-refresh.dto';
|
||||||
|
import { MobileAuthService } from './mobile-auth.service';
|
||||||
|
|
||||||
|
@Controller('auth/mobile')
|
||||||
|
export class MobileAuthController {
|
||||||
|
constructor(private readonly mobileAuth: MobileAuthService) {}
|
||||||
|
|
||||||
|
@Post('login')
|
||||||
|
@HttpCode(200)
|
||||||
|
@Public()
|
||||||
|
@SkipCsrf()
|
||||||
|
@Throttle({ default: { limit: 5, ttl: 60_000, blockDuration: 60_000 } })
|
||||||
|
login(
|
||||||
|
@Body() dto: LoginDto,
|
||||||
|
@Req() request: RequestWithContext,
|
||||||
|
) {
|
||||||
|
return this.mobileAuth.login(dto, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('refresh')
|
||||||
|
@HttpCode(200)
|
||||||
|
@Public()
|
||||||
|
@SkipCsrf()
|
||||||
|
@Throttle({ default: { limit: 20, ttl: 60_000 } })
|
||||||
|
refresh(
|
||||||
|
@Body() dto: MobileRefreshDto,
|
||||||
|
@Req() request: RequestWithContext,
|
||||||
|
) {
|
||||||
|
return this.mobileAuth.refresh(dto.refreshToken, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('logout')
|
||||||
|
@HttpCode(200)
|
||||||
|
logout(
|
||||||
|
@CurrentAuth() principal: AuthPrincipal,
|
||||||
|
@Req() request: RequestWithContext,
|
||||||
|
) {
|
||||||
|
return this.mobileAuth.logout(principal, request);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
import { isIP } from 'node:net';
|
||||||
|
import {
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { DataSource } from 'typeorm';
|
||||||
|
import { AuditService } from '../audit/audit.service';
|
||||||
|
import type {
|
||||||
|
AuthPrincipal,
|
||||||
|
RequestWithContext,
|
||||||
|
} from '../common/http/request-context';
|
||||||
|
import { AuthSessionsRepository } from '../core-data/repositories/auth-sessions.repository';
|
||||||
|
import { RolesRepository } from '../core-data/repositories/roles.repository';
|
||||||
|
import { UsersRepository } from '../core-data/repositories/users.repository';
|
||||||
|
import {
|
||||||
|
AuditAction,
|
||||||
|
AuditSource,
|
||||||
|
AuthSession,
|
||||||
|
User,
|
||||||
|
UserStatus,
|
||||||
|
} from '../database/entities';
|
||||||
|
import type { LoginDto } from './dto/login.dto';
|
||||||
|
import { PasswordService } from './services/password.service';
|
||||||
|
import {
|
||||||
|
IssuedRefreshToken,
|
||||||
|
TokenService,
|
||||||
|
} from './services/token.service';
|
||||||
|
|
||||||
|
interface RequestMetadata {
|
||||||
|
ip: string | null;
|
||||||
|
userAgent: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SuccessfulAuthentication {
|
||||||
|
user: User;
|
||||||
|
accessToken: string;
|
||||||
|
refreshToken: IssuedRefreshToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
type LoginOutcome = SuccessfulAuthentication | null;
|
||||||
|
type RefreshOutcome =
|
||||||
|
| ({ kind: 'ok' } & SuccessfulAuthentication)
|
||||||
|
| { kind: 'reuse' }
|
||||||
|
| { kind: 'invalid' };
|
||||||
|
|
||||||
|
function invalidCredentials(): UnauthorizedException {
|
||||||
|
return new UnauthorizedException({
|
||||||
|
code: 'INVALID_CREDENTIALS',
|
||||||
|
message: 'Credenciales inválidas',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function invalidSession(): UnauthorizedException {
|
||||||
|
return new UnauthorizedException({
|
||||||
|
code: 'INVALID_SESSION',
|
||||||
|
message: 'Sesión móvil inválida o vencida',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function inspectorRequired(): ForbiddenException {
|
||||||
|
return new ForbiddenException({
|
||||||
|
code: 'INSPECTION_INSPECTOR_ROLE_REQUIRED',
|
||||||
|
message: 'Sólo un usuario con rol inspector puede ingresar a la aplicación móvil',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestMetadata(request: RequestWithContext): RequestMetadata {
|
||||||
|
const candidateIp = request.ip || request.socket.remoteAddress || '';
|
||||||
|
const ip = isIP(candidateIp) ? candidateIp : null;
|
||||||
|
const rawUserAgent = request.header('user-agent')?.trim();
|
||||||
|
return {
|
||||||
|
ip,
|
||||||
|
userAgent: rawUserAgent ? rawUserAgent.slice(0, 2048) : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MobileAuthService {
|
||||||
|
constructor(
|
||||||
|
private readonly dataSource: DataSource,
|
||||||
|
private readonly users: UsersRepository,
|
||||||
|
private readonly sessions: AuthSessionsRepository,
|
||||||
|
private readonly roles: RolesRepository,
|
||||||
|
private readonly passwords: PasswordService,
|
||||||
|
private readonly tokens: TokenService,
|
||||||
|
private readonly audit: AuditService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async login(dto: LoginDto, request: RequestWithContext) {
|
||||||
|
const identifier = dto.identifier.trim().toLowerCase();
|
||||||
|
const candidate = await this.users.findForAuthentication(identifier);
|
||||||
|
const metadata = requestMetadata(request);
|
||||||
|
|
||||||
|
if (!candidate) {
|
||||||
|
await this.passwords.verifyUnknown(dto.password);
|
||||||
|
await this.audit.record({
|
||||||
|
action: AuditAction.AUTH_LOGIN_FAILED,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
metadata: { identifier, reason: 'UNKNOWN_IDENTIFIER' },
|
||||||
|
});
|
||||||
|
throw invalidCredentials();
|
||||||
|
}
|
||||||
|
|
||||||
|
const outcome = await this.dataSource.transaction<LoginOutcome>(
|
||||||
|
async (manager) => {
|
||||||
|
const user = await manager
|
||||||
|
.getRepository(User)
|
||||||
|
.createQueryBuilder('user')
|
||||||
|
.addSelect('user.passwordHash')
|
||||||
|
.where('user.id = :id', { id: candidate.id })
|
||||||
|
.setLock('pessimistic_write')
|
||||||
|
.getOne();
|
||||||
|
if (!user) return null;
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const passwordMatches = await this.passwords.verify(
|
||||||
|
user.passwordHash,
|
||||||
|
dto.password,
|
||||||
|
);
|
||||||
|
const locked = Boolean(user.lockedUntil && user.lockedUntil > now);
|
||||||
|
const active = user.status === UserStatus.ACTIVE;
|
||||||
|
|
||||||
|
if (!passwordMatches || locked || !active) {
|
||||||
|
if (!passwordMatches && active && !locked) {
|
||||||
|
await manager.query(
|
||||||
|
`
|
||||||
|
UPDATE users
|
||||||
|
SET
|
||||||
|
failed_login_attempts = failed_login_attempts + 1,
|
||||||
|
locked_until = CASE
|
||||||
|
WHEN failed_login_attempts + 1 >= $2
|
||||||
|
THEN CURRENT_TIMESTAMP + ($3 * INTERVAL '1 second')
|
||||||
|
ELSE locked_until
|
||||||
|
END,
|
||||||
|
updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE id = $1
|
||||||
|
`,
|
||||||
|
[
|
||||||
|
user.id,
|
||||||
|
this.tokens.maxLoginAttempts,
|
||||||
|
this.tokens.lockoutSeconds,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.audit.record(
|
||||||
|
{
|
||||||
|
actorUserId: user.id,
|
||||||
|
actorUsername: user.username,
|
||||||
|
action: AuditAction.AUTH_LOGIN_FAILED,
|
||||||
|
entityType: 'user',
|
||||||
|
entityId: user.id,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
metadata: {
|
||||||
|
reason: !active
|
||||||
|
? 'INACTIVE_USER'
|
||||||
|
: locked
|
||||||
|
? 'LOCKED_USER'
|
||||||
|
: 'INVALID_PASSWORD',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.passwords.needsRehash(user.passwordHash)) {
|
||||||
|
user.passwordHash = await this.passwords.hash(dto.password);
|
||||||
|
}
|
||||||
|
user.failedLoginAttempts = 0;
|
||||||
|
user.lockedUntil = null;
|
||||||
|
user.lastLoginAt = now;
|
||||||
|
await manager.getRepository(User).save(user);
|
||||||
|
|
||||||
|
const refreshToken = this.tokens.issueRefreshToken();
|
||||||
|
const session = manager.getRepository(AuthSession).create({
|
||||||
|
id: refreshToken.sessionId,
|
||||||
|
userId: user.id,
|
||||||
|
refreshTokenHash: refreshToken.tokenHash,
|
||||||
|
expiresAt: this.tokens.refreshExpiresAt(now),
|
||||||
|
lastUsedAt: now,
|
||||||
|
revokedAt: null,
|
||||||
|
replacedBySessionId: null,
|
||||||
|
ip: metadata.ip,
|
||||||
|
userAgent: metadata.userAgent,
|
||||||
|
deviceLabel: dto.deviceLabel?.trim() || 'DH Android',
|
||||||
|
});
|
||||||
|
await manager.getRepository(AuthSession).save(session);
|
||||||
|
|
||||||
|
const accessToken = await this.tokens.issueAccessToken({
|
||||||
|
userId: user.id,
|
||||||
|
sessionId: session.id,
|
||||||
|
username: user.username,
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.audit.record(
|
||||||
|
{
|
||||||
|
actorUserId: user.id,
|
||||||
|
actorUsername: user.username,
|
||||||
|
action: AuditAction.AUTH_LOGIN_SUCCESS,
|
||||||
|
entityType: 'auth_session',
|
||||||
|
entityId: session.id,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
metadata: { deviceLabel: session.deviceLabel },
|
||||||
|
},
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
|
||||||
|
return { user, accessToken, refreshToken };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!outcome) throw invalidCredentials();
|
||||||
|
return this.complete(outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
async refresh(rawToken: string, request: RequestWithContext) {
|
||||||
|
const parsed = this.tokens.parseRefreshToken(rawToken);
|
||||||
|
if (!parsed) throw invalidSession();
|
||||||
|
|
||||||
|
const metadata = requestMetadata(request);
|
||||||
|
const outcome = await this.dataSource.transaction<RefreshOutcome>(
|
||||||
|
async (manager) => {
|
||||||
|
const session = await manager
|
||||||
|
.getRepository(AuthSession)
|
||||||
|
.createQueryBuilder('session')
|
||||||
|
.addSelect('session.refreshTokenHash')
|
||||||
|
.where('session.id = :id', { id: parsed.sessionId })
|
||||||
|
.setLock('pessimistic_write')
|
||||||
|
.getOne();
|
||||||
|
|
||||||
|
if (
|
||||||
|
!session ||
|
||||||
|
!this.tokens.verifyRefreshToken(rawToken, session.refreshTokenHash)
|
||||||
|
) {
|
||||||
|
return { kind: 'invalid' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await manager.getRepository(User).findOne({
|
||||||
|
where: { id: session.userId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (session.revokedAt) {
|
||||||
|
await this.sessions.revokeSessionFamily(session.id, manager);
|
||||||
|
await this.audit.record(
|
||||||
|
{
|
||||||
|
actorUserId: user?.id ?? null,
|
||||||
|
actorUsername: user?.username ?? null,
|
||||||
|
action: AuditAction.AUTH_REFRESH_REUSE_DETECTED,
|
||||||
|
entityType: 'auth_session',
|
||||||
|
entityId: session.id,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
},
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
return { kind: 'reuse' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
if (!user || user.status !== UserStatus.ACTIVE || session.expiresAt <= now) {
|
||||||
|
session.revokedAt = now;
|
||||||
|
session.lastUsedAt = now;
|
||||||
|
await manager.getRepository(AuthSession).save(session);
|
||||||
|
if (user?.status === UserStatus.INACTIVE) {
|
||||||
|
await this.sessions.revokeUserSessions(user.id, undefined, manager);
|
||||||
|
}
|
||||||
|
return { kind: 'invalid' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const refreshToken = this.tokens.issueRefreshToken();
|
||||||
|
const replacement = manager.getRepository(AuthSession).create({
|
||||||
|
id: refreshToken.sessionId,
|
||||||
|
userId: user.id,
|
||||||
|
refreshTokenHash: refreshToken.tokenHash,
|
||||||
|
expiresAt: this.tokens.refreshExpiresAt(now),
|
||||||
|
lastUsedAt: now,
|
||||||
|
revokedAt: null,
|
||||||
|
replacedBySessionId: null,
|
||||||
|
ip: metadata.ip,
|
||||||
|
userAgent: metadata.userAgent,
|
||||||
|
deviceLabel: session.deviceLabel,
|
||||||
|
});
|
||||||
|
await manager.getRepository(AuthSession).save(replacement);
|
||||||
|
|
||||||
|
session.revokedAt = now;
|
||||||
|
session.lastUsedAt = now;
|
||||||
|
session.replacedBySessionId = replacement.id;
|
||||||
|
await manager.getRepository(AuthSession).save(session);
|
||||||
|
|
||||||
|
const accessToken = await this.tokens.issueAccessToken({
|
||||||
|
userId: user.id,
|
||||||
|
sessionId: replacement.id,
|
||||||
|
username: user.username,
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.audit.record(
|
||||||
|
{
|
||||||
|
actorUserId: user.id,
|
||||||
|
actorUsername: user.username,
|
||||||
|
action: AuditAction.AUTH_REFRESH,
|
||||||
|
entityType: 'auth_session',
|
||||||
|
entityId: replacement.id,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
metadata: { replacedSessionId: session.id },
|
||||||
|
},
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
|
||||||
|
return { kind: 'ok', user, accessToken, refreshToken };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (outcome.kind !== 'ok') throw invalidSession();
|
||||||
|
return this.complete(outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
async logout(
|
||||||
|
principal: AuthPrincipal,
|
||||||
|
request: RequestWithContext,
|
||||||
|
) {
|
||||||
|
const metadata = requestMetadata(request);
|
||||||
|
await this.dataSource.transaction(async (manager) => {
|
||||||
|
await this.sessions.revokeSession(
|
||||||
|
principal.sessionId,
|
||||||
|
principal.userId,
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
await this.audit.record(
|
||||||
|
{
|
||||||
|
actorUserId: principal.userId,
|
||||||
|
actorUsername: principal.username,
|
||||||
|
action: AuditAction.AUTH_LOGOUT,
|
||||||
|
entityType: 'auth_session',
|
||||||
|
entityId: principal.sessionId,
|
||||||
|
requestId: request.requestId,
|
||||||
|
source: AuditSource.ANDROID,
|
||||||
|
...metadata,
|
||||||
|
},
|
||||||
|
manager,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return { status: 'ok' };
|
||||||
|
}
|
||||||
|
|
||||||
|
private async complete(authentication: SuccessfulAuthentication) {
|
||||||
|
const [roleCodes, permissionCodes] = await Promise.all([
|
||||||
|
this.roles.findRoleCodesForUser(authentication.user.id),
|
||||||
|
this.roles.findPermissionCodesForUser(authentication.user.id),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!roleCodes.includes('inspector')) {
|
||||||
|
await this.sessions.revokeSession(
|
||||||
|
authentication.refreshToken.sessionId,
|
||||||
|
authentication.user.id,
|
||||||
|
);
|
||||||
|
throw inspectorRequired();
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
user: {
|
||||||
|
id: authentication.user.id,
|
||||||
|
username: authentication.user.username,
|
||||||
|
firstName: authentication.user.firstName,
|
||||||
|
lastName: authentication.user.lastName,
|
||||||
|
email: authentication.user.email,
|
||||||
|
mustChangePassword: authentication.user.mustChangePassword,
|
||||||
|
roles: roleCodes,
|
||||||
|
permissions: permissionCodes,
|
||||||
|
},
|
||||||
|
accessToken: authentication.accessToken,
|
||||||
|
refreshToken: authentication.refreshToken.token,
|
||||||
|
accessExpiresInSeconds: this.tokens.accessTokenTtlSeconds,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,247 +0,0 @@
|
|||||||
import 'reflect-metadata';
|
|
||||||
|
|
||||||
import { promises as fs } from 'node:fs';
|
|
||||||
import { migrationDataSource } from '../database/data-source';
|
|
||||||
|
|
||||||
const APPLY_TOKEN = 'DHV2-FRESH-START-20260905';
|
|
||||||
|
|
||||||
const PRESERVED_TABLES = new Set([
|
|
||||||
'typeorm_migrations',
|
|
||||||
'spatial_ref_sys',
|
|
||||||
'users',
|
|
||||||
'user_roles',
|
|
||||||
'roles',
|
|
||||||
'role_permissions',
|
|
||||||
'permissions',
|
|
||||||
'asset_types',
|
|
||||||
'asset_type_parent_rules',
|
|
||||||
'asset_attribute_definitions',
|
|
||||||
'finding_categories',
|
|
||||||
'finding_catalog_items',
|
|
||||||
'finding_catalog_item_asset_types',
|
|
||||||
'finding_catalog_asset_type_profiles',
|
|
||||||
]);
|
|
||||||
|
|
||||||
type AdminRow = {
|
|
||||||
id: string;
|
|
||||||
username: string;
|
|
||||||
email: string | null;
|
|
||||||
status: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type TableRow = { table_name: string };
|
|
||||||
type CountRow = { count: string | number };
|
|
||||||
|
|
||||||
function quoteIdentifier(value: string): string {
|
|
||||||
return `"${value.replaceAll('"', '""')}"`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function requestedMode(): 'preview' | 'apply' {
|
|
||||||
const args = process.argv.slice(2);
|
|
||||||
if (args.length === 1 && args[0] === '--preview') return 'preview';
|
|
||||||
if (args.length === 2 && args[0] === '--apply' && args[1] === APPLY_TOKEN) {
|
|
||||||
return 'apply';
|
|
||||||
}
|
|
||||||
throw new Error(
|
|
||||||
`Uso inválido. Permitido: --preview o --apply ${APPLY_TOKEN}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function rowCount(table: string): Promise<number> {
|
|
||||||
const result = (await migrationDataSource.query(
|
|
||||||
`SELECT COUNT(*)::bigint AS count FROM public.${quoteIdentifier(table)}`,
|
|
||||||
)) as CountRow[];
|
|
||||||
return Number(result[0]?.count ?? 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function clearMediaStorage(): Promise<void> {
|
|
||||||
const root = process.env.ASSET_MEDIA_ROOT;
|
|
||||||
if (!root) {
|
|
||||||
process.stdout.write('MEDIA: ASSET_MEDIA_ROOT no configurado; no se tocaron archivos.\n');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const entries = await fs.readdir(root, { withFileTypes: true });
|
|
||||||
for (const entry of entries) {
|
|
||||||
await fs.rm(`${root}/${entry.name}`, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
await fs.mkdir(`${root}/imports`, { recursive: true });
|
|
||||||
process.stdout.write(`MEDIA: almacenamiento limpiado en ${root}\n`);
|
|
||||||
} catch (error) {
|
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
|
||||||
process.stdout.write(`MEDIA WARNING: no se pudo limpiar completamente ${root}: ${message}\n`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main(): Promise<void> {
|
|
||||||
const mode = requestedMode();
|
|
||||||
await migrationDataSource.initialize();
|
|
||||||
|
|
||||||
try {
|
|
||||||
await migrationDataSource.query(
|
|
||||||
`SELECT pg_advisory_lock(hashtext('dhv2-fresh-start-reset'))`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const admins = (await migrationDataSource.query(`
|
|
||||||
SELECT DISTINCT user_row.id, user_row.username, user_row.email, user_row.status
|
|
||||||
FROM users user_row
|
|
||||||
INNER JOIN user_roles user_role ON user_role.user_id = user_row.id
|
|
||||||
INNER JOIN roles role ON role.id = user_role.role_id
|
|
||||||
WHERE role.code = 'admin'
|
|
||||||
ORDER BY user_row.username
|
|
||||||
`)) as AdminRow[];
|
|
||||||
|
|
||||||
if (admins.length !== 1) {
|
|
||||||
throw new Error(
|
|
||||||
`Se esperaba exactamente 1 usuario con rol admin y se encontraron ${admins.length}. Limpieza abortada.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const admin = admins[0];
|
|
||||||
const tables = (await migrationDataSource.query(`
|
|
||||||
SELECT table_name
|
|
||||||
FROM information_schema.tables
|
|
||||||
WHERE table_schema = 'public'
|
|
||||||
AND table_type = 'BASE TABLE'
|
|
||||||
ORDER BY table_name
|
|
||||||
`)) as TableRow[];
|
|
||||||
|
|
||||||
const existingTables = tables.map((row) => row.table_name);
|
|
||||||
const tablesToClear = existingTables.filter(
|
|
||||||
(table) => !PRESERVED_TABLES.has(table),
|
|
||||||
);
|
|
||||||
const tablesToPreserve = existingTables.filter((table) =>
|
|
||||||
PRESERVED_TABLES.has(table),
|
|
||||||
);
|
|
||||||
|
|
||||||
process.stdout.write('\n============================================================\n');
|
|
||||||
process.stdout.write(` DH V2 · FRESH START · ${mode.toUpperCase()}\n`);
|
|
||||||
process.stdout.write('============================================================\n');
|
|
||||||
process.stdout.write(
|
|
||||||
`ADMIN PRESERVADO: ${admin.username} · ${admin.email ?? 'sin email'} · ${admin.id}\n`,
|
|
||||||
);
|
|
||||||
|
|
||||||
process.stdout.write('\n========== TABLAS ESTRUCTURALES CONSERVADAS ==========\n');
|
|
||||||
for (const table of tablesToPreserve) {
|
|
||||||
process.stdout.write(`KEEP ${table.padEnd(46)} ${await rowCount(table)}\n`);
|
|
||||||
}
|
|
||||||
|
|
||||||
process.stdout.write('\n========== DATOS A ELIMINAR ==========\n');
|
|
||||||
let rowsToDelete = 0;
|
|
||||||
for (const table of tablesToClear) {
|
|
||||||
const count = await rowCount(table);
|
|
||||||
rowsToDelete += count;
|
|
||||||
process.stdout.write(`CLEAR ${table.padEnd(46)} ${count}\n`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const userCount = await rowCount('users');
|
|
||||||
const nonAdminUsers = Math.max(0, userCount - 1);
|
|
||||||
process.stdout.write(`CLEAR ${'users (excepto admin)'.padEnd(46)} ${nonAdminUsers}\n`);
|
|
||||||
rowsToDelete += nonAdminUsers;
|
|
||||||
process.stdout.write(`TOTAL FILAS OPERATIVAS/USUARIOS A RETIRAR: ${rowsToDelete}\n`);
|
|
||||||
|
|
||||||
if (mode === 'preview') {
|
|
||||||
process.stdout.write('\nPREVIEW_OK: no se modificó ningún dato.\n');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await migrationDataSource.transaction(async (manager) => {
|
|
||||||
await manager.query(`SET LOCAL session_replication_role = replica`);
|
|
||||||
|
|
||||||
for (const table of tablesToClear) {
|
|
||||||
await manager.query(`DELETE FROM public.${quoteIdentifier(table)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
await manager.query(
|
|
||||||
`DELETE FROM user_roles WHERE user_id <> $1::uuid`,
|
|
||||||
[admin.id],
|
|
||||||
);
|
|
||||||
await manager.query(
|
|
||||||
`
|
|
||||||
DELETE FROM user_roles user_role
|
|
||||||
USING roles role
|
|
||||||
WHERE user_role.user_id = $1::uuid
|
|
||||||
AND role.id = user_role.role_id
|
|
||||||
AND role.code <> 'admin'
|
|
||||||
`,
|
|
||||||
[admin.id],
|
|
||||||
);
|
|
||||||
await manager.query(`DELETE FROM users WHERE id <> $1::uuid`, [admin.id]);
|
|
||||||
await manager.query(
|
|
||||||
`
|
|
||||||
UPDATE users
|
|
||||||
SET status = 'ACTIVE',
|
|
||||||
failed_login_attempts = 0,
|
|
||||||
locked_until = NULL,
|
|
||||||
created_by = CASE WHEN created_by = $1::uuid THEN created_by ELSE NULL END,
|
|
||||||
updated_by = $1::uuid,
|
|
||||||
updated_at = CURRENT_TIMESTAMP
|
|
||||||
WHERE id = $1::uuid
|
|
||||||
`,
|
|
||||||
[admin.id],
|
|
||||||
);
|
|
||||||
await manager.query(
|
|
||||||
`
|
|
||||||
UPDATE user_roles user_role
|
|
||||||
SET assigned_by = $1::uuid
|
|
||||||
FROM roles role
|
|
||||||
WHERE user_role.user_id = $1::uuid
|
|
||||||
AND role.id = user_role.role_id
|
|
||||||
AND role.code = 'admin'
|
|
||||||
`,
|
|
||||||
[admin.id],
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
const usersAfter = await rowCount('users');
|
|
||||||
if (usersAfter !== 1) {
|
|
||||||
throw new Error(`Verificación falló: users=${usersAfter}, esperado=1`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const adminAfter = (await migrationDataSource.query(
|
|
||||||
`
|
|
||||||
SELECT COUNT(DISTINCT user_row.id)::integer AS count
|
|
||||||
FROM users user_row
|
|
||||||
INNER JOIN user_roles user_role ON user_role.user_id = user_row.id
|
|
||||||
INNER JOIN roles role ON role.id = user_role.role_id
|
|
||||||
WHERE role.code = 'admin'
|
|
||||||
`,
|
|
||||||
)) as CountRow[];
|
|
||||||
if (Number(adminAfter[0]?.count ?? 0) !== 1) {
|
|
||||||
throw new Error('Verificación falló: el administrador no quedó correctamente asignado');
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const table of tablesToClear) {
|
|
||||||
const count = await rowCount(table);
|
|
||||||
if (count !== 0) {
|
|
||||||
throw new Error(`Verificación falló: ${table} conserva ${count} fila(s)`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await clearMediaStorage();
|
|
||||||
|
|
||||||
process.stdout.write('\n========== VERIFICACIÓN FRESH START ==========\n');
|
|
||||||
process.stdout.write(`Usuarios: 1 (${admin.username})\n`);
|
|
||||||
process.stdout.write('Datos operativos/importados: 0\n');
|
|
||||||
process.stdout.write('Roles/permisos/tipos/catálogos estructurales: conservados\n');
|
|
||||||
process.stdout.write('FRESH_START_OK\n');
|
|
||||||
} finally {
|
|
||||||
if (migrationDataSource.isInitialized) {
|
|
||||||
try {
|
|
||||||
await migrationDataSource.query(
|
|
||||||
`SELECT pg_advisory_unlock(hashtext('dhv2-fresh-start-reset'))`,
|
|
||||||
);
|
|
||||||
} catch {
|
|
||||||
// La conexión se destruirá de todas formas.
|
|
||||||
}
|
|
||||||
await migrationDataSource.destroy();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
main().catch((error: unknown) => {
|
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
|
||||||
process.stderr.write(`FRESH_START_ERROR: ${message}\n`);
|
|
||||||
process.exitCode = 1;
|
|
||||||
});
|
|
||||||
Reference in New Issue
Block a user