LabWork06: ну не то что бы работает, но, работает

This commit is contained in:
Safgerd 2023-06-16 16:13:34 +04:00
parent 02268b2b1b
commit 09861b425c
10 changed files with 878 additions and 443 deletions

View File

@ -6,10 +6,13 @@
<meta name="viewport" content="width=device-width,initial-scale=1.0"> <meta name="viewport" content="width=device-width,initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/chota@latest"> <link rel="stylesheet" href="https://unpkg.com/chota@latest">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://code.jquery.com/jquery-3.7.0.slim.min.js" integrity="sha256-tG5mcZUtJsZvyKAxYLVXrmjKBVLd6VpVccqz/r4ypFE=" crossorigin="anonymous"></script>
<title>LabWork04 - Social Network</title> <title>LabWork04 - Social Network</title>
</head> </head>
<body> <body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <script src="https://unpkg.com/@popperjs/core@2"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
<div id="app"></div> <div id="app"></div>
</body> </body>
</html> </html>

View File

@ -1,45 +1,72 @@
<template> <template>
<div>
<p class='text-center m-3 h3'>LabWork04 - Social Network</p>
</div>
<div class="nav row"> <div class="nav row">
<div class="nav-left col-4"> <div class="nav-left">
<router-link to="/customers" class="text-decoration-none m-3">Профили</router-link> <router-link to="/customers" v-bind:class="'button primary ' + this.$route.path.startsWith('/customers')? 'clear' : ''">Профили</router-link>
<router-link to="/posts" class="text-decoration-none m-3">Посты</router-link> <router-link to="/feed" v-bind:class="'button primary ' + this.$route.path.startsWith('/feed')? 'clear' : ''">Посты</router-link>
<select class="form-select mt-4" style="font-size: 16px; max-height: 35px; max-width: 180px;" v-model="currentCustomerId"> <router-link v-if="role === 'ADMIN'" to="/admin" v-bind:class="'button primary ' + this.$route.path.startsWith('/admin')? 'clear' : ''">Администрирование</router-link>
<option value="-1" selected class="button dark outline" :on-click="updateCurrentCustomer()">Не выбран</option> <router-link v-if="this.token_value == null" to="/login" v-bind:class="'button primary ' + this.$route.path.startsWith('/login')? 'clear' : ''">Вход</router-link>
<option v-for="customer in customers" v-bind:value="customer['id']" class="button dark outline" :on-click="updateCurrentCustomer()">{{ customer['username'] }}</option> <button v-if="this.token_value != null" v-on:click="logout()" v-bind:class="'button primary ' + this.$route.path.startsWith('/signup')? 'clear' : ''">Выход</button>
</select>
</div> </div>
</div> </div>
<router-view></router-view> <router-view></router-view>
</template> </template>
<script> <script>
import axios from 'axios'
export default { export default {
data() { data() {
return { return {
currentCustomerId: -1, token_value: localStorage.getItem("token"),
customers: [] role: ''
} }
}, },
methods: { methods: {
async updateCurrentCustomer() { logout() {
history.replaceState(this.currentCustomerId, ""); this.token = null
this.role = ''
localStorage.clear()
this.$router.push('login')
},
async actualRole() {
let response = await fetch(
"http://localhost:8080/api/1.0/customer/role/" + localStorage.getItem("token"),
{
method: "GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.role = await response.text()
localStorage.setItem("role", this.role)
}
},
computed: {
token: {
get: function() {
return this.token_value
},
set: function(value) {
this.token_value = value
localStorage.setItem("token", value)
localStorage.setItem("role", this.role)
}
} }
}, },
async beforeMount() { async beforeMount() {
setInterval(async () => { if (localStorage.getItem("token") === null) {
const response = await axios.get('http://localhost:8080/api/customer'); return null;
this.customers = []; }
response.data.forEach(element => {
this.customers.push(element);
console.log(element);
});
}, 500)
}, await this.actualRole()
const component = this
document.addEventListener('token_changed', async function() {
component.token = localStorage.getItem("token")
await component.actualRole()
})
}
} }
</script> </script>

View File

@ -0,0 +1,223 @@
<template>
<div class="row">
<div class="col">
<div class="row mb-5">
<p class='is-center h2'>Профили</p>
</div>
<div class="row mb-5">
<div class="col"></div>
<div class="col-10 is-center">
<button class="button primary" data-bs-toggle="modal" data-bs-target="#customerCreate">
Добавить нового пользователя
</button>
</div>
<div class="col"></div>
</div>
<p class='h3 is-center row mb-5'>Список профилей</p>
<div class="row">
<div class="col">
<div class="row card mb-3">
<div class="row">
<div class="col-3 is-left h3 fw-bold">ID</div>
<div class="col-3 is-center h3 fw-bold">Никнейм</div>
<div class="col-3 is-right h3 fw-bold">Пароль</div>
<div class="col-2"></div>
<div class="col-1"></div>
</div>
</div>
<div v-for="customer in customers" class="row card mb-3">
<div class="row">
<div class="col-3 is-left h3">{{ customer.id }}</div>
<router-link :to="{name: 'Customers', params: {'id': customer.id}}" class="col-3 is-center h3">{{ customer.username }}</router-link>
<div class="col-3 is-right h3">
<span style="text-overflow: ellipsis; overflow: hidden; max-width: 10ch; white-space: nowrap">
{{ customer.password }}
</span>
</div>
<button style="max-width: 66px; max-height: 38px;" v-on:click="prepareEditModal(customer)" class="button primary outline is-right" data-bs-toggle="modal" data-bs-target="#customerEdit">
<i class="fa fa-pencil" aria-hidden="true">
</i>
</button>
<div class="col-1 is-right">
<button class="button dark outline is-right" v-on:click="deleteCustomer(customer)" style="max-width: 66px; max-height: 38px;">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="customerCreate" tabindex="-1" role="dialog" aria-labelledby="customerCreateLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="customerCreateLabel">Создать профиль</h5>
</div>
<div class="modal-body text-center">
<p>Логин</p>
<textarea name="username" v-model="newCustomer.username" cols="30" rows="1"></textarea>
<p>Пароль</p>
<textarea name="password" v-model="newCustomer.password" id="passwordTextC" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="button" v-on:click="createCustomer()" class="btn btn-primary" data-bs-dismiss="modal">Сохранить</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content" id="edit-customer-form">
<div class="modal-header">
<h5 class="modal-title" id="customerEditLabel">Редактировать профиль</h5>
</div>
<div class="modal-body text-center">
<p>Логин</p>
<textarea name="username" v-model="editedCustomer.username" cols="30" rows="1"></textarea>
<p>Пароль</p>
<textarea name="password" v-model="editedCustomer.password" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="button" v-on:click="editCustomer()" class="btn btn-primary" data-bs-dismiss="modal">Изменить</button>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
editedCustomer: {
id: -1,
username: '',
password: ''
},
newCustomer: {
id: -1,
username: '',
password: ''
},
customers: [],
currentCustomerId: -1
}
},
methods: {
async updateCustomers() {
const response = await fetch(
"http://localhost:8080/api/1.0/customer",
{
method: "GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.customers = await response.json()
},
async createCustomer() {
const response = await fetch(
"http://localhost:8080/api/1.0/customer",
{
method: "POST",
headers: {
'Content-Type': 'application/json',
"Authorization": "Bearer " + localStorage.getItem("token")
},
body: JSON.stringify({
"username": this.newCustomer.username,
"password": this.newCustomer.password
})
}
)
await this.updateCustomers()
},
async editCustomer() {
const response = await fetch(
"http://localhost:8080/api/1.0/customer/" + this.editedCustomer.id,
{
method: "PUT",
headers: {
'Content-Type': 'application/json',
"Authorization": "Bearer " + localStorage.getItem("token")
},
body: JSON.stringify({
"username": this.editedCustomer.username,
"password": this.editedCustomer.password
})
}
)
if (this.currentCustomerId == this.editedCustomer.id) {
localStorage.clear()
document.dispatchEvent(new Event("token_changed"))
this.$router.replace("login")
}
await this.updateCustomers()
},
async deleteCustomer(customer) {
const response = await fetch(
"http://localhost:8080/api/1.0/customer/" + customer.id,
{
method: "DELETE",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
if (this.currentCustomerId == this.editedCustomer.id) {
localStorage.clear()
document.dispatchEvent(new Event("token_changed"))
this.$router.replace("login")
}
await this.updateCustomers()
},
async prepareEditModal(customer) {
this.editedCustomer.username = customer.username
this.editedCustomer.id = customer.id
},
async getCurrentCustomer() {
const response = await fetch(
"http://localhost:8080/api/1.0/customer/me",
{
method: "GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.currentCustomerId = (await response.json())['id']
}
},
async beforeMount() {
if (localStorage.getItem("role") !== "ADMIN") {
this.$router.replace("login")
}
if (!localStorage.getItem("token") === null) {
this.$router.replace("login")
}
await this.getCurrentCustomer()
await this.updateCustomers()
}
}
</script>
<style>
</style>

View File

@ -1,9 +1,6 @@
<template> <template>
<div class="ms-5"> <div class="ms-5">
<p class='h4 m-3'>Пользователи</p> <p class='h4 m-3'>Пользователи</p>
<button type='button' class="btn btn-primary ms-3 mb-3" data-bs-toggle="modal" data-bs-target="#customerCreate">
Добавить нового пользователя
</button>
<p class='h4 ms-3'>Список</p> <p class='h4 ms-3'>Список</p>
<div class="row"> <div class="row">
@ -14,7 +11,7 @@
</div> </div>
<p class="row is-left"></p> <p class="row is-left"></p>
<div class="row" v-if="!(customer['posts'].length == 0)"> <div class="row" v-if="customer['posts'].length !== 0">
<p class="h4">Посты:</p> <p class="h4">Посты:</p>
<div class="col"> <div class="col">
<div v-for="post in customer['posts']" class="row is-left card mb-3"> <div v-for="post in customer['posts']" class="row is-left card mb-3">
@ -25,7 +22,7 @@
</div> </div>
<div class="row is-left" v-if="!(customer['comments'].length == 0)"> <div class="row is-left" v-if="customer['comments'].length !== 0">
<p class="h4">Комментарии:</p> <p class="h4">Комментарии:</p>
<div class="col"> <div class="col">
<div v-for="comment in customer['comments']" class="row is-left card mb-3"> <div v-for="comment in customer['comments']" class="row is-left card mb-3">
@ -34,52 +31,31 @@
</div> </div>
</div> </div>
<div class="row" v-if="customer['id'] == currentCustomerId"> <div class="row" v-if="currentCustomerId === customer['id']">
<button v-on:click="deleteUser(customer['id'])" class="col button dark outline">Удалить</button> <button v-on:click="deleteCustomer(customer)" class="col button dark outline">Удалить</button>
<button v-on:click="selectedCustomer = customer; usernameModal=customer['username'];passwordModal=customer['password']" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#customerEdit">Редактировать</button> <button v-on:click="prepareEditModal(customer)" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#customerEdit">Редактировать</button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<!-- Modal -->
<div class="modal fade" id="customerCreate" tabindex="-1" role="dialog" aria-labelledby="customerCreateLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="customerCreateLabel">Создать пользователя</h5>
</div>
<div class="modal-body text-center">
<p>Имя пользователя</p>
<textarea v-model='usernameModal' id="usernameText" cols="30" rows="1"></textarea>
<p>Пароль</p>
<textarea v-model='passwordModal' id="passwordText" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-primary" v-on:click='createUser'>Создать</button>
</div>
</div>
</div>
</div>
<!-- Modal --> <!-- Modal -->
<div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true"> <div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document"> <div class="modal-dialog" role="document">
<div class="modal-content"> <div class="modal-content" id="edit-customer-form">
<div class="modal-header"> <div class="modal-header">
<h5 class="modal-title" id="customerEditLabel">Изменение пользователя</h5> <h5 class="modal-title" id="customerEditLabel">Изменение пользователя</h5>
</div> </div>
<div class="modal-body text-center"> <div class="modal-body text-center">
<p>Имя пользователя</p> <p>Имя пользователя</p>
<textarea v-model='usernameModal' id="usernameText" cols="30" rows="1"></textarea> <textarea name="username" id="usernameTextE" cols="30" rows="1"></textarea>
<p>Пароль</p> <p>Пароль</p>
<textarea v-model='passwordModal' id="passwordText" cols="30" rows="1"></textarea> <textarea name="password" id="passwordTextE" cols="30" rows="1"></textarea>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-primary" v-on:click='editUser'>Применить</button> <button v-on:click="editCustomer()" type="button" class="btn btn-primary">Применить</button>
</div> </div>
</div> </div>
</div> </div>
@ -87,73 +63,98 @@
</template> </template>
<script> <script>
import axios from 'axios'
export default { export default {
data() { data() {
return { return {
customers: [], customers: [],
usernameModal: '',
passwordModal: '',
selectedCustomer: {},
currentCustomerId: -1 currentCustomerId: -1
} }
}, },
methods: { methods: {
async createUser(){ async updateCustomers() {
let customer = { if (!this.$route.params.id) {
username: this.usernameModal, const response = await fetch(
password: this.passwordModal "http://localhost:8080/api/1.0/customer",
}; {
const response = await axios.post('http://localhost:8080/api/customer', customer); method: "GET",
this.refreshList(); headers: {
}, "Authorization": "Bearer " + localStorage.getItem("token")
async deleteUser(id) { }
const response = await axios.delete('http://localhost:8080/api/customer/' + id); }
this.refreshList(); )
}, this.customers = await response.json()
async editUser() { }
let customer = { else {
username: this.usernameModal, const response = await fetch(
password: this.passwordModal "http://localhost:8080/api/1.0/customer/" + this.$route.params.id,
}; {
const response = await axios.put('http://localhost:8080/api/customer/' + this.selectedCustomer['id'], customer); method: "GET",
this.refreshList(); headers: {
}, "Authorization": "Bearer " + localStorage.getItem("token")
async refreshList() { }
this.customers = []; }
if (this.$route.params.id === "") { )
const response = await axios.get('http://localhost:8080/api/customer'); this.customers = [await response.json()]
response.data.forEach(element => { }
this.customers.push(element);
console.log(element);
});
} else {
const response = await axios.get('http://localhost:8080/api/customer/' + this.$route.params.id);
this.customers.push(response.data)
}
}, },
async getCurrentCustomer() {
const response = await fetch(
"http://localhost:8080/api/1.0/customer/me",
{
method: "GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.currentCustomerId = (await response.json())['id']
},
prepareEditModal(customer) {
$("#usernameTextE").val(customer['username'])
},
async deleteCustomer() {
await fetch(
"http://localhost:8080/api/1.0/customer/" + this.currentCustomerId,
{
method: "DELETE",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
localStorage.clear()
this.$router.push("login")
},
async editCustomer() {
await fetch(
"http://localhost:8080/api/1.0/customer/" + this.currentCustomerId,
{
method: "PUT",
headers: {
'Content-Type': 'application/json',
"Authorization": "Bearer " + localStorage.getItem("token")
},
body: JSON.stringify({
"username": $("#usernameTextE").val(),
"password": $("#passwordTextE").val()
})
}
)
localStorage.clear()
this.$router.replace("login")
}
}, },
async mounted() { async beforeMount() {
this.currentCustomerId = history.state; if (localStorage.getItem("token") == null) {
setInterval(async () => this.currentCustomerId = history.state, 50) this.$router.push("login")
if (this.$route.params.id === "") {
const response = await axios.get('http://localhost:8080/api/customer');
response.data.forEach(element => {
this.customers.push(element);
console.log(element);
});
} else {
const response = await axios.get('http://localhost:8080/api/customer/' + this.$route.params.id);
this.customers.push(response.data)
} }
}, await Promise.all([this.updateCustomers(), this.getCurrentCustomer()])
async beforeRouteUpdate(to, from) { }
this.$route.params.id = to.params.id;
this.refreshList();
},
} }
</script> </script>

View File

@ -0,0 +1,324 @@
<template>
<div class="ms-5">
<p class='is-left h2'>Посты</p>
<div class="col-5">
<form class="row is-left mb-5" @submit.prevent="searchPosts">
<input type="search" v-model="searchQuery" class="col-7">
<button class="button primary col-3" type="submit">Поиск</button>
</form>
</div>
<div class="row is-left mb-5" v-if="currentCustomerId > 0">
<form class="col-7" @submit.prevent="createPost">
<input name="customerId" type="text" style="display: none;" :value="currentCustomerId">
<div class="row is-left">
<p class="col-2 is-left mb-2">Заголовок:</p>
<input name="title" type="text" class="col-5" v-model="newPost.title" />
</div>
<div class="row is-left">
<p class="col-2 is-left mb-2">Текст:</p>
<textarea name="content" class="col-5" v-model="newPost.content"></textarea>
</div>
<div class="row is-left">
<button type='submit' class="button primary col-7">
Опубликовать
</button>
</div>
</form>
</div>
<div v-if="posts.length > 0" class="row">
<div class="col-5">
<div class="row mb-5 card" v-for="post in posts" :key="post.id">
<div class="col">
<div class="row h3">
<div class="col is-left">
<p>Автор: <a :href="'/customers/' + post.customerId" class="text-primary">{{ post.customerName }}</a></p>
</div>
</div>
<div class="row is-left text-left">
<span class="h2">{{ post.title }}</span>
<span class="h3">{{ post.content }}</span>
</div>
<div class="row">
<div class="col">
<p class="row h3 is-left my-2">Комментарии</p>
<div v-if="post.comments.length > 0" class="row text-left mb-5 card" v-for="comment in post.comments" :key="comment.id">
<div class="row is-left">
<span class="h2 text-primary">{{ comment.customerName }}</span>
<span class="h3">{{ comment.content }}</span>
</div>
<div v-if="currentCustomerId === comment.customerId" class="row">
<button @click="prepareCommentEditModal(comment)" class="button primary outline col" data-bs-toggle="modal" data-bs-target="#commentEdit">Изменить</button>
<form @submit.prevent="deleteComment(comment.id)" class="col">
<button type="submit" class="button error is-full-width">Удалить</button>
</form>
</div>
</div>
<p v-else class="h3 row is-center mb-5">Пусто</p>
<form class="row" v-if="currentCustomerId !== -1" @submit.prevent="addComment(post.id)">
<input name="content" type="text" class="col-7" v-model="newComment.content"/>
<input name="customerId" type="text" style="display: none;" :value="currentCustomerId">
<input name="postId" type="text" style="display: none;" :value="post.id">
<button type="submit" class="button col-5 secondary outline">Комментировать</button>
</form>
</div>
</div>
<div class="row" v-if="currentCustomerId === post.customerId">
<form class="col" @submit.prevent="deletePost(post.id)">
<button type="submit" class="is-full-width button dark outline">Удалить</button>
</form>
<button @click="preparePostEditModal(post)" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#postEdit">Изменить</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="postEdit" tabindex="-1" role="dialog" aria-labelledby="postEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="postEditLabel">Редактировать пост</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body text-center">
<form @submit.prevent="updatePost">
<input type="hidden" name="postId" v-model="editedPost.id">
<div class="form-group">
<label for="postEditTitle">Заголовок</label>
<input type="text" class="form-control" id="postEditTitle" v-model="editedPost.title">
</div>
<div class="form-group">
<label for="postEditContent">Содержание</label>
<textarea class="form-control" id="postEditContent" rows="5" v-model="editedPost.content"></textarea>
</div>
<button type="submit" class="btn btn-primary">Измененить</button>
</form>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="commentEdit" tabindex="-1" role="dialog" aria-labelledby="commentEditLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="commentEditLabel">Изменить комментарий</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body text-center">
<form @submit.prevent="updateComment">
<input type="hidden" name="commentId" v-model="editedComment.id">
<div class="form-group">
<label for="commentEditContent">Содержание</label>
<textarea class="form-control" id="commentEditContent" rows="5" v-model="editedComment.content"></textarea>
</div>
<button type="submit" class="btn btn-primary">Сохранить</button>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
posts: [],
currentCustomerId: -1,
searchQuery: '',
newPost: {
title: '',
content: ''
},
newComment: {
content: ''
},
editedPost: {
id: -1,
title: '',
content: ''
},
editedComment: {
id: -1,
content: ''
}
}
},
methods: {
async updatePosts() {
const response = await fetch(
"http://localhost:8080/api/1.0/post",
{
method: "GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.posts = await response.json()
},
async searchPosts() {
if (this.searchQuery) {
const response = await fetch(
"http://localhost:8080/api/1.0/post/search?query=" + this.searchQuery,
{
method: "GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.posts = await response.json()
} else {
await this.updatePosts()
}
},
async createPost() {
const response = await fetch(
"http://localhost:8080/api/1.0/post",
{
method: "POST",
headers: {
'Content-Type': 'application/json',
"Authorization": "Bearer " + localStorage.getItem("token")
},
body: JSON.stringify({
"customerId": this.currentCustomerId,
"title": this.newPost.title,
"content": this.newPost.content
})
}
)
await this.updatePosts()
},
async updatePost() {
const response = await fetch(
"http://localhost:8080/api/1.0/post/" + this.editedPost.id,
{
method: "PUT",
headers: {
'Content-Type': 'application/json',
"Authorization": "Bearer " + localStorage.getItem("token")
},
body: JSON.stringify({
"title": this.editedPost.title,
"content": this.editedPost.content,
"customerId": this.currentCustomerId
})
}
)
await this.updatePosts()
},
async deletePost(postId) {
const response = await fetch(
"http://localhost:8080/api/1.0/post/" + postId,
{
method: "DELETE",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
await this.updatePosts()
},
async addComment(postId) {
const response = await fetch(
"http://localhost:8080/api/1.0/comment",
{
method: "POST",
headers: {
'Content-Type': 'application/json',
"Authorization": "Bearer " + localStorage.getItem("token")
},
body: JSON.stringify({
"postId": postId,
"content": this.newComment.content,
"customerId": this.currentCustomerId
})
}
)
await this.updatePosts()
},
async updateComment() {
const response = await fetch(
"http://localhost:8080/api/1.0/comment/" + this.editedComment.id,
{
method: "PUT",
headers: {
'Content-Type': 'application/json',
"Authorization": "Bearer " + localStorage.getItem("token")
},
body: JSON.stringify({
"content": this.editedComment.content
})
}
)
await this.updatePosts()
},
async deleteComment(commentId) {
const response = await fetch(
"http://localhost:8080/api/1.0/comment/" + commentId,
{
method: "DELETE",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
await this.updatePosts()
},
prepareCommentEditModal(comment) {
this.editedComment.id = comment.id
this.editedComment.content = comment.content
},
preparePostEditModal(post) {
this.editedPost.id = post.id
this.editedPost.title = post.title
this.editedPost.content = post.content
},
async getCurrentCustomer() {
const response = await fetch(
"http://localhost:8080/api/1.0/customer/me",
{
method: "GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.currentCustomerId = (await response.json()).id
}
},
async beforeMount() {
if (localStorage.getItem("token") == null) {
this.$router.push("login")
}
await Promise.all([this.updatePosts(), this.getCurrentCustomer()])
}
}
</script>
<style>
</style>

View File

@ -0,0 +1,64 @@
<template>
<div class="row">
<div class="col"></div>
<div class="col-6">
<div class="row mb-3">
<label>Имя пользователя: <input type="text" id="username" required /></label>
</div>
<div class="row mb-3">
<label>Пароль: <input type="password" id="password" required /></label>
</div>
<div class="row mb-3 alert alert-danger" v-if="error !== null" role="alert">
{{ error }}
</div>
<div class="row mt-3">
<div class="col-4"></div>
<button v-on:click="login()" type="button" class="button primary col" id="enter">Войти</button>
<div class="col-4"></div>
</div>
<div class="row mt-5">
<router-link to="/signup" class="button primary outline">Регистрация</router-link>
</div>
</div>
<div class="col"></div>
</div>
</template>
<script>
export default {
data() {
return {
error: null
}
},
methods: {
async login() {
let response = await fetch(
"http://localhost:8080/api/1.0/customer/jwt/login",
{
method: "POST",
body: JSON.stringify({
"username": $("#username").val(),
"password": $("#password").val()
}),
headers: {
'Content-Type': 'application/json'
}
}
)
if (response.status !== 200) {
this.error = await response.text()
} else {
localStorage.setItem("token", await response.text())
document.dispatchEvent(new Event("token_changed"))
this.$router.push("feed")
}
}
}
}
</script>
<style>
</style>

View File

@ -1,295 +0,0 @@
<template>
<div class="ms-5">
<div class="col-7">
<div class="row">
<input type="text" v-bind:id="'searchString'" class="col-4"/>
<button type="button" v-on:click="getSearchResult()" class="button col-2 secondary outline">Поиск</button>
<button type="button" v-on:click="searchMode = -1;" class="button col-2 secondary outline">Отмена</button>
</div>
</div>
<div v-if="!(searchMode == -1)">
<div v-if="!(searchResults.length == 0)" class="row">
<div class="col-5">
<div class="row mb-5 card" v-for="result in searchResults">
<div class="col">
<div v-if="result['title'] == null">
<div class="row is-left mt-2">
<span class="h3">Комментарий</span>
<!-- <p class="text-primary h2">Пользователь: {{ result['customerName'] }}</p> -->
<span class="h3">Контент: {{ result['content'] }}</span>
</div>
</div>
<div v-else>
<div class="row is-left mt-2">
<span class="h3">Пост</span>
<!-- <p class="text-primary h2">Пользователь: {{ result['customerName'] }}</p> -->
<span class="h3">Оглавление: {{ result['title'] }}</span>
<span class="h3">Контент: {{ result['content'] }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div v-if="searchMode == -1">
<p class='h3 m-3'>Посты</p>
<div class="row" v-if="currentCustomerId != -1">
<div class="col-7">
<div class="row is-left">
<p class="col-2 is-left mb-2">Заголовок:</p>
<input type="text" class="col-5" v-model="titleModal"/>
</div>
<div class="row is-left">
<p class="col-2 is-left mb-2">Текст:</p>
<textarea type="textarea" class="col-5" v-model="postContentModal"/>
</div>
<div class="row is-left">
<button type='button' class="button btn-primary col-7" v-on:click='createPost'>
Опубликовать
</button>
</div>
</div>
</div>
<div v-if="!(posts.length == 0)" class="row">
<div class="col-5">
<div class="row mb-5 card" v-for="post in posts">
<div class="col">
<div class="row is-left my-3">
<p class="h2"><router-link v-bind:to="'/customers/' + post['customerId']" class="text-primary">{{ post['customerName'] }}</router-link></p>
</div>
<div class="row text-left">
<span class="h2">{{ post['title'] }}</span>
<span class="h3">{{ post['content'] }}</span>
</div>
<div class="row">
<div v-if="!(post['comments'].length == 0)">
<p class="row h3 is-left my-3">Комментарии:</p>
<div class="row text-left mb-4 card" v-for="comment in post['comments']">
<div class="row is-left">
<span class="h2"><router-link v-bind:to="'/customers/' + post['customerId']" class="text-primary">{{ post['customerName'] }}</router-link></span>
<span class="h3">{{ comment['content'] }}</span>
</div>
<div v-if="selectedCustomerContainsComment(comment) == true" class="row mt-3">
<button v-on:click="selectedCommentId = comment['id']; selectedPostTitle = post['title']" class="button primary outline col" data-bs-toggle="modal" data-bs-target="#commentEdit">Изменить</button>
<button v-on:click="deleteComment(comment['id'])" class="button error col">Удалить</button>
</div>
</div>
</div>
<div class="row" v-if="currentCustomerId != -1">
<input type="text" v-bind:id="'post-comment-' + post['id']" class="col-7"/>
<button type="button" v-on:click="selectedPostId = post['id']; selectedPostTitle = post['title']; createComment()" class="button col-5 secondary outline">Комментировать</button>
</div>
</div>
<div class="row" v-if="post['customerId'] == currentCustomerId">
<button type="button" v-on:click="deletePost(post['id'])" class="col button dark outline">Удалить пост</button>
<button type="button" v-on:click="selectedPostId = post['id']" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#postEdit">Изменить пост</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="postEdit" tabindex="-1" role="dialog" aria-labelledby="postEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="postEditLabel">Редактировать пост</h5>
</div>
<div class="modal-body text-center">
<p>{{ currentCustomer['username'] }}</p>
<p>Заголовок</p>
<textarea v-model='titleModal' id="editModalTitle" cols="30" rows="1"></textarea>
<p>Содержание</p>
<textarea v-model='postContentModal' id="editModalPostContent" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="button" class="btn btn-primary" v-on:click='editPost'>Изменить</button>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="commentEdit" tabindex="-1" role="dialog" aria-labelledby="commentEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="commentEditLabel">Изменить комментарий</h5>
</div>
<div class="modal-body text-center">
<p>Под именем:</p>
<p>{{ currentCustomer['username'] }}</p>
<p>К посту:</p>
<p>{{ selectedPostTitle }}</p>
<p>Комментарий</p>
<textarea v-model='contentModal' id="editModalText" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="button" class="btn btn-primary" v-on:click='editComment'>Изменить</button>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
searchResults: [],
customers: [],
selectedCustomerId: 0,
currentCustomer: {},
posts: [],
selectedPostId: 0,
selectedPostTitle: '',
contentModal: '',
titleModal: '',
postContentModal: '',
selectedCommentId: 0,
currentCustomerId: -1,
searchMode: -1,
}
},
methods: {
async getSearchResult(){
const content = document.getElementById("searchString").value
if (content != ''){
this.searchMode = 0;
this.searchResults = [];
const responseSearch = await axios.post('http://localhost:8080/search?searchStr=' + content);
responseSearch.data.forEach(element => {
this.searchResults.push(element);
console.log(element);
});
}
else{
this.searchMode = -1;
this.refreshList();
}
},
selectedCustomerContainsComment(comment) {
var customer = this.customers.find(element => element['id'] == this.currentCustomerId);
console.log(customer);
if (customer == null) return false;
var flag = false;
customer['comments'].forEach(commentIn => {
if (commentIn['id'] == comment['id']) {
flag = true;
}
});
return flag;
},
async createComment() {
const content = document.getElementById("post-comment-" + this.selectedPostId).value
let comment = {
"content": content,
customerId: this.currentCustomerId,
postId: this.selectedPostId
};
await axios.post('http://localhost:8080/api/comment', comment);
document.getElementById("post-comment-" + this.selectedPostId).value = ''
this.refreshList();
},
async deleteComment(commentId) {
await axios.delete('http://localhost:8080/api/comment/' + commentId);
this.refreshList();
},
async editComment(){
let comment = {
content: this.contentModal,
customerId: this.currentCustomerId,
postId: 0
};
await axios.put('http://localhost:8080/api/comment/' + this.selectedCommentId, comment);
this.refreshList();
},
async createPost() {
let post = {
"content": this.postContentModal,
title: this.titleModal,
customerId: this.currentCustomerId
};
const response = await axios.post('http://localhost:8080/api/post', post);
this.titleModal = ''
this.postContentModal = ''
this.refreshList();
},
async deletePost(postId) {
const response = await axios.delete('http://localhost:8080/api/post/' + postId);
this.refreshList();
},
async editPost(){
let post = {
"content": this.postContentModal,
title: this.titleModal,
customerId: this.currentCustomerId
};
const response = await axios.put('http://localhost:8080/api/post/' + this.selectedPostId, post);
this.refreshList();
},
async refreshList(){
this.customers = [];
this.posts = [];
const responseCustomer = await axios.get('http://localhost:8080/api/customer');
responseCustomer.data.forEach(element => {
this.customers.push(element);
console.log(element);
});
const responsePost = await axios.get('http://localhost:8080/api/post');
responsePost.data.forEach(element => {
this.posts.splice(0, 0, element);
console.log(element);
});
}
},
async beforeMount() {
this.currentCustomerId = history.state;
setInterval(async () => this.currentCustomerId = history.state, 50)
const responseCustomer = await axios.get('http://localhost:8080/api/customer');
responseCustomer.data.forEach(element => {
this.customers.push(element);
if (element['id'] == this.currentCustomerId) {
this.currentCustomer = element;
}
console.log(element);
});
const responsePost = await axios.get('http://localhost:8080/api/post');
responsePost.data.forEach(element => {
this.posts.splice(0, 0, element);
console.log(element);
});
}
}
</script>
<style lang="">
</style>

View File

@ -0,0 +1,69 @@
<template>
<div class="row">
<div class="col"></div>
<div class="col-6">
<div class="row">
<label>Имя пользователя: <input type="text" id="username" required /></label>
</div>
<div class="row">
<label>Пароль: <input v-on:change="check()" type="password" id="password" required /></label>
</div>
<div class="row">
<label>Пароль повторно: <input v-on:change="check()" type="password" id="confirm-password" required /></label>
</div>
<div class="row mb-3 alert alert-danger" v-if="error !== null" role="alert">
{{ error }}
</div>
<div class="row mt-3">
<div class="col-4"></div>
<button v-on:click="register()" class="button primary col" id="enter" disabled>Регистрация</button>
<div class="col-4"></div>
</div>
</div>
<div class="col"></div>
</div>
</template>
<script>
export default {
data() {
return {
error: null
}
},
methods: {
check() {
if ($("#password").val() === $("#confirm-password").val()) {
$("#enter").removeAttr("disabled")
} else {
$("#enter").attr("disabled", "disabled")
}
},
async register() {
const response = await fetch(
"http://localhost:8080/api/1.0/customer",
{
method: "POST",
body: JSON.stringify({
"username": $("#username").val(),
"password": $("#password").val()
}),
headers: {
'Content-Type': 'application/json'
}
}
)
if (response.status !== 200) {
this.error = await response.text()
} else {
this.$router.push("login")
}
}
}
}
</script>
<style>
</style>

View File

@ -3,20 +3,36 @@ import App from './App'
import { createRouter, createWebHistory } from "vue-router" import { createRouter, createWebHistory } from "vue-router"
import Customers from './components/Customers' import Customers from './components/Customers'
import Posts from './components/Posts' import Feed from './components/Feed'
import Login from "@/components/Login.vue";
import Signup from "@/components/Signup.vue";
import Admin from "@/components/Admin.vue";
const routes = [ const routes = [
{ {
path: '/customers/:id?', path: '/customers/:id?',
name: "Customers", name: "Customers",
component: Customers, component: Customers
props: true
}, },
{ {
path: '/posts', path: '/feed',
name: "Posts", name: "Feed",
component: Posts, component: Feed
props: true },
{
path: '/login',
name: "Login",
component: Login
},
{
path: '/signup',
name: "Signup",
component: Signup
},
{
path: '/admin',
name: "Admin",
component: Admin
} }
] ]

View File

@ -23,6 +23,7 @@ import org.springframework.security.web.authentication.LoginUrlAuthenticationEnt
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
import ru.ulstu.is.labwork.WebConfiguration;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -50,42 +51,44 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
} }
} }
@Override //mvc java
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().authenticationEntryPoint(delegatingEntryPoint());
http.headers().frameOptions().sameOrigin().and()
.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers(UserSignUp.SIGNUP_URL).permitAll()
.antMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(LOGIN_URL).permitAll()
.and()
.logout().permitAll();
}
// @Override // @Override
// protected void configure(HttpSecurity http) throws Exception { // protected void configure(HttpSecurity http) throws Exception {
// log.info("Creating security configuration"); // http.exceptionHandling().authenticationEntryPoint(delegatingEntryPoint());
// http.cors() // http.headers().frameOptions().sameOrigin().and()
// .and() // .cors().and()
// .csrf().disable() // .csrf().disable()
// .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// .and()
// .authorizeRequests() // .authorizeRequests()
// .antMatchers("/", SPA_URL_MASK).permitAll() // .antMatchers(UserSignUp.SIGNUP_URL).permitAll()
// .antMatchers(HttpMethod.POST, WebConfiguration.REST_API + "/customer" + CustomerController.URL_LOGIN).permitAll() // .antMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
// .antMatchers(HttpMethod.POST, WebConfiguration.REST_API + "/customer").permitAll() // .anyRequest().authenticated()
// .anyRequest()
// .authenticated()
// .and() // .and()
// .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class) // .formLogin()
// .anonymous(); // .loginPage(LOGIN_URL).permitAll()
// .and()
// .logout().permitAll();
// } // }
//jwt vue
@Override
protected void configure(HttpSecurity http) throws Exception {
log.info("Creating security configuration");
http.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/", SPA_URL_MASK).permitAll()
.antMatchers(HttpMethod.POST, WebConfiguration.REST_API + "/customer" + CustomerController.URL_LOGIN).permitAll()
.antMatchers(HttpMethod.POST, WebConfiguration.REST_API + "/customer").permitAll()
.anyRequest()
.authenticated()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.anonymous();
}
@Override @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customerService); auth.userDetailsService(customerService);