Skip to content

Commit

Permalink
moving remaining references to session getters to the useUser composable
Browse files Browse the repository at this point in the history
  • Loading branch information
nathanaelg16 committed Aug 28, 2024
1 parent cef47b7 commit 8b79e1a
Show file tree
Hide file tree
Showing 39 changed files with 207 additions and 110 deletions.
4 changes: 2 additions & 2 deletions kolibri/core/assets/src/composables/useUserSyncStatus.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { SyncStatus } from 'kolibri.coreVue.vuex.constants';
import { get, useTimeoutPoll } from '@vueuse/core';
import useUser from './useUser';

const { isLearnerOnlyImport, isUserLoggedIn } = useUser();
const { isLearnerOnlyImport, isUserLoggedIn, currentUserId } = useUser();

const status = ref(SyncStatus.NOT_CONNECTED);
const queued = ref(false);
Expand Down Expand Up @@ -41,7 +41,7 @@ export function pollUserSyncStatusTask() {
if (!get(isUserLoggedIn) || !get(isLearnerOnlyImport)) {
return Promise.resolve();
}
return fetchUserSyncStatus({ user: store.state.core.session.user_id }).then(syncData => {
return fetchUserSyncStatus({ user: get(currentUserId) }).then(syncData => {
if (syncData && syncData[0]) {
queued.value = syncData[0].queued;
lastSynced.value = syncData[0].last_synced ? new Date(syncData[0].last_synced) : null;
Expand Down
7 changes: 4 additions & 3 deletions kolibri/core/assets/src/core-app/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { CancelToken } from 'axios';
import qs from 'qs';
import heartbeat from 'kolibri.heartbeat';
import logger from 'kolibri.lib.logging';
import store from 'kolibri.coreVue.vuex.store';
import { get } from '@vueuse/core';
import useUser from 'kolibri.coreVue.composables.useUser';
import errorCodes from '../disconnectionErrorCodes';
import useConnection from '../composables/useConnection';
import clientFactory from './baseClient';
Expand Down Expand Up @@ -41,15 +41,16 @@ baseClient.interceptors.response.use(
// if they were logged in.
if (error.response) {
if (error.response.status === 403) {
if (store.state.core.session.id && !store.state.core.session.user_id) {
const { id, user_id } = useUser();
if (get(id) && !get(user_id)) {
// We have session information but no user_id, which means we are not logged in
// This is a sign that the user has been logged out due to inactivity
heartbeat.signOutDueToInactivity();
} else {
// In this case, we should check right now if they are still logged in
heartbeat.pollSessionEndPoint().then(() => {
// If they are not, we should handle sign out
if (!store.state.core.session.user_id) {
if (!get(user_id)) {
heartbeat.signOutDueToInactivity();
}
});
Expand Down
5 changes: 3 additions & 2 deletions kolibri/core/assets/src/heartbeat.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import redirectBrowser from 'kolibri.utils.redirectBrowser';
import Lockr from 'lockr';
import urls from 'kolibri.urls';
import { get, set } from '@vueuse/core';
import useUser from 'kolibri.coreVue.composables.useUser';
import useConnection from './composables/useConnection';
import clientFactory from './core-app/baseClient';
import { SIGNED_OUT_DUE_TO_INACTIVITY } from './constants';
Expand Down Expand Up @@ -158,7 +159,7 @@ export class HeartBeat {
* @return {Promise} promise that resolves when the endpoint check is complete.
*/
_checkSession() {
const { currentUserId } = store.getters;
const { id, currentUserId } = useUser();
// Record the current user id to check if a different one is returned by the server.
if (!get(this._connection.connected)) {
// If not currently connected to the server, flag that we are currently trying to reconnect.
Expand All @@ -183,7 +184,7 @@ export class HeartBeat {
const pollEnd = Date.now();
const session = response.data;
// If our session is already defined, check the user id in the response
if (store.state.core.session.id && session.user_id !== currentUserId) {
if (get(id) && session.user_id !== get(currentUserId)) {
if (session.user_id === null) {
// If it is different, and the user_id is now null then our user has been signed out.
return this.signOutDueToInactivity();
Expand Down
9 changes: 6 additions & 3 deletions kolibri/core/assets/src/state/modules/core/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ import redirectBrowser from 'kolibri.utils.redirectBrowser';
import CatchErrors from 'kolibri.utils.CatchErrors';
import Vue from 'kolibri.lib.vue';
import Lockr from 'lockr';
import { set } from '@vueuse/core';
import { set, get } from '@vueuse/core';
import useUser from 'kolibri.coreVue.composables.useUser';
import { baseSessionState } from '../session';
import { LoginErrors, ERROR_CONSTANTS, UPDATE_MODAL_DISMISSED } from '../../../constants';
import { browser, os } from '../../../utils/browserInfo';
Expand Down Expand Up @@ -191,7 +192,8 @@ export function setPageVisibility(store) {
}

export function getNotifications(store) {
if (store.getters.isAdmin || store.getters.isSuperuser) {
const { isAdmin, isSuperuser } = useUser();
if (get(isAdmin) || get(isSuperuser)) {
return PingbackNotificationResource.fetchCollection()
.then(notifications => {
logging.info('Notifications set.');
Expand All @@ -205,8 +207,9 @@ export function getNotifications(store) {
}

export function saveDismissedNotification(store, notification_id) {
const { user_id } = useUser();
const dismissedNotificationData = {
user: store.getters.session.user_id,
user: get(user_id),
notification: notification_id,
};
return PingbackNotificationDismissedResource.saveModel({ data: dismissedNotificationData })
Expand Down
7 changes: 5 additions & 2 deletions kolibri/core/assets/src/state/modules/core/getters.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import useUser from 'kolibri.coreVue.composables.useUser';
import { get } from '@vueuse/core';
import { MaxPointsPerContent } from '../../../constants';

export function facilityConfig(state) {
Expand Down Expand Up @@ -26,8 +28,9 @@ export function pageSessionId(state) {
return state.pageSessionId;
}

export function allowAccess(state, getters, rootState, rootGetters) {
return state.allowRemoteAccess || rootGetters.isAppContext;
export function allowAccess(state) {
const { isAppContext } = useUser();
return state.allowRemoteAccess || get(isAppContext);
}

export function isPageLoading(state) {
Expand Down
8 changes: 6 additions & 2 deletions kolibri/core/assets/src/utils/appCapabilities.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import client from 'kolibri.client';
import store from 'kolibri.coreVue.vuex.store';
import logger from 'kolibri.lib.logging';
import urls from 'kolibri.urls';
import useUser from 'kolibri.coreVue.composables.useUser';
import { get } from '@vueuse/core';
import plugin_data from 'plugin_data';

const logging = logger.getLogger(__filename);
Expand All @@ -11,7 +12,10 @@ const appCapabilities = plugin_data.appCapabilities || {};
// Check that we are in an appcontext, if not disable all capabilities
// this means that consumers of this API can rely solely on the existence
// check of methods in this API to know if they can call these or not.
export const checkCapability = key => store.getters.isAppContext && appCapabilities[key];
export const checkCapability = key => {
const { isAppContext } = useUser();
return get(isAppContext) && appCapabilities[key];
};

// Use a janky getter to return a method here to only expose functions
// that are available so that we have a single API for both existence
Expand Down
8 changes: 4 additions & 4 deletions kolibri/plugins/coach/assets/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ class CoachToolsModule extends KolibriApp {
return pluginModule;
}
ready() {
const { snackbarIsVisibile, clearSnackbar } = useSnackbar();
const { isLearnerOnlyImport } = useUser();
const { snackbarIsVisible, clearSnackbar } = useSnackbar();
const { isLearnerOnlyImport, isSuperuser } = useUser();
router.beforeEach((to, from, next) => {
if (get(isLearnerOnlyImport)) {
redirectBrowser();
Expand Down Expand Up @@ -56,7 +56,7 @@ class CoachToolsModule extends KolibriApp {

// Clear the snackbar at every navigation to prevent it from re-appearing
// when the next page component mounts.
if (get(snackbarIsVisibile) && !skipLoading.includes(to.name)) {
if (get(snackbarIsVisible) && !skipLoading.includes(to.name)) {
clearSnackbar();
}

Expand Down Expand Up @@ -107,7 +107,7 @@ class CoachToolsModule extends KolibriApp {
promises.push(this.store.dispatch('initClassInfo', to.params.classId));
}

if (this.store.getters.isSuperuser && this.store.state.core.facilities.length === 0) {
if (get(isSuperuser) && this.store.state.core.facilities.length === 0) {
promises.push(this.store.dispatch('getFacilities').catch(() => {}));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
} from 'kolibri.resources';
import { ContentNodeKinds } from 'kolibri.coreVue.vuex.constants';
import chunk from 'lodash/chunk';
import useUser from 'kolibri.coreVue.composables.useUser';
import { get } from '@vueuse/core';
import { LessonsPageNames } from '../../constants/lessonsConstants';

async function showResourceSelectionPage(store, params) {
Expand All @@ -20,8 +22,9 @@ async function showResourceSelectionPage(store, params) {
const pendingSelections = store.state.lessonSummary.workingResources || [];
const cache = store.state.lessonSummary.resourceCache || {};
const initClassInfoPromise = store.dispatch('initClassInfo', params.classId);
const { isSuperuser } = useUser();
const getFacilitiesPromise =
store.getters.isSuperuser && store.state.core.facilities.length === 0
get(isSuperuser) && store.state.core.facilities.length === 0
? store.dispatch('getFacilities').catch(() => {})
: Promise.resolve();

Expand Down Expand Up @@ -183,8 +186,9 @@ function getBookmarks() {
export async function showLessonResourceContentPreview(store, params) {
const { classId, lessonId, contentId } = params;
const initClassInfoPromise = store.dispatch('initClassInfo', classId);
const { isSuperuser } = useUser();
const getFacilitiesPromise =
store.getters.isSuperuser && store.state.core.facilities.length === 0
get(isSuperuser) && store.state.core.facilities.length === 0
? store.dispatch('getFacilities').catch(() => {})
: Promise.resolve();

Expand All @@ -199,8 +203,9 @@ export async function showLessonResourceContentPreview(store, params) {
export async function showLessonSelectionContentPreview(store, params, query = {}) {
const { classId, lessonId, contentId } = params;
const initClassInfoPromise = store.dispatch('initClassInfo', classId);
const { isSuperuser } = useUser();
const getFacilitiesPromise =
store.getters.isSuperuser && store.state.core.facilities.length === 0
get(isSuperuser) && store.state.core.facilities.length === 0
? store.dispatch('getFacilities').catch(() => {})
: Promise.resolve();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { LearnerGroupResource } from 'kolibri.resources';
import useUser from 'kolibri.coreVue.composables.useUser';
import { get } from '@vueuse/core';
import { LessonsPageNames } from '../../constants/lessonsConstants';

export async function setLessonSummaryState(store, params) {
Expand All @@ -12,8 +14,9 @@ export async function setLessonSummaryState(store, params) {
lessonsModalSet: null,
});
const initClassInfoPromise = store.dispatch('initClassInfo', classId);
const { isSuperuser } = useUser();
const getFacilitiesPromise =
store.getters.isSuperuser && store.state.core.facilities.length === 0
get(isSuperuser) && store.state.core.facilities.length === 0
? store.dispatch('getFacilities').catch(() => {})
: Promise.resolve();

Expand Down
9 changes: 6 additions & 3 deletions kolibri/plugins/coach/assets/src/modules/pluginModule.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { ClassroomResource } from 'kolibri.resources';
import logger from 'kolibri.lib.logging';
import useUser from 'kolibri.coreVue.composables.useUser';
import { get } from '@vueuse/core';
import { pageNameToModuleMap } from '../constants';
import { LessonsPageNames } from '../constants/lessonsConstants';
import examReportDetail from './examReportDetail';
Expand Down Expand Up @@ -49,11 +51,12 @@ export default {
return state.classList.length !== 1;
},
userIsAuthorizedForCoach(state, getters, rootState) {
if (getters.isSuperuser) {
const { isAdmin, isSuperuser, isCoach, facility_id } = useUser();
if (get(isSuperuser)) {
return true;
} else if (getters.isCoach || getters.isAdmin) {
} else if (get(isCoach) || get(isAdmin)) {
return (
rootState.route.params.facilityId === rootState.core.session.facility_id ||
rootState.route.params.facilityId === get(facility_id) ||
!rootState.route.params.facilityId
);
}
Expand Down
11 changes: 8 additions & 3 deletions kolibri/plugins/coach/assets/src/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import store from 'kolibri.coreVue.vuex.store';
import router from 'kolibri.coreVue.router';
import useUser from 'kolibri.coreVue.composables.useUser';
import { get } from '@vueuse/core';
import AllFacilitiesPage from '../views/AllFacilitiesPage';
import CoachClassListPage from '../views/CoachClassListPage';
import ClassLearnersListPage from '../views/ClassLearnersListPage';
Expand All @@ -15,8 +17,9 @@ import { classIdParamRequiredGuard } from './utils';

function showHomePage(toRoute) {
const initClassInfoPromise = store.dispatch('initClassInfo', toRoute.params.classId);
const { isSuperuser } = useUser();
const getFacilitiesPromise =
store.getters.isSuperuser && store.state.core.facilities.length === 0
get(isSuperuser) && store.state.core.facilities.length === 0
? store.dispatch('getFacilities').catch(() => {})
: Promise.resolve();

Expand Down Expand Up @@ -44,7 +47,8 @@ export default [
store.dispatch('notLoading');
// if user only has access to one facility, facility_id will not be accessible from URL,
// but always defaulting to userFacilityId would cause problems for multi-facility admins
const facilityId = toRoute.params.facility_id || store.getters.userFacilityId;
const { userFacilityId } = useUser();
const facilityId = toRoute.params.facility_id || get(userFacilityId);
store.dispatch('setClassList', facilityId).then(
() => {
if (!store.getters.classListPageEnabled) {
Expand Down Expand Up @@ -116,7 +120,8 @@ export default [
path: '/',
// Redirect to AllFacilitiesPage if a superuser and device has > 1 facility
beforeEnter(to, from, next) {
if (store.getters.userIsMultiFacilityAdmin) {
const { userIsMultiFacilityAdmin } = useUser();
if (get(userIsMultiFacilityAdmin)) {
next({ name: 'AllFacilitiesPage', replace: true });
} else {
next({ name: 'CoachClassListPage', replace: true });
Expand Down
7 changes: 4 additions & 3 deletions kolibri/plugins/coach/assets/src/routes/utils.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import store from 'kolibri.coreVue.vuex.store';
import useUser from 'kolibri.coreVue.composables.useUser';
import { get } from '@vueuse/core';

export function classIdParamRequiredGuard(toRoute, subtopicName, next) {
if (!toRoute.params.classId) {
const redirectPage = store.getters.userIsMultiFacilityAdmin
? 'AllFacilitiesPage'
: 'CoachClassListPage';
const { userIsMultiFacilityAdmin } = useUser();
const redirectPage = get(userIsMultiFacilityAdmin) ? 'AllFacilitiesPage' : 'CoachClassListPage';

next({
name: redirectPage,
Expand Down
11 changes: 6 additions & 5 deletions kolibri/plugins/device/assets/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ class DeviceManagementModule extends KolibriApp {
return Cookies.get(IsPinAuthenticated) === 'true';
}
checkIfPinAuthenticationIsRequired(store, grantPluginAccess) {
const { isLearnerOnlyImport } = useUser();
const isSuperuser = store.getters.isSuperuser;
const isFacilityAdmin = store.getters.isFacilityAdmin;
const userCanManageContent = store.getters.canManageContent;
if (get(isLearnerOnlyImport) && !isFacilityAdmin && (isSuperuser || userCanManageContent)) {
const { isLearnerOnlyImport, isSuperuser, isFacilityAdmin, canManageContent } = useUser();
if (
get(isLearnerOnlyImport) &&
!get(isFacilityAdmin) &&
(get(isSuperuser) || get(canManageContent))
) {
//While browsing within the device plugin, prevent expiry.
//On page refresh within plugin, show pin prompt if cookie has expired.
viewPlugin = viewPlugin ? viewPlugin : this.isPinAuthenticated;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ export function getDeviceInfo() {
* @returns Promise<void>
*/
export function showDeviceInfoPage(store) {
if (store.getters.canManageContent) {
const { canManageContent } = useUser();
if (get(canManageContent)) {
const shouldResolve = samePageCheckGenerator(store);
const promises = Promise.all([getDeviceInfo()]);
return promises
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import useUser from 'kolibri.coreVue.composables.useUser';
import { get } from '@vueuse/core';

export function showManageContentPage(store) {
store.commit('manageContent/RESET_STATE');
store.commit('manageContent/wizard/RESET_STATE');
if (store.getters.canManageContent) {
const { canManageContent } = useUser();
if (get(canManageContent)) {
return Promise.all([
store.dispatch('manageContent/refreshTaskList'),
store.dispatch('manageContent/refreshChannelList'),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { DevicePermissionsResource, FacilityUserResource } from 'kolibri.resources';
import samePageCheckGenerator from 'kolibri.utils.samePageCheckGenerator';
import useUser from 'kolibri.coreVue.composables.useUser';
import { get } from '@vueuse/core';

/**
* Serially fetches Permissions, then FacilityUser. If returned Promise rejects,
Expand Down Expand Up @@ -44,7 +46,8 @@ export function showUserPermissionsPage(store, userId) {
const stopLoading = () => store.dispatch('notLoading');

// Don't request any data if not an Admin
if (!store.getters.isSuperuser) {
const { isSuperuser } = useUser();
if (!get(isSuperuser)) {
setUserPermissionsState({ user: null, permissions: {} });
stopLoading();
return Promise.resolve();
Expand Down
Loading

0 comments on commit 8b79e1a

Please sign in to comment.