UNPKG

@rnaga/wp-node

Version:

👉 **[View Full Documentation at rnaga.github.io/wp-node →](https://rnaga.github.io/wp-node/)**

274 lines (273 loc) • 10.9 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.User = void 0; const config_1 = require("../config"); const constants_1 = require("../constants"); const async_init_1 = require("../decorators/async-init"); const component_1 = require("../decorators/component"); const val = __importStar(require("../validators")); const components_1 = require("./components"); const current_1 = require("./current"); const logger_1 = require("./logger"); const meta_1 = require("./meta"); const options_1 = require("./options"); const role_1 = require("./role"); const roles_1 = require("./roles"); const query_util_1 = require("./utils/query.util"); const user_util_1 = require("./utils/user.util"); let User = class User { meta; logger; queryUtil; components; config; userRef; _props; _roles; _role; constructor(meta, logger, queryUtil, components, config, userRef, _props, _roles) { this.meta = meta; this.logger = logger; this.queryUtil = queryUtil; this.components = components; this.config = config; this.userRef = userRef; this._props = _props; this._roles = _roles; this._role = this.components.get(role_1.Role); } async hasCapabilities(capabilities, options) { const userUtil = this.components.get(user_util_1.UserUtil); return userUtil.hasCapabilities(this, capabilities, options); } async role() { await this.roles(); return this._role; } async roles() { if (!this._roles) { this.setAnonymous(); } const user = this._props; const current = this.components.get(current_1.Current); const roles = []; this.meta.set("user", this._props.ID); // Grab and set a role from database const rolesMeta = (await this.meta.get(`${current.tables.prefix}capabilities`)) ?? {}; for (const [key] of Object.entries(rolesMeta)) { roles.push(key); } // Get the first role in array let primaryRoleName = roles[0]; // Check super admin // get_super_admins // get_site_option( 'site_admins', array( 'admin' ) ) const options = this.components.get(options_1.Options); if (this.config.isMultiSite()) { const superAdmins = await options.get("site_admins", { siteId: current.site?.props.site?.id, //serialized: true, }); if (Array.isArray(superAdmins) && superAdmins.includes(user.user_login)) { roles.push("superadmin"); primaryRoleName = "superadmin"; } } const roleJson = this.components.get(roles_1.Roles).get(primaryRoleName); const role = this.components.get(role_1.Role, [ roleJson?.name, roleJson?.capabilities, ]); // If user has more than one role, add its names and capabilities to a role if (roles.length > 1) { role.addNames(roles); for (const roleName of roles.slice(1)) { const roleJson = this.components.get(roles_1.Roles).get(roleName); Array.isArray(roleJson?.capabilities) && role.add(roleJson.capabilities); } } this._roles = roles; this._role = role; return this._roles; } get props() { return !this._props || 0 >= this._props.ID ? undefined : this._props; } setDefaultProps(id = -1) { this._props = { ...this._props, ID: id, }; this._roles = []; } setAnonymous() { this.setDefaultProps(-1); } async can(action, ...args) { const role = await this.role(); return await role.can(action, this, ...args); } // async bulkCan<T extends types.RoleCapabilityActions>( // actionOrArrArgs: [T, ...types.TMapMetaCapArgs<T>[]][], // arrArgs?: never // ): Promise<[T, types.TMapMetaCapArgs<T>, boolean][]>; // async bulkCan<T extends types.RoleCapabilityActions>( // actionOrArrArgs: T, // arrArgs: types.TMapMetaCapArgs<T>[] // ): Promise<[T, types.TMapMetaCapArgs<T>, boolean][]>; // async bulkCan(actionOrArrArgs: any, arrArgs?: any[]) { // let bulkArgs: any[] = []; // if (Array.isArray(actionOrArrArgs)) { // bulkArgs = actionOrArrArgs; // } else { // arrArgs?.map((args) => bulkArgs.push([actionOrArrArgs, ...args])); // } // const results = []; // for (const [action, ...args] of bulkArgs) { // const result = await this.can(action, ...(args as any)); // results.push([action, args, result]); // } // return results; // } async bulkCan(actionOrArrArgs, arrArgs) { let bulkArgs = []; // Check if the first argument is an array and handle it accordingly if (Array.isArray(actionOrArrArgs)) { if (actionOrArrArgs.length > 0 && Array.isArray(actionOrArrArgs[0])) { // Handle the case when the first argument is an array of arrays bulkArgs = actionOrArrArgs; } else { // Handle the case when the first argument is just an array (of arguments for a single action) bulkArgs.push(actionOrArrArgs); } } else { // Handle the case when the first argument is a single action and the second is an array of arguments arrArgs?.forEach((args) => bulkArgs.push([actionOrArrArgs, ...args])); } const results = []; for (const [action, ...args] of bulkArgs) { const result = await this.can(action, ...args); results.push([action, args, result]); } return results; } // async bulkCan<T extends types.RoleCapabilityActions>( // actionOrArrArgs: T | [T, ...types.TMapMetaCapArgs<T>[]][], // arrArgs?: types.TMapMetaCapArgs<T>[] // ): Promise<[T, types.TMapMetaCapArgs<T>[], boolean][]> { // let bulkArgs: [T, ...types.TMapMetaCapArgs<T>[]][] = []; // if ( // Array.isArray(actionOrArrArgs) && // actionOrArrArgs.every((item: any) => Array.isArray(item)) // ) { // // When actionOrArrArgs is an array of arrays, cast it directly. // bulkArgs = actionOrArrArgs as [T, ...types.TMapMetaCapArgs<T>[]][]; // } else if (!Array.isArray(actionOrArrArgs) && arrArgs) { // // When actionOrArrArgs is a single action and arrArgs are provided. // bulkArgs = arrArgs.map((args: any) => [actionOrArrArgs, ...args]); // } // const results: [T, types.TMapMetaCapArgs<T>[], boolean][] = []; // for (const [action, ...args] of bulkArgs) { // const result = await this.can( // action, // ...(args as types.TMapMetaCapArgs<T>) // ); // results.push([action, args, result]); // } // return results; // } async init() { this.setDefaultProps(this._props?.ID); let user = this._props; if (typeof this._props?.ID === "undefined" || 0 >= this._props?.ID) { if (!this.userRef) return; const result = await this.queryUtil.users((query) => { query.get(this.userRef); }, val.database.wpUsers); if (!result) { this.logger.info(`User not found: ${this.userRef}`); return; } // Set props this._props = result; user = result; } else if ( // Sync userRef (typeof this.userRef == "number" && user.ID !== this.userRef) || (typeof this.userRef == "string" && user.user_nicename !== this.userRef && user.display_name !== this.userRef && user.user_email !== this.userRef)) { this.userRef = user.ID; } this.meta.set("user", this._props.ID); // Set props with valid role and roles this._props = { ...this._props, ...user, }; return this; } }; exports.User = User; __decorate([ async_init_1.asyncInit, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", Promise) ], User.prototype, "init", null); exports.User = User = __decorate([ (0, component_1.component)({ scope: constants_1.Scope.Transient }), __metadata("design:paramtypes", [meta_1.Meta, logger_1.Logger, query_util_1.QueryUtil, components_1.Components, config_1.Config, Object, Object, Array]) ], User);