2025-02-20 18:55:24 +00:00
|
|
|
import { AggregateRoot, EmailAddress, Result, UniqueID } from "@common/domain";
|
2025-02-15 21:30:12 +00:00
|
|
|
import { UserAuthenticatedEvent } from "../events";
|
2025-02-20 18:55:24 +00:00
|
|
|
import { Username } from "../value-objects";
|
2025-02-15 21:30:12 +00:00
|
|
|
|
|
|
|
|
export interface IUserProps {
|
|
|
|
|
username: Username;
|
|
|
|
|
email: EmailAddress;
|
|
|
|
|
roles: string[];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface IUser {
|
|
|
|
|
username: Username;
|
|
|
|
|
email: EmailAddress;
|
|
|
|
|
|
|
|
|
|
isUser: boolean;
|
|
|
|
|
isAdmin: boolean;
|
|
|
|
|
|
|
|
|
|
hasRole(role: string): boolean;
|
|
|
|
|
hasRoles(roles: string[]): boolean;
|
|
|
|
|
getRoles(): string[];
|
|
|
|
|
toPersistenceData(): any;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export class User extends AggregateRoot<IUserProps> implements IUser {
|
|
|
|
|
static create(props: IUserProps, id: UniqueID): Result<User, Error> {
|
|
|
|
|
const user = new User(props, id);
|
|
|
|
|
|
|
|
|
|
// 🔹 Disparar evento de dominio "UserAuthenticatedEvent"
|
|
|
|
|
const { email } = props;
|
|
|
|
|
user.addDomainEvent(new UserAuthenticatedEvent(id, email.toString()));
|
|
|
|
|
|
|
|
|
|
return Result.ok(user);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
getRoles(): string[] {
|
2025-02-20 18:55:24 +00:00
|
|
|
return this.props.roles;
|
2025-02-15 21:30:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
hasRole(role: string): boolean {
|
2025-02-20 18:55:24 +00:00
|
|
|
return (this.props.roles || []).some((r) => r === role);
|
2025-02-15 21:30:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
hasRoles(roles: string[]): boolean {
|
|
|
|
|
return roles.map((rol) => this.hasRole(rol)).some((value) => value != false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
get username(): Username {
|
2025-02-20 18:55:24 +00:00
|
|
|
return this.props.username;
|
2025-02-15 21:30:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
get email(): EmailAddress {
|
2025-02-20 18:55:24 +00:00
|
|
|
return this.props.email;
|
2025-02-15 21:30:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
get isUser(): boolean {
|
|
|
|
|
return this.hasRole("user");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
get isAdmin(): boolean {
|
|
|
|
|
return this.hasRole("admin");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 🔹 Devuelve una representación lista para persistencia
|
|
|
|
|
*/
|
|
|
|
|
toPersistenceData(): any {
|
|
|
|
|
return {
|
2025-02-20 18:55:24 +00:00
|
|
|
id: this.id.toString(),
|
|
|
|
|
username: this.props.username.toString(),
|
|
|
|
|
email: this.props.email.toString(),
|
|
|
|
|
roles: this.props.roles.map((role) => role.toString()),
|
2025-02-15 21:30:12 +00:00
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|