moleculerjs / database

Advanced Database Access Service for Moleculer microservices framework
MIT License
32 stars 15 forks source link

Change scope handling logic #15

Closed icebob closed 2 years ago

icebob commented 2 years ago

Closes #13.

Breaking change

Old behaviour The scope: ["onlyActive"] disabled all default scopes and added the onlyActive scope.

New behaviour The scope: ["onlyActive"] added the onlyActive scope besides all default scopes.

Disabling default scopes

To disable a default scope, use the - (minus) sign before the scope name. E.g: scope: ["-onlyActive", "myScope"]

Disabling all scopes

It's not changed. Use scope: false

checkScopeAuthority signature changed.

The checkScopeAuthority method signature is changed to support the new default scope disabling logic.

        /**
         * Check the scope authority. Should be implemented in the service.
         *
         * @param {Context} ctx
         * @param {String} name
         * @param {String} operation Values: "add", "remove"
         * @param {Object} scope
         */
        async checkScopeAuthority(ctx, name, operation, scope) {
            return true;
        },

Full example

This example demonstrates a tenant scope authorization. It disables removing tenant scope for users, but allows for administrators.

module.exports = {
    name: "posts",
    mixins: [DbService()],
    settings: {
        fields: {/*...*/},

        scopes: {
            tenant(q, ctx) {
                q.tenantId = ctx.meta.tenantId;
                return q;
            },
            onlyActive: {
                status: true
            }
        },
        defaultScopes: ["tenant"]
    },

    methods: {
        async checkScopeAuthority(ctx, name, operation) {
            // Admin can add/remove any scopes
            if (ctx.meta.user.roles.includes("admin"))
                return true;

            // Disable removing tenant scope
            if (name == "tenant" && operation == "remove")
                return false;

            return true;
        }
    }
}
icebob commented 2 years ago

ping @vimalraj-a Is it cover your use-case, as well?