import { AggregateRoot, Result, UniqueID } from "@common/domain"; import { UserAuthenticatedEvent } from "../events"; import { EmailAddress, HashPassword, PlainPassword, Username } from "../value-objects"; export interface IAuthenticatedUserProps { username: Username; email: EmailAddress; hashPassword: HashPassword; roles: string[]; } export interface IAuthenticatedUser { username: Username; email: EmailAddress; accessToken: string; refreshToken: string; isUser: boolean; isAdmin: boolean; verifyPassword(candidatePassword: PlainPassword): Promise; hasRole(role: string): boolean; hasRoles(roles: string[]): boolean; getRoles(): string[]; toPersistenceData(): any; } export class AuthenticatedUser extends AggregateRoot implements IAuthenticatedUser { public accessToken: string = ""; public refreshToken: string = ""; static create(props: IAuthenticatedUserProps, id: UniqueID): Result { const user = new AuthenticatedUser(props, id); // 🔹 Disparar evento de dominio "UserAuthenticatedEvent" const { email } = props; user.addDomainEvent(new UserAuthenticatedEvent(id, email.toString())); return Result.ok(user); } verifyPassword(candidatePassword: PlainPassword): Promise { return this._props.hashPassword.verifyPassword(candidatePassword.toString()); } getRoles(): string[] { return this._props.roles; } hasRole(role: string): boolean { return (this._props.roles || []).some((r) => r === role); } hasRoles(roles: string[]): boolean { return roles.map((rol) => this.hasRole(rol)).some((value) => value != false); } get username(): Username { return this._props.username; } get email(): EmailAddress { return this._props.email; } get isUser(): boolean { return this.hasRole("user"); } get isAdmin(): boolean { return this.hasRole("admin"); } /** * 🔹 Devuelve una representación lista para persistencia */ toPersistenceData(): any { return { id: this._id.toString(), username: this._props.username.toString(), email: this._props.email.toString(), hash_password: this._props.hashPassword.toString(), roles: this._props.roles.map((role) => role.toString()), access_token: this.accessToken, refresh_token: this.refreshToken, }; } }