database migrated to POSTGRESQL

This commit is contained in:
2026-10-13 16:11:51 +03:30
parent 41ad8c1063
commit 514c3ccaf0
47 changed files with 1500 additions and 891 deletions
+8 -8
View File
@@ -1,16 +1,16 @@
import { UserDocument } from '../schemas/user.schema';
import { User } from '../schemas/user.schema';
import { ProfileDto } from '../../auth/dto/profile.dto';
import { UserResponseDto } from '../dto/user-response.dto';
/** Maps Mongoose user documents to API DTOs (never exposes password/hash fields). */
/** Maps user rows to API DTOs (never exposes password or token fields). */
export class UserMapper {
static toProfileDto(user: UserDocument): ProfileDto {
static toProfileDto(user: User): ProfileDto {
return {
id: user._id.toString(),
id: user.id,
fullName: user.fullName,
username: user.username,
email: user.email,
mobile: user.mobile,
mobile: user.mobile ?? undefined,
role: user.role,
clientType: user.clientType,
appName: user.appName,
@@ -21,14 +21,14 @@ export class UserMapper {
requestLimitPerMinute: user.requestLimitPerMinute,
requestLimitPerDay: user.requestLimitPerDay,
totalRequests: user.totalRequests,
lastLoginAt: user.lastLoginAt,
passwordChangedAt: user.passwordChangedAt,
lastLoginAt: user.lastLoginAt ?? undefined,
passwordChangedAt: user.passwordChangedAt ?? undefined,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
};
}
static toResponseDto(user: UserDocument): UserResponseDto {
static toResponseDto(user: User): UserResponseDto {
return UserMapper.toProfileDto(user);
}
}
+42 -38
View File
@@ -1,85 +1,89 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Types } from 'mongoose';
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';
import { ClientType } from '../../common/enums/client-type.enum';
import { Role } from '../../common/enums/role.enum';
export type UserDocument = HydratedDocument<User>;
/**
* Unified user model — internal admins and external API clients share one collection.
* Unified user model — internal admins and external API clients share one table.
* Designed for future extensions: API keys, HMAC, IP whitelist, permissions, multi-tenant.
*/
@Schema({ timestamps: true, collection: 'users' })
@Entity('users')
@Index(['role', 'isActive'])
@Index(['clientType', 'appName'])
export class User {
@Prop({ required: true, trim: true })
@PrimaryGeneratedColumn('uuid')
id!: string;
@Column({ type: 'text' })
fullName!: string;
@Prop({ required: true, unique: true, lowercase: true, trim: true, index: true })
@Index({ unique: true })
@Column({ type: 'text' })
username!: string;
@Prop({ required: true, unique: true, lowercase: true, trim: true, index: true })
@Index({ unique: true })
@Column({ type: 'text' })
email!: string;
@Prop({ trim: true })
mobile?: string;
@Column({ type: 'text', nullable: true })
mobile?: string | null;
@Prop({ required: true, select: false })
@Column({ type: 'text', select: false })
password!: string;
@Prop({ required: true, enum: Role, default: Role.USER, index: true })
@Index()
@Column({ type: 'text' })
role!: Role;
@Prop({ required: true, enum: ClientType, default: ClientType.EXTERNAL, index: true })
@Index()
@Column({ type: 'text' })
clientType!: ClientType;
@Prop({ trim: true, default: '' })
@Column({ type: 'text', default: '' })
appName!: string;
@Prop({ trim: true, default: '' })
@Column({ type: 'text', default: '' })
clientName!: string;
@Prop({ default: true })
@Column({ type: 'boolean', default: true })
isActive!: boolean;
@Prop({ default: false })
@Column({ type: 'boolean', default: false })
isBlocked!: boolean;
/** Future: machine-to-machine auth without JWT. */
@Prop({ select: false })
apiKey?: string;
@Column({ type: 'text', nullable: true, select: false })
apiKey?: string | null;
@Prop({ type: [String], default: [] })
@Column({ type: 'text', array: true, default: () => "'{}'" })
allowedInquiries!: string[];
@Prop({ default: 60 })
@Column({ type: 'int', default: 60 })
requestLimitPerMinute!: number;
@Prop({ default: 10000 })
@Column({ type: 'int', default: 10000 })
requestLimitPerDay!: number;
@Prop({ default: 0 })
@Column({ type: 'int', default: 0 })
totalRequests!: number;
@Prop()
lastLoginAt?: Date;
@Column({ type: 'timestamptz', nullable: true })
lastLoginAt?: Date | null;
@Prop()
passwordChangedAt?: Date;
@Column({ type: 'timestamptz', nullable: true })
passwordChangedAt?: Date | null;
@Prop({ type: Types.ObjectId, ref: 'User' })
createdBy?: Types.ObjectId;
@Column({ type: 'uuid', nullable: true })
createdBy?: string | null;
@Prop({ select: false })
refreshToken?: string;
@Column({ type: 'text', nullable: true, select: false })
refreshToken?: string | null;
@Prop({ type: Object, default: {} })
@Column({ type: 'jsonb', default: () => "'{}'::jsonb" })
metadata!: Record<string, unknown>;
@CreateDateColumn({ type: 'timestamptz' })
createdAt!: Date;
@UpdateDateColumn({ type: 'timestamptz' })
updatedAt!: Date;
}
export const UserSchema = SchemaFactory.createForClass(User);
UserSchema.index({ role: 1, isActive: 1 });
UserSchema.index({ clientType: 1, appName: 1 });
+4 -7
View File
@@ -1,17 +1,14 @@
import { Module, forwardRef } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from '../auth/auth.module';
import { User, UserSchema } from './schemas/user.schema';
import { User } from './schemas/user.schema';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
@Module({
imports: [
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
forwardRef(() => AuthModule),
],
imports: [TypeOrmModule.forFeature([User]), forwardRef(() => AuthModule)],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService, MongooseModule],
exports: [UsersService],
})
export class UsersModule {}
+98 -80
View File
@@ -1,11 +1,11 @@
import {
Injectable,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { randomBytes } from 'crypto';
import { Not, QueryDeepPartialEntity, Repository } from 'typeorm';
import { AuditEvent } from '../common/enums/audit-event.enum';
import { ADMIN_ROLES, Role } from '../common/enums/role.enum';
import { AppException } from '../common/exceptions/app-exception';
import { isUniqueViolation, isUuid } from '../database/postgres.helpers';
import { AuditService } from '../audit/audit.service';
import { PasswordService } from '../auth/services/password.service';
import { AuthenticatedUser } from '../auth/interfaces/authenticated-user.interface';
@@ -13,9 +13,8 @@ import { CreateUserDto } from './dto/create-user.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UserMapper } from './mappers/user.mapper';
import { User, UserDocument } from './schemas/user.schema';
import { User } from './schemas/user.schema';
import { UserResponseDto } from './dto/user-response.dto';
import { AppException } from '../common/exceptions/app-exception';
export interface RequestContext {
ip?: string;
@@ -25,30 +24,35 @@ export interface RequestContext {
@Injectable()
export class UsersService {
constructor(
@InjectModel(User.name) private readonly userModel: Model<UserDocument>,
@InjectRepository(User) private readonly users: Repository<User>,
private readonly passwordService: PasswordService,
private readonly auditService: AuditService,
) {}
async findById(id: string): Promise<UserDocument> {
const user = await this.userModel.findById(id);
async findById(id: string): Promise<User> {
if (!isUuid(id)) {
throw new AppException('USER_NOT_FOUND');
}
const user = await this.users.findOne({ where: { id } });
if (!user) {
throw new AppException('USER_NOT_FOUND');
}
return user;
}
async findByUsername(username: string, includePassword = false): Promise<UserDocument | null> {
const query = this.userModel.findOne({ username: username.toLowerCase().trim() });
async findByUsername(username: string, includePassword = false): Promise<User | null> {
const query = this.users
.createQueryBuilder('user')
.where('user.username = :username', { username: username.toLowerCase().trim() });
if (includePassword) {
query.select('+password +refreshToken');
query.addSelect('user.password').addSelect('user.refreshToken');
}
return query.exec();
return query.getOne();
}
async findAll(): Promise<UserResponseDto[]> {
const users = await this.userModel.find().sort({ createdAt: -1 });
return users.map((u) => UserMapper.toResponseDto(u));
const users = await this.users.find({ order: { createdAt: 'DESC' } });
return users.map((user) => UserMapper.toResponseDto(user));
}
async create(
@@ -61,9 +65,7 @@ export class UsersService {
const username = dto.username.toLowerCase().trim();
const email = dto.email.toLowerCase().trim();
const existing = await this.userModel.findOne({
$or: [{ username }, { email }],
});
const existing = await this.users.findOne({ where: [{ username }, { email }] });
if (existing) {
throw new AppException('USERNAME_OR_EMAIL_EXISTS');
}
@@ -71,29 +73,39 @@ export class UsersService {
const passwordHash = await this.passwordService.hash(dto.password);
const apiKey = this.generateApiKey();
const user = await this.userModel.create({
fullName: dto.fullName,
username,
email,
mobile: dto.mobile,
password: passwordHash,
role: dto.role,
clientType: dto.clientType,
appName: dto.appName ?? '',
clientName: dto.clientName ?? '',
isActive: dto.isActive ?? true,
allowedInquiries: dto.allowedInquiries ?? [],
requestLimitPerMinute: dto.requestLimitPerMinute ?? 60,
requestLimitPerDay: dto.requestLimitPerDay ?? 10000,
apiKey,
passwordChangedAt: new Date(),
createdBy: new Types.ObjectId(actor.id),
metadata: dto.metadata ?? {},
});
let user: User;
try {
user = await this.users.save(
this.users.create({
fullName: dto.fullName,
username,
email,
mobile: dto.mobile,
password: passwordHash,
role: dto.role,
clientType: dto.clientType,
appName: dto.appName ?? '',
clientName: dto.clientName ?? '',
isActive: dto.isActive ?? true,
allowedInquiries: dto.allowedInquiries ?? [],
requestLimitPerMinute: dto.requestLimitPerMinute ?? 60,
requestLimitPerDay: dto.requestLimitPerDay ?? 10000,
apiKey,
passwordChangedAt: new Date(),
createdBy: isUuid(actor.id) ? actor.id : null,
metadata: dto.metadata ?? {},
}),
);
} catch (error) {
if (isUniqueViolation(error)) {
throw new AppException('USERNAME_OR_EMAIL_EXISTS');
}
throw error;
}
await this.auditService.log(AuditEvent.USER_CREATED, {
actorId: actor.id,
userId: user._id.toString(),
userId: user.id,
username: user.username,
ip: context.ip,
userAgent: context.userAgent,
@@ -110,33 +122,36 @@ export class UsersService {
this.assertCanAssignRole(actor.role, dto.role);
}
const changes: Partial<User> = {};
if (dto.email) {
const email = dto.email.toLowerCase().trim();
const conflict = await this.userModel.findOne({ email, _id: { $ne: id } });
const conflict = await this.users.findOne({ where: { email, id: Not(id) } });
if (conflict) {
throw new AppException('EMAIL_ALREADY_IN_USE');
}
user.email = email;
changes.email = email;
}
Object.assign(user, {
...(dto.fullName !== undefined && { fullName: dto.fullName }),
...(dto.mobile !== undefined && { mobile: dto.mobile }),
...(dto.role !== undefined && { role: dto.role }),
...(dto.clientType !== undefined && { clientType: dto.clientType }),
...(dto.appName !== undefined && { appName: dto.appName }),
...(dto.clientName !== undefined && { clientName: dto.clientName }),
...(dto.isActive !== undefined && { isActive: dto.isActive }),
...(dto.allowedInquiries !== undefined && { allowedInquiries: dto.allowedInquiries }),
...(dto.requestLimitPerMinute !== undefined && {
requestLimitPerMinute: dto.requestLimitPerMinute,
}),
...(dto.requestLimitPerDay !== undefined && { requestLimitPerDay: dto.requestLimitPerDay }),
...(dto.metadata !== undefined && { metadata: dto.metadata }),
});
if (dto.fullName !== undefined) changes.fullName = dto.fullName;
if (dto.mobile !== undefined) changes.mobile = dto.mobile;
if (dto.role !== undefined) changes.role = dto.role;
if (dto.clientType !== undefined) changes.clientType = dto.clientType;
if (dto.appName !== undefined) changes.appName = dto.appName;
if (dto.clientName !== undefined) changes.clientName = dto.clientName;
if (dto.isActive !== undefined) changes.isActive = dto.isActive;
if (dto.allowedInquiries !== undefined) changes.allowedInquiries = dto.allowedInquiries;
if (dto.requestLimitPerMinute !== undefined) {
changes.requestLimitPerMinute = dto.requestLimitPerMinute;
}
if (dto.requestLimitPerDay !== undefined) changes.requestLimitPerDay = dto.requestLimitPerDay;
if (dto.metadata !== undefined) changes.metadata = dto.metadata;
await user.save();
return UserMapper.toResponseDto(user);
if (Object.keys(changes).length > 0) {
await this.users.update(user.id, changes as QueryDeepPartialEntity<User>);
}
return UserMapper.toResponseDto(await this.findById(id));
}
async block(
@@ -145,12 +160,10 @@ export class UsersService {
context: RequestContext = {},
): Promise<UserResponseDto> {
const user = await this.findById(id);
if (user._id.toString() === actor.id) {
if (user.id === actor.id) {
throw new AppException('CANNOT_BLOCK_SELF');
}
user.isBlocked = true;
user.refreshToken = undefined;
await user.save();
await this.users.update(user.id, { isBlocked: true, refreshToken: null });
await this.auditService.log(AuditEvent.USER_BLOCKED, {
actorId: actor.id,
@@ -160,7 +173,7 @@ export class UsersService {
userAgent: context.userAgent,
});
return UserMapper.toResponseDto(user);
return UserMapper.toResponseDto(await this.findById(id));
}
async unblock(
@@ -169,8 +182,7 @@ export class UsersService {
context: RequestContext = {},
): Promise<UserResponseDto> {
const user = await this.findById(id);
user.isBlocked = false;
await user.save();
await this.users.update(user.id, { isBlocked: false });
await this.auditService.log(AuditEvent.USER_UNBLOCKED, {
actorId: actor.id,
@@ -180,7 +192,7 @@ export class UsersService {
userAgent: context.userAgent,
});
return UserMapper.toResponseDto(user);
return UserMapper.toResponseDto(await this.findById(id));
}
async resetPassword(
@@ -189,15 +201,12 @@ export class UsersService {
actor: AuthenticatedUser,
context: RequestContext = {},
): Promise<void> {
const user = await this.userModel.findById(id).select('+password +refreshToken');
if (!user) {
throw new AppException('USER_NOT_FOUND');
}
user.password = await this.passwordService.hash(dto.newPassword);
user.passwordChangedAt = new Date();
user.refreshToken = undefined;
await user.save();
const user = await this.findById(id);
await this.users.update(user.id, {
password: await this.passwordService.hash(dto.newPassword),
passwordChangedAt: new Date(),
refreshToken: null,
});
await this.auditService.log(AuditEvent.PASSWORD_RESET, {
actorId: actor.id,
@@ -209,16 +218,23 @@ export class UsersService {
}
async saveRefreshToken(userId: string, refreshToken: string): Promise<void> {
if (!isUuid(userId)) return;
const hash = await this.passwordService.hash(refreshToken);
await this.userModel.findByIdAndUpdate(userId, { refreshToken: hash });
await this.users.update(userId, { refreshToken: hash });
}
async clearRefreshToken(userId: string): Promise<void> {
await this.userModel.findByIdAndUpdate(userId, { $unset: { refreshToken: 1 } });
if (!isUuid(userId)) return;
await this.users.update(userId, { refreshToken: null });
}
async validateRefreshToken(userId: string, refreshToken: string): Promise<boolean> {
const user = await this.userModel.findById(userId).select('+refreshToken');
if (!isUuid(userId)) return false;
const user = await this.users
.createQueryBuilder('user')
.addSelect('user.refreshToken')
.where('user.id = :userId', { userId })
.getOne();
if (!user?.refreshToken) {
return false;
}
@@ -226,11 +242,13 @@ export class UsersService {
}
async recordLogin(userId: string): Promise<void> {
await this.userModel.findByIdAndUpdate(userId, { lastLoginAt: new Date() });
if (!isUuid(userId)) return;
await this.users.update(userId, { lastLoginAt: new Date() });
}
async incrementTotalRequests(userId: string): Promise<void> {
await this.userModel.findByIdAndUpdate(userId, { $inc: { totalRequests: 1 } });
if (!isUuid(userId)) return;
await this.users.increment({ id: userId }, 'totalRequests', 1);
}
private assertCanAssignRole(actorRole: Role, targetRole: Role): void {