aboutsummaryrefslogtreecommitdiff
path: root/front-end/src/store/pageProtectionPlugin.ts
blob: a747e496c5b46c8b6d6d905e1c6a8aa00d884bb3 (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
import 'pinia'
import { watch } from 'vue';
import {  } from '@vnuge/vnlib.browser';
import { useSessionStorage, get, set } from '@vueuse/core';
import { PiniaPluginContext, PiniaPlugin, storeToRefs } from 'pinia'
import { includes, startsWith } from 'lodash-es';
import { useRouter } from 'vue-router';

declare module 'pinia' {
    export interface PiniaCustomProperties {
       
    }
}

export const pageProtectionPlugin = (router: ReturnType<typeof useRouter>): PiniaPlugin => {

    return ({ store }: PiniaPluginContext) => {

        const { loggedIn, headerRoutes } = storeToRefs(store)

        const lastPageStore = useSessionStorage('lastPageStore', undefined)

        //Setup nav guards
        router.beforeEach((to, from) => {
            if(!to.name){
                return true;
            }

            //see if to route is login route
            if(startsWith(to.name as string, 'Login')){

                //If the user is logged-in, redirect to the last page
                if(get(loggedIn) === true){
                    const lastPath = get(lastPageStore);
                    set(lastPageStore, undefined)   //Clear the last page

                    return lastPath ? { path: lastPath } : true;
                }
                else{
                    //Set last page as from page
                    set(lastPageStore, from.fullPath)
                }
                return true;
            }

            //See if the to route is not in allowed routes
            if (!includes(get(headerRoutes), to.name as string)){
                //Check if the user is logged in
                if(get(loggedIn) === false){

                    //Save the last page
                    set(lastPageStore, to.fullPath)

                    //Redirect to login
                    return { name: 'Login' }
                }
            }

            //Allow
            return true;
        })

        //scroll window back to top
        router.afterEach(() => window.scrollTo(0, 0))

        watch(loggedIn, (li) => {
            //If the user gets logged out, redirect to login
            if(li === false && router.currentRoute.value.name !== 'Login'){
                router.push({ name: 'Login' })
            }
        })

        return {
          
        }
    }
}