services/UserAccessService.jsjavascript
"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 __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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = require("../utils/errors.js");
const user_1 = __importDefault(require("../db/models/user"));
const userAccess_1 = __importStar(require("../db/models/userAccess"));
const FeatureFlagService_1 = __importStar(require("./FeatureFlagService"));
const { logger } = require("../plugins/winston");
/**
 * Service for managing user access relationships.
 * Handles CRUD operations for owner-child access permissions.
 * A child can have access to multiple owners.
 *
 * @class UserAccessService
 */
class UserAccessService {
    /**
     * Check if the ACCESS_SHARING feature flag is enabled.
     * @returns {Promise<boolean>} True if access sharing is enabled.
     */
    async isAccessSharingEnabled() {
        return FeatureFlagService_1.default.isEnabled(FeatureFlagService_1.FeatureFlagKey.ACCESS_SHARING);
    }
    /**
     * Find a user access relationship by owner and child IDs.
     * @param {UUID} ownerId - The owner's user ID.
     * @param {UUID} childId - The child's user ID.
     * @returns {Promise<UserAccess | null>} The user access object or null if not found.
     */
    async findByOwnerAndChild(ownerId, childId) {
        if (!(await this.isAccessSharingEnabled()))
            return null;
        logger.debug(`UserAccessService findByOwnerAndChild ${JSON.stringify({ ownerId, childId })}`);
        return userAccess_1.default.findOne({
            where: { ownerUserId: ownerId, childUserId: childId },
        });
    }
    /**
     * Get all children for an owner.
     * @param {UUID} ownerId - The owner's user ID.
     * @returns {Promise<Array>} Array of user access objects.
     */
    async getChildren(ownerId) {
        if (!(await this.isAccessSharingEnabled()))
            return [];
        logger.debug(`UserAccessService getChildren ${JSON.stringify({ ownerId })}`);
        return userAccess_1.default.findAll({
            where: { ownerUserId: ownerId },
            include: [{ model: user_1.default, as: "child" }],
        });
    }
    /**
     * Get all owners for a child.
     * @param {UUID} childId - The child's user ID.
     * @returns {Promise<Array>} Array of user access objects.
     */
    async getOwners(childId) {
        if (!(await this.isAccessSharingEnabled()))
            return [];
        logger.debug(`UserAccessService getOwners ${JSON.stringify({ childId })}`);
        return userAccess_1.default.findAll({
            where: { childUserId: childId },
            include: [{ model: user_1.default, as: "owner" }],
        });
    }
    /**
     * Create a new user access relationship.
     * @param {UUID} ownerId - The owner's user ID.
     * @param {UUID} childId - The child's user ID.
     * @param {AccessRole} role - The access role.
     * @param {boolean} enabled - Whether the access is enabled.
     * @returns {Promise<UserAccess>} The created user access object.
     */
    async create(ownerId, childId, role = userAccess_1.AccessRole.ATHLETE, enabled = true) {
        if (!(await this.isAccessSharingEnabled())) {
            throw new errors_1.AccessDeniedError("Access sharing is disabled");
        }
        logger.debug(`UserAccessService create ${JSON.stringify({ ownerId, childId, role, enabled })}`);
        const existing = await userAccess_1.default.findOne({
            where: { ownerUserId: ownerId, childUserId: childId },
        });
        if (existing) {
            throw new Error("User access relationship already exists");
        }
        return userAccess_1.default.create({
            ownerUserId: ownerId,
            childUserId: childId,
            role,
            enabled,
        });
    }
    /**
     * Update an existing user access relationship.
     * @param {UUID} id - The user access ID.
     * @param {object} data - The data to update (role, enabled).
     * @param {UUID} ownerId - The owner's user ID (for authorization).
     * @returns {Promise<UserAccess>} The updated user access object.
     */
    async update(id, data, ownerId) {
        if (!(await this.isAccessSharingEnabled())) {
            throw new errors_1.AccessDeniedError("Access sharing is disabled");
        }
        logger.debug(`UserAccessService update ${JSON.stringify({ id, data, ownerId })}`);
        const access = await userAccess_1.default.findOne({
            where: { id, ownerUserId: ownerId },
        });
        if (!access) {
            throw new errors_1.NotFoundError(`User access with id ${id} not found`);
        }
        return access.update(data);
    }
    /**
     * Remove a user access relationship.
     * @param {UUID} id - The user access ID.
     * @param {UUID} ownerId - The owner's user ID (for authorization).
     * @returns {Promise<void>}
     */
    async remove(id, ownerId) {
        if (!(await this.isAccessSharingEnabled())) {
            throw new errors_1.AccessDeniedError("Access sharing is disabled");
        }
        logger.debug(`UserAccessService remove ${JSON.stringify({ id, ownerId })}`);
        const access = await userAccess_1.default.findOne({
            where: { id, ownerUserId: ownerId },
        });
        if (!access) {
            throw new errors_1.NotFoundError(`User access with id ${id} not found`);
        }
        return access.destroy();
    }
    /**
     * Accept an access invitation.
     * @param {UUID} id - The user access ID.
     * @param {UUID} childId - The child's user ID (for authorization).
     * @returns {Promise<UserAccess>} The updated user access object.
     */
    async accept(id, childId) {
        if (!(await this.isAccessSharingEnabled())) {
            throw new errors_1.AccessDeniedError("Access sharing is disabled");
        }
        logger.debug(`UserAccessService accept ${JSON.stringify({ id, childId })}`);
        const access = await userAccess_1.default.findOne({
            where: { id, childUserId: childId },
        });
        if (!access) {
            throw new errors_1.NotFoundError(`User access with id ${id} not found`);
        }
        return access.update({ accepted: true });
    }
    /**
     * Decline an access invitation.
     * @param {UUID} id - The user access ID.
     * @param {UUID} childId - The child's user ID (for authorization).
     * @returns {Promise<UserAccess>} The deleted user access object.
     */
    async decline(id, childId) {
        if (!(await this.isAccessSharingEnabled())) {
            throw new errors_1.AccessDeniedError("Access sharing is disabled");
        }
        logger.debug(`UserAccessService decline ${JSON.stringify({ id, childId })}`);
        const access = await userAccess_1.default.findOne({
            where: { id, childUserId: childId },
        });
        if (!access) {
            throw new errors_1.NotFoundError(`User access with id ${id} not found`);
        }
        return access.destroy();
    }
    /**
     * Find a user by username.
     * @param {string} username - The username to search for.
     * @returns {Promise<User | null>} The user object or null if not found.
     */
    async findByUsername(username) {
        return user_1.default.findOne({ where: { username } });
    }
    /**
     * Check if a user has access to another user's data.
     * @param {UUID} ownerId - The owner's user ID.
     * @param {UUID} childId - The child's user ID.
     * @returns {Promise<boolean>} Whether the child has access.
     */
    async hasAccess(ownerId, childId) {
        if (!(await this.isAccessSharingEnabled()))
            return false;
        const access = await userAccess_1.default.findOne({
            where: {
                ownerUserId: ownerId,
                childUserId: childId,
                enabled: true,
                accepted: true,
            },
        });
        return !!access;
    }
    /**
     * Get the role for a child accessing owner's data.
     * @param ownerId - The owner's user ID.
     * @param childId - The child's user ID.
     * @returns {Promise<AccessRole | null>} The role or null if no access.
     */
    async getRole(ownerId, childId) {
        if (!(await this.isAccessSharingEnabled()))
            return null;
        const access = await userAccess_1.default.findOne({
            where: {
                ownerUserId: ownerId,
                childUserId: childId,
                enabled: true,
                accepted: true,
            },
        });
        return access?.role || null;
    }
}
exports.default = new UserAccessService();