hjortur17
4 months ago

Authorization with Vue

Posted 4 months ago by hjortur17

Hi, I'm trying to create Vue Component and to make this component function correctly I need to do authorization. On my User.php I have isAdmin method and a middleware called admin but in Vue I need to check if the sign in user has a role = admin

Here is what I tried, (authorizations.js)

let user = window.App.user;

module.exports = {
    owns (model, prop = 'user_id') {
        return model[prop] === user.id;
    },

    isAdmin() {
        return ['admin'].includes(user.role);
    }
};

And this is in my master.blade.php:

window.App ={!! json_encode([
            'signedIn' => Auth::check(),
            'user' => Auth::user(),
        ]) !!};

And this in my bootstrap.js file:

window.Vue = require('vue');

let authorizations = require('./authorizations.js');

Vue.prototype.authorize = function(...params) {
    if (! window.App.signedIn) return false;

    if (typeof params[0] === 'string') {
        return authorizations[params[0]](params[1]);
    }

    return params[0](window.App.user);
};

Please sign in or create an account to participate in this conversation.