yoho-plugin-user.js 2.25 KB
/**
 * 权限插件
 */
import axios from 'axios';
import config from 'config';
import userService from 'user-service';
import _ from 'lodash';

const plugin = {
    install(Vue) {
        // 登录验证权限
        Vue.mixin({
            beforeRouteEnter(to, from, next) {
                if (to.matched && to.matched.length > 0) {
                    let loginPass = _.get(_.last(to.matched), 'meta.loginPass', false);
                    let userInfo = Vue.$store.get(config.userKey);
                    let pruviews = Vue.$store.get(config.purviewKey);

                    if (loginPass) {
                        return next();
                    }
                    if (userInfo) {
                        if (to.name === 'auth.login') {
                            return next('/');
                        }
                        if (!Vue.prototype.$user) {
                            Vue.updateUser(userInfo);
                        }
                        if (!pruviews) {

                        }
                        return next();
                    } else {
                        return next('/login.html');
                    }
                }
                return next('/login.html');
            }
        });
        Vue.passport = {
            local: (username, password) => {
                return userService.login(username, password).then((res) => {
                    if (res.code === 200) {
                        Vue.updateUser(res.data);
                        // return userService.purviews().then(resPurviews => {
                            return res.data;
                        // });
                    }
                    return Promise.reject(res);
                });
            }
        };
        Vue.logout = () => {
            Vue.$store.remove(config.userKey);
            Vue.$router.push('/login.html');
            axios.post('/logout');
        };
        Vue.updateUser = (user) => {
            Vue.$store.set(config.userKey, user);
            Vue.prototype.isLogin = Vue.isLogin = true;
            Vue.prototype.$user = user;
            axios.defaults.headers.post.shopsId = user.currentShop.id;
            axios.defaults.headers.get.shopsId = user.currentShop.id;
        };
    }
};

export default plugin;