All files / src/store/modules auth.module.js

96.55% Statements 28/29
95.45% Branches 21/22
90.9% Functions 10/11
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65        2x   2x           2x   3x 3x 3x       2x   2x 2x       3x 3x 2x 1x 1x   2x 2x         2x 3x   2x     6x 6x     5x 8x 8x     5x                    
import { AUTH_ACT, AUTH_GET, AUTH_MUT } from '../types';
import { hasPermission } from '../../utils/permissions';
import createLogger from '../../utils/logger';
 
const log = createLogger('auth');
 
const state = () => ({
  user: null,
  isAuthenticated: false,
  expiresAt: null,
});
 
const mutations = {
  [AUTH_MUT.setUser](s, userData) {
    s.isAuthenticated = !!userData?.isAuthenticated;
    s.user = userData?.user || null;
    s.expiresAt = userData?.expiresAt || null;
  },
};
 
const actions = {
  async [AUTH_ACT.hydrate]({ commit }, initial = {}) {
    const ssrUser = initial?.pageData?.userData;
    if (ssrUser) commit(AUTH_MUT.setUser, ssrUser);
  },
 
  async [AUTH_ACT.fetchUser]({ commit }) {
    try {
      const res = await fetch('/auth/user', { credentials: 'same-origin' });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      commit(AUTH_MUT.setUser, json);
    } catch (err) {
      log.error('fetchUser failed:', err);
      throw err;
    }
  },
};
 
const getters = {
  [AUTH_GET.user]: (s, _g, root) => s.user || root.pageData?.userData?.user || null,
 
  [AUTH_GET.isAuthenticated]: (s, _g, root) => s.isAuthenticated || !!root.pageData?.userData?.isAuthenticated,
 
  [AUTH_GET.roles]: (s, _g, root) => {
    const user = s.user || root.pageData?.userData?.user;
    return user?.roles ?? [];
  },
 
  [AUTH_GET.hasRole]: (s, _g, root) => (role) => {
    const user = s.user || root.pageData?.userData?.user;
    return Array.isArray(user?.roles) && user.roles.includes(role);
  },
 
  [AUTH_GET.can]: (s, g) => (action) => hasPermission(action, g[AUTH_GET.roles]),
};
 
export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions,
};