Uecko_ERP/apps/server/src/contexts/auth/domain/aggregates/authenticated-user.ts

42 lines
1.3 KiB
TypeScript
Raw Normal View History

2025-02-01 21:48:13 +00:00
import { AggregateRoot, Result, UniqueID } from "@common/domain";
import { UserAuthenticatedEvent } from "../events";
2025-02-03 13:12:36 +00:00
import { EmailAddress, PasswordHash, Username } from "../value-objects";
2025-02-01 21:48:13 +00:00
export interface IAuthenticatedUserProps {
username: Username;
email: EmailAddress;
2025-02-03 13:12:36 +00:00
passwordHash: PasswordHash;
2025-02-01 21:48:13 +00:00
roles: string[];
token: string;
}
export class AuthenticatedUser extends AggregateRoot<IAuthenticatedUserProps> {
2025-02-03 13:12:36 +00:00
static create(props: IAuthenticatedUserProps, id: UniqueID): Result<AuthenticatedUser, Error> {
const user = new AuthenticatedUser(props, id);
2025-02-01 21:48:13 +00:00
// 🔹 Disparar evento de dominio "UserAuthenticatedEvent"
2025-02-03 13:12:36 +00:00
const { email } = props;
2025-02-01 21:48:13 +00:00
user.addDomainEvent(new UserAuthenticatedEvent(id, email.toString()));
return Result.ok(user);
}
2025-02-03 18:03:23 +00:00
comparePassword(plainPassword: string): Promise<boolean> {
return this._props.passwordHash.compare(plainPassword);
}
2025-02-01 21:48:13 +00:00
/**
* 🔹 Devuelve una representación lista para persistencia
*/
2025-02-03 13:12:36 +00:00
toPersistenceData(): any {
2025-02-01 21:48:13 +00:00
return {
id: this._id.toString(),
username: this._props.username.toString(),
email: this._props.email.toString(),
2025-02-03 13:12:36 +00:00
password: this._props.passwordHash.toString(),
2025-02-03 18:03:23 +00:00
roles: this._props.roles.map((role) => role.toString()),
2025-02-01 21:48:13 +00:00
token: this._props.token,
};
}
}