add: frontend login logic

v0.6
rrr-marble 3 years ago
parent d2c45c4fbc
commit a4ea2a018f

@ -7,6 +7,7 @@
<va-button type="submit" class="form-item">Login</va-button>
</va-form>
</va-modal>
<va-modal v-model="errorModal" hide-default-actions message="Неверный логин или пароль" />
</template>
@ -20,13 +21,40 @@ export default {
showModal: true,
username: 'demo',
password: 'demo',
errorModal: false,
}
},
methods: {
handleSubmit() {
this.$router.push('/admin')
if (!localStorage.getItem("user")) {
const formData = new FormData();
formData.append('username', this.username);
formData.append('password', this.password);
fetch("/api/v1/token/", { method: 'POST', body: formData })
.then(res => {
if (!res.ok) {
this.errorModal = true;
}
return res.json()
})
.then(data => {
if (data.access_token) {
localStorage.setItem('user', JSON.stringify(data));
this.$router.push('/admin')
}
})
.catch((e) => { console.log(e) })
} else {
this.$router.push('/admin')
}
}
},
computed: {
loggedIn() {
return Boolean(localStorage.getItem("user"))
}
}
}
</script>

@ -23,15 +23,20 @@ export default {
const formData = new FormData();
formData.append('file', files[0], files[0].name);
fetch("/api/v1/items/", {method: 'POST', body: formData})
const user = JSON.parse(localStorage.getItem('user'));
const authHeader = user && user.access_token
? { Authorization: 'Bearer ' + user.access_token }
: {};
fetch("/api/v1/items/", { method: 'POST', body: formData, headers: authHeader })
.then(res => res.json())
.then(data => this.response = data)
.catch((e) => console.log(e))
.then(()=>this.showModal=!this.showModal)
.then(() => this.showModal = !this.showModal)
}
},
computed: {
result(){
result() {
if (this.response.status === "Success") {
return {
status: "Success!",

@ -47,4 +47,18 @@ const router = createRouter({
history: createWebHistory(process.env.BASE_URL)
});
router.beforeEach(async (to, from, next) => {
const restrictedPages = ['/admin', '/admin/'];
const authRequired = restrictedPages.includes(to.path);
const loggedIn = localStorage.getItem('user')
// trying to access a restricted page + not logged in
// redirect to login page
if (authRequired && !loggedIn) {
next('/login/');
} else {
next();
}
})
export default router;

@ -1,5 +1,5 @@
<template>
<navbar @accountClick="showModal=!showModal">
<navbar @accountClick="$router.push('/admin/')">
<va-input v-model="searchQuery"></va-input>
</navbar>
<div class="central-view">

@ -1,5 +1,5 @@
<template>
<navbar @accountClick="showModal=!showModal" />
<navbar @accountClick="$router.push('/admin/')" />
<div class="central-view">
<sidebar>
<item-sidebar-menu :sidebarItems="sidebarItems" />

Loading…
Cancel
Save