Lab6: I wish I could turn into Mercury Snake. Lab 6 is ready

This commit is contained in:
Сергей Полевой 2023-05-24 02:47:43 +04:00
parent 75f4b6a178
commit bebea782c7
17 changed files with 755 additions and 349 deletions

View File

@ -6,6 +6,7 @@
<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.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" 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> <script src="https://code.jquery.com/jquery-3.7.0.slim.min.js" integrity="sha256-tG5mcZUtJsZvyKAxYLVXrmjKBVLd6VpVccqz/r4ypFE=" crossorigin="anonymous"></script>
<title>Социальная сеть</title> <title>Социальная сеть</title>
</head> </head>

View File

@ -6,8 +6,8 @@
<router-link v-if="role === 'ADMIN'" to="/admin" v-bind:class="'button primary ' + this.$route.path.startsWith('/admin')? 'clear' : ''">Администрирование</router-link> <router-link v-if="role === 'ADMIN'" to="/admin" v-bind:class="'button primary ' + this.$route.path.startsWith('/admin')? 'clear' : ''">Администрирование</router-link>
</div> </div>
<div class="nav-right col-2"> <div class="nav-right col-2">
<router-link v-if="" to="/login" v-bind:class="'button primary ' + this.$route.path.startsWith('/login')? 'clear' : ''">Войти</router-link> <router-link v-if="this.token_value == null" to="/login" v-bind:class="'button primary ' + this.$route.path.startsWith('/login')? 'clear' : ''">Войти</router-link>
<button v-on:click="logout()" v-bind:class="'button primary ' + this.$route.path.startsWith('/signup')? 'clear' : ''">Выйти</button> <button v-if="this.token_value != null" v-on:click="logout()" v-bind:class="'button primary ' + this.$route.path.startsWith('/signup')? 'clear' : ''">Выйти</button>
</div> </div>
</div> </div>
<router-view></router-view> <router-view></router-view>
@ -24,7 +24,23 @@ export default {
methods: { methods: {
logout() { logout() {
this.token = null this.token = null
this.role = ''
localStorage.clear()
this.$router.push('login') 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: { computed: {
@ -35,6 +51,7 @@ export default {
set: function(value) { set: function(value) {
this.token_value = value this.token_value = value
localStorage.setItem("token", value) localStorage.setItem("token", value)
localStorage.setItem("role", this.role)
} }
} }
}, },
@ -43,22 +60,13 @@ export default {
return null; return null;
} }
let response = await fetch( await this.actualRole()
"http://localhost:8080/api/1.0/customer/role/" + localStorage.getItem("token"),
{
method: "POST",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.role = await response.json()
const component = this const component = this
document.addEventListener('token_changed', function() { document.addEventListener('token_changed', async function() {
component.token = localStorage.getItem("token") component.token = localStorage.getItem("token")
await component.actualRole()
}) })
} }
} }

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

@ -33,7 +33,7 @@
</div> </div>
<p v-else class="row">Нет постов</p> <p v-else class="row">Нет постов</p>
<div class="row" v-if="currentCustomerId === customer['id']"> <div class="row" v-if="currentCustomerId === customer['id']">
<button v-on:click="deleteCustomer(customer)" class="button dark outline is-full-width">Удалить</button> <button v-on:click="deleteCustomer(customer)" class="button dark outline col">Удалить</button>
<button v-on:click="prepareEditModal(customer)" 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>
@ -57,7 +57,7 @@
</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 v-on:click="editCustomer()" type="button" class="btn btn-primary"> data-bs-dismiss="modal"Изменить</button> <button v-on:click="editCustomer()" type="button" class="btn btn-primary">Изменить</button>
</div> </div>
</div> </div>
</div> </div>
@ -74,6 +74,7 @@ export default {
}, },
methods: { methods: {
async updateCustomers() { async updateCustomers() {
if (!this.$route.params.id) {
const response = await fetch( const response = await fetch(
"http://localhost:8080/api/1.0/customer", "http://localhost:8080/api/1.0/customer",
{ {
@ -83,8 +84,20 @@ export default {
} }
} }
) )
this.customers = await response.json() this.customers = await response.json()
}
else {
const response = await fetch(
"http://localhost:8080/api/1.0/customer/" + this.$route.params.id,
{
method: "GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.customers = [await response.json()]
}
}, },
async getCurrentCustomer() { async getCurrentCustomer() {
const response = await fetch( const response = await fetch(
@ -120,23 +133,26 @@ export default {
await fetch( await fetch(
"http://localhost:8080/api/1.0/customer/" + this.currentCustomerId, "http://localhost:8080/api/1.0/customer/" + this.currentCustomerId,
{ {
method: "GET", method: "PUT",
headers: { headers: {
'Content-Type': 'application/json',
"Authorization": "Bearer " + localStorage.getItem("token") "Authorization": "Bearer " + localStorage.getItem("token")
}, },
body: JSON.stringify({ body: JSON.stringify({
username: $("usernameTextE").val(), "username": $("#usernameTextE").val(),
password: $("passwordTextE").val() "password": $("#passwordTextE").val()
}) })
} }
) )
await this.updateCustomers() localStorage.clear()
this.$router.replace("login")
} }
}, },
async beforeMount() { async beforeMount() {
if (localStorage.getItem("token") === null) { if (localStorage.getItem("token") == null) {
this.$router.replace("login") this.$router.push("login")
} }
await Promise.all([this.updateCustomers(), this.getCurrentCustomer()]) await Promise.all([this.updateCustomers(), this.getCurrentCustomer()])

View File

@ -0,0 +1,338 @@
<template>
<div>
<div class="row">
<div class="col">
<div class="row mb-5">
<p class='is-center h2'>Посты</p>
</div>
<form class="row mb-5" @submit.prevent="searchPosts">
<input type="search" v-model="searchQuery" class="col-10">
<button class="button primary col" type="submit">Найти</button>
</form>
<div class="row mb-5" v-if="currentCustomerId > 0">
<div class="col"></div>
<form class="col-10" @submit.prevent="createPost">
<input name="customerId" type="text" style="display: none;" :value="currentCustomerId">
<div class="row mb-4 is-center">
<p class="col-2 is-left mb-2">Заголовок:</p>
<input name="title" type="text" class="col-6" v-model="newPost.title" />
</div>
<div class="row mb-4 is-center">
<p class="col-2 is-left mb-2">Текст:</p>
<textarea name="content" class="col-6" v-model="newPost.content"></textarea>
</div>
<div class="row is-center">
<button type='submit' class="button primary col-8">
Опубликовать
</button>
</div>
</form>
<div class="col"></div>
</div>
<div v-if="posts.length > 0" class="row">
<div class="col">
<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 class="col is-right">
<p>Дата: <span class="text-primary">{{ post.createDate }}</span></p>
</div>
</div>
<div class="row text-center">
<span class="h1">{{ post.title }}</span>
</div>
<div class="row text-center mb-5">
<span class="h3">{{ post.content }}</span>
</div>
<div class="row">
<div class="col">
<p class="row h2 is-center mb-3">Комментарии</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 mb-1">
<div class="col is-left">
<span class="h2 text-primary">{{ comment.customerName }}</span>
</div>
<div class="col is-right">
<span class="h2 text-primary">{{ comment.createDate }}</span>
</div>
</div>
<div class="row mb-3">
<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-9" 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-3 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 v-else class="row text-center is-center">
Нет постов
</div>
</div>
</div>
<!-- Modal for editing a post -->
<div class="modal fade" id="postEdit" tabindex="-1" role="dialog" aria-labelledby="postEditLabel" 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="postEditLabel">Изменить пост</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<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 for editing a comment -->
<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">
<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>
</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

@ -17,7 +17,7 @@
<div class="col-4"></div> <div class="col-4"></div>
</div> </div>
<div class="row mt-5"> <div class="row mt-5">
<router-link to="/login" class="button primary outline">Регистрация</router-link> <router-link to="/signup" class="button primary outline">Регистрация</router-link>
</div> </div>
</div> </div>
<div class="col"></div> <div class="col"></div>
@ -38,13 +38,16 @@
{ {
method: "POST", method: "POST",
body: JSON.stringify({ body: JSON.stringify({
username: $("#username").val(), "username": $("#username").val(),
password: $("#password").val() "password": $("#password").val()
}) }),
headers: {
'Content-Type': 'application/json'
}
} }
) )
if (response.statusCode !== 200) { if (response.status !== 200) {
this.error = await response.text() this.error = await response.text()
} else { } else {
localStorage.setItem("token", await response.text()) localStorage.setItem("token", await response.text())

View File

@ -1,247 +0,0 @@
<template>
<div class="row">
<div class="col">
<div class="row mb-5">
<p class='is-center h2'>Посты</p>
</div>
<div class="row mb-5" v-if="currentCustomerId != -1">
<div class="col"></div>
<div class="col-10">
<div class="row mb-4 is-center">
<p class="col-2 is-left mb-2">Заголовок:</p>
<input type="text" class="col-6" v-model="titleModal"/>
</div>
<div class="row mb-4 is-center">
<p class="col-2 is-left mb-2">Текст:</p>
<textarea type="textarea" class="col-6" v-model="postContentModal"/>
</div>
<div class="row is-center">
<button type='button' class="button primary col-8" v-on:click='createPost'>
Опубликовать
</button>
</div>
</div>
<div class="col"></div>
</div>
<div v-if="!(posts.length == 0)" class="row">
<div class="col">
<div class="row mb-5 card" v-for="post in posts">
<div class="col">
<div class="row h3">
<div class="col is-left">
<p>Автор: <router-link v-bind:to="'/customers/' + post['customerId']" class="text-primary">{{ post['customerName'] }}</router-link></p>
</div>
<div class="col is-right">
<p>Дата: <span class="text-primary">{{ post['createDate'] }}</span></p>
</div>
</div>
<div class="row text-center">
<span class="h1">{{ post['title'] }}</span>
</div>
<div class="row text-center mb-5">
<span class="h3">{{ post['content'] }}</span>
</div>
<div class="row">
<div class="col">
<p class="row h2 is-center mb-3">Комментарии</p>
<div v-if="!(post['comments'].length == 0)" class="row text-left mb-5 card" v-for="comment in post['comments']">
<div class="row mb-1">
<div class="col is-left">
<span class="h2 text-primary">{{ comment['customerName'] }}</span>
</div>
<div class="col is-right">
<span class="h2 text-primary">{{ comment['createDate'] }}</span>
</div>
</div>
<div class="row mb-3">
<span class="h3">{{ comment['content'] }}</span>
</div>
<div v-if="selectedCustomerContainsComment(comment) == true" class="row">
<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>
<p v-else class="h3 row is-center mb-5">Пусто</p>
<div class="row" v-if="currentCustomerId != -1">
<input type="text" v-bind:id="'post-comment-' + post['id']" class="col-9"/>
<button type="button" v-on:click="selectedPostId = post['id']; selectedPostTitle = post['title']; createComment()" class="button col-3 secondary outline">Комментировать</button>
</div>
</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 v-else class="row text-center is-center">
Нет постов
</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>
<!-- 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>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
customers: [],
selectedCustomerId: 0,
currentCustomer: {},
posts: [],
selectedPostId: 0,
selectedPostTitle: '',
contentModal: '',
titleModal: '',
postContentModal: '',
selectedCommentId: 0,
currentCustomerId: -1,
}
},
methods: {
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

@ -33,7 +33,7 @@ export default {
}, },
methods: { methods: {
check() { check() {
if ($("#password").val() !== $("#confirm-password").val()) { if ($("#password").val() === $("#confirm-password").val()) {
$("#enter").removeAttr("disabled") $("#enter").removeAttr("disabled")
} else { } else {
$("#enter").attr("disabled", "disabled") $("#enter").attr("disabled", "disabled")
@ -45,13 +45,16 @@ export default {
{ {
method: "POST", method: "POST",
body: JSON.stringify({ body: JSON.stringify({
username: $("#username").val(), "username": $("#username").val(),
password: $("#password").val() "password": $("#password").val()
}) }),
headers: {
'Content-Type': 'application/json'
}
} }
) )
if (response.statusCode !== 200) { if (response.status !== 200) {
this.error = await response.text() this.error = await response.text()
} else { } else {
this.$router.push("login") this.$router.push("login")

View File

@ -5,6 +5,8 @@ import { createRouter, createWebHistory } from "vue-router"
import Customers from './components/Customers' import Customers from './components/Customers'
import Feed from './components/Feed' import Feed from './components/Feed'
import Login from "@/components/Login.vue"; import Login from "@/components/Login.vue";
import Signup from "@/components/Signup.vue";
import Admin from "@/components/Admin.vue";
const routes = [ const routes = [
{ {
@ -21,6 +23,16 @@ const routes = [
path: '/login', path: '/login',
name: "Login", name: "Login",
component: Login component: Login
},
{
path: '/signup',
name: "Signup",
component: Signup
},
{
path: '/admin',
name: "Admin",
component: Admin
} }
] ]

View File

@ -65,7 +65,7 @@ public class CustomerController {
@GetMapping ("/me") @GetMapping ("/me")
CustomerDto getCurrentCustomer(@RequestHeader(HttpHeaders.AUTHORIZATION) String token) { CustomerDto getCurrentCustomer(@RequestHeader(HttpHeaders.AUTHORIZATION) String token) {
return new CustomerDto(customerService.findByUsername(customerService.loadUserByToken(token).getUsername())); return new CustomerDto(customerService.findByUsername(customerService.loadUserByToken(token.substring(7)).getUsername()));
} }
@GetMapping("role/{token}") @GetMapping("role/{token}")

View File

@ -52,4 +52,15 @@ public class PostController {
public void deleteAllPosts() { public void deleteAllPosts() {
postService.deleteAllPosts(); postService.deleteAllPosts();
} }
@GetMapping("/search")
public List<PostDto> searchPosts(@RequestParam(required = false) String query) {
if (query == null || query.isBlank()) {
return postService.findAllPosts().stream()
.map(PostDto::new)
.toList();
} else {
return postService.searchPosts(query);
}
}
} }

View File

@ -16,6 +16,7 @@ import org.springframework.web.bind.annotation.*;
@Controller @Controller
@RequestMapping("/admin") @RequestMapping("/admin")
@Secured({UserRole.AsString.ADMIN})
public class Admin { public class Admin {
private final CustomerService customerService; private final CustomerService customerService;

View File

@ -45,28 +45,7 @@ public class Feed {
if (search == null) { if (search == null) {
model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList()); model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList());
} else { } else {
var posts = new ArrayList<>(postService.searchPosts(search)); model.addAttribute("posts", postService.searchPosts(search));
var comments = commentService.searchComments(search);
for (var post: posts) {
post.getComments().clear();
}
for (var comment: comments) {
boolean found = false;
for (var post: posts) {
if (Objects.equals(comment.getPost().getId(), post.getId())) {
post.getComments().add(comment);
found = true;
break;
}
}
if (!found) {
var newPost = comment.getPost();
newPost.getComments().clear();
newPost.getComments().add(comment);
posts.add(newPost);
}
}
model.addAttribute("posts", posts.stream().map(PostDto::new).toList());
} }
model.addAttribute("customers", customerService.findAllCustomers().stream().map(CustomerDto::new).toList()); model.addAttribute("customers", customerService.findAllCustomers().stream().map(CustomerDto::new).toList());

View File

@ -7,6 +7,7 @@ import np.something.mvc.UserSignUp;
import np.something.services.CustomerService; import np.something.services.CustomerService;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
@ -16,7 +17,15 @@ import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint;
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
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.RequestMatcher;
import java.util.LinkedHashMap;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@ -42,40 +51,42 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
} }
} }
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// 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()
.anyRequest() .anyRequest().authenticated()
.authenticated()
.and() .and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class) .formLogin()
.anonymous(); .loginPage(LOGIN_URL).permitAll()
.and()
.logout().permitAll();
} }
// @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);
@ -91,4 +102,16 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.antMatchers("/swagger-resources/**") .antMatchers("/swagger-resources/**")
.antMatchers("/v3/api-docs/**"); .antMatchers("/v3/api-docs/**");
} }
@Bean
public AuthenticationEntryPoint delegatingEntryPoint() {
final LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> map = new LinkedHashMap();
map.put(new AntPathRequestMatcher("/"), new LoginUrlAuthenticationEntryPoint("/login"));
map.put(new AntPathRequestMatcher("/api/1.0/**"), new Http403ForbiddenEntryPoint());
final DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(map);
entryPoint.setDefaultEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
return entryPoint;
}
} }

View File

@ -1,30 +1,31 @@
package np.something.services; package np.something.services;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import np.something.DTO.PostDto;
import np.something.Exceptions.PostNotFoundException; import np.something.Exceptions.PostNotFoundException;
import np.something.model.Comment;
import np.something.model.Customer; import np.something.model.Customer;
import np.something.model.Post; import np.something.model.Post;
import np.something.repositories.CustomerRepository; import np.something.repositories.CommentRepository;
import np.something.repositories.PostRepository; import np.something.repositories.PostRepository;
import np.something.util.validation.ValidatorUtil; import np.something.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
@Service @Service
public class PostService { public class PostService {
private final PostRepository postRepository; private final PostRepository postRepository;
private final CommentRepository commentRepository;
private final ValidatorUtil validatorUtil; private final ValidatorUtil validatorUtil;
public PostService(PostRepository postRepository, public PostService(PostRepository postRepository,
ValidatorUtil validatorUtil) { CommentRepository commentRepository, ValidatorUtil validatorUtil) {
this.postRepository = postRepository; this.postRepository = postRepository;
this.commentRepository = commentRepository;
this.validatorUtil = validatorUtil; this.validatorUtil = validatorUtil;
} }
@ -70,7 +71,28 @@ public class PostService {
} }
@Transactional @Transactional
public List<Post> searchPosts(String tag) { public List<PostDto> searchPosts(String search) {
return postRepository.searchPosts(tag); var posts = new ArrayList<>(postRepository.searchPosts(search));
var comments = commentRepository.searchComments(search);
for (var post: posts) {
post.getComments().clear();
}
for (var comment: comments) {
boolean found = false;
for (var post: posts) {
if (Objects.equals(comment.getPost().getId(), post.getId())) {
post.getComments().add(comment);
found = true;
break;
}
}
if (!found) {
var newPost = comment.getPost();
newPost.getComments().clear();
newPost.getComments().add(comment);
posts.add(newPost);
}
}
return posts.stream().map(PostDto::new).toList();
} }
} }

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="alert alert-danger">
<span th:text="${error}"></span>
</div>
<a href="/" class="is-center">На главную</a>
</div>
</body>
</html>

View File

@ -76,7 +76,7 @@
<p th:if="${#arrays.isEmpty(post.comments)}" class="h3 row is-center mb-5">Пусто</p> <p th:if="${#arrays.isEmpty(post.comments)}" class="h3 row is-center mb-5">Пусто</p>
<form class="row" th:if="${currentCustomerId != -1}" th:action="@{/comments/}" method="post"> <form class="row" th:if="${currentCustomerId != -1}" th:action="@{/comments/}" method="post">
<input name="content" type="text" class="col-9"/> <input name="content" type="text" class="col-9"/>
<input name="customerId" type="text" style="display: none;" th:value="${session.currentCustomerId}"> <input name="customerId" type="text" style="display: none;" th:value="${currentCustomerId}">
<input name="postId" type="text" style="display: none;" th:value="${post.id}"> <input name="postId" type="text" style="display: none;" th:value="${post.id}">
<button type="submit" class="button col-3 secondary outline">Комментировать</button> <button type="submit" class="button col-3 secondary outline">Комментировать</button>
</form> </form>