Haris Razis
4 years ago
3 changed files with 86 additions and 51 deletions
@ -1,25 +1,43 @@ |
|||
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router' |
|||
import {createRouter, createWebHistory, RouteRecordRaw} from 'vue-router' |
|||
import Home from '../views/Home.vue' |
|||
import store from '../store/index' |
|||
|
|||
const routes: Array<RouteRecordRaw> = [ |
|||
{ |
|||
path: '/', |
|||
name: 'Home', |
|||
component: Home |
|||
}, |
|||
{ |
|||
path: '/about', |
|||
name: 'About', |
|||
// route level code-splitting
|
|||
// this generates a separate chunk (about.[hash].js) for this route
|
|||
// which is lazy-loaded when the route is visited.
|
|||
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') |
|||
} |
|||
{ |
|||
path: '/', |
|||
name: 'Home', |
|||
component: Home, |
|||
}, |
|||
{ |
|||
path: '/login', |
|||
name: 'Login', |
|||
component: () => import('../views/Login.vue'), |
|||
}, |
|||
{ |
|||
path: '/dashboard', |
|||
name: 'Dashboard', |
|||
component: () => import('../views/Dashboard.vue'), |
|||
meta: { |
|||
requiresAuth: true |
|||
} |
|||
} |
|||
] |
|||
|
|||
const router = createRouter({ |
|||
history: createWebHistory(process.env.BASE_URL), |
|||
routes |
|||
history: createWebHistory(process.env.BASE_URL), |
|||
routes |
|||
}) |
|||
|
|||
router.beforeEach((to, from, next) => { |
|||
if (to.matched.some(record => record.meta.requiresAuth)) { |
|||
if (store.getters.isLoggedIn) { |
|||
next() |
|||
return |
|||
} |
|||
next('/login') |
|||
} else { |
|||
next() |
|||
} |
|||
}) |
|||
|
|||
export default router |
|||
|
@ -1,12 +1,48 @@ |
|||
import { createStore } from 'vuex' |
|||
import {createStore} from 'vuex' |
|||
import axios, {AxiosResponse} from "axios"; |
|||
|
|||
export default createStore({ |
|||
state: { |
|||
}, |
|||
mutations: { |
|||
}, |
|||
actions: { |
|||
}, |
|||
modules: { |
|||
} |
|||
state: { |
|||
status: false, |
|||
user: {} |
|||
}, |
|||
mutations: { |
|||
auth_success(state, user) { |
|||
state.status = true |
|||
state.user = user |
|||
}, |
|||
auth_error(state) { |
|||
state.status = false |
|||
}, |
|||
logout(state) { |
|||
state.status = false |
|||
state.user = {} |
|||
}, |
|||
}, |
|||
actions: { |
|||
login({commit}, user: { username: string, password: string }) { |
|||
return new Promise((resolve, reject) => { |
|||
axios({url: 'http://backend:6000/api/auth/login', data: {user}, method: 'POST'}) |
|||
.then((resp: AxiosResponse) => { |
|||
commit("auth_success", user.username); |
|||
resolve(resp) |
|||
}) |
|||
.catch((err: Error) => { |
|||
commit('auth_error') |
|||
reject(err) |
|||
}) |
|||
}) |
|||
}, |
|||
logout({commit}) { |
|||
return new Promise((resolve, reject) => { |
|||
let user = null; |
|||
commit("logout"); |
|||
resolve() |
|||
}) |
|||
}, |
|||
}, |
|||
modules: {}, |
|||
getters: { |
|||
isLoggedIn: state => !!state.status, |
|||
} |
|||
}) |
|||
|
Loading…
Reference in new issue