react-antd-admin-panel
Version:
Modern TypeScript-first React admin panel builder with Ant Design 6
106 lines • 2.6 kB
JavaScript
/**
* UserState - Manages authenticated user state
* Provides reactive user context with subscriptions
*
* @example
* const userState = new UserState();
* userState.set({ id: 1, name: 'John', email: 'john@example.com', role: 'admin' });
* userState.subscribe((user) => console.log('User changed:', user));
* userState.hasPermission('users.create');
*/
export class UserState {
_user = null;
_subscribers = new Set();
/**
* Get the current user
*/
get() {
return this._user;
}
/**
* Set the current user
*/
set(user) {
this._user = user;
this._notifySubscribers();
}
/**
* Update user properties
*/
update(updates) {
if (this._user) {
this._user = { ...this._user, ...updates };
this._notifySubscribers();
}
}
/**
* Clear the current user (logout)
*/
clear() {
this._user = null;
this._notifySubscribers();
}
/**
* Check if a user is authenticated
*/
isAuthenticated() {
return this._user !== null;
}
/**
* Check if user has a specific role
*/
hasRole(role) {
return this._user?.role === role;
}
/**
* Check if user has any of the specified roles
*/
hasAnyRole(roles) {
return roles.includes(this._user?.role ?? '');
}
/**
* Check if user has a specific permission
*/
hasPermission(permission) {
return this._user?.permissions?.includes(permission) ?? false;
}
/**
* Check if user has all specified permissions
*/
hasAllPermissions(permissions) {
if (!this._user?.permissions)
return false;
return permissions.every(p => this._user.permissions.includes(p));
}
/**
* Check if user has any of the specified permissions
*/
hasAnyPermission(permissions) {
if (!this._user?.permissions)
return false;
return permissions.some(p => this._user.permissions.includes(p));
}
/**
* Get a user property
*/
getProperty(key) {
return this._user?.[key];
}
/**
* Subscribe to user changes
* Returns an unsubscribe function
*/
subscribe(callback) {
this._subscribers.add(callback);
return () => {
this._subscribers.delete(callback);
};
}
/**
* Notify all subscribers
*/
_notifySubscribers() {
this._subscribers.forEach(callback => callback(this._user));
}
}
//# sourceMappingURL=UserState.js.map