L
L
lemonlimelike2018-06-24 21:31:06
Vue.js
lemonlimelike, 2018-06-24 21:31:06

How to check user authorization?

Good evening everyone. I am developing an application in vue + laravel. I don't understand how to check if the user is logged in or not. On pure laravel I know how, but with the use of vue componennts I don’t really understand this. Let's say there is a div with a form for authorization, I hang v-if="????" on it. and there is another div if the user is already logged in, v-else on it... But what should I write in v-if? How to do this check? Declare a global variable? What to write into it, if you write it like this window.isLogin = {{Auth::check()}}, then such a record does not work.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Romashkan, 2018-06-24
@lemonlimelike

app.js - https://github.com/EvgeniiR/forum/blob/master/reso...

let authorizations = require('./authorizations')

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

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

    return params[0](window.App.user);
}
Vue.prototype.signedIn = window.App.signedIn;

authorizations.js - https://github.com/EvgeniiR/forum/blob/master/reso...
let user = window.App.user;

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

    isAdmin() {
        return user.name === 'admin';
    }
};

app.blade.php - https://github.com/EvgeniiR/forum/blob/master/reso...
<script>
        window.App = {!! json_encode([
            'user' => Auth::user(),
            'signedIn' => Auth::check()
        ]) !!};
</script>

Usage examples:
<div v-if="signedIn">- check if the user is authorized
v-if="authorize('owns', thread)", where user_id is set in the thread object - check if he is the owner.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question