Compare commits

...

35 Commits

Author SHA1 Message Date
ityurner02@mail.ru
cf09538c11 ЛР6(Vue) еще чуть-чуть безопасности 2023-06-11 21:28:10 +04:00
ityurner02@mail.ru
24190594f1 ЛР6(Vue) оно работает 2023-06-10 21:06:52 +04:00
ityurner02@mail.ru
57596deb85 ЛР4 теперь готова 2023-05-21 19:56:47 +04:00
ityurner02@mail.ru
72cc3edb7d ЛР4 -лишнее 2023-05-21 17:34:35 +04:00
ityurner02@mail.ru
1126696bb9 ЛР4 коллекции тоже работают, остался отчет 2023-05-21 17:32:22 +04:00
ityurner02@mail.ru
446e83c38e ЛР4 фильмы работают с чекбоксами как надо 2023-05-20 21:51:38 +04:00
ityurner02@mail.ru
e1fe87f1fa ЛР4 начало изменений 2023-05-20 20:15:57 +04:00
ityurner02@mail.ru
c9132c20eb ЛР4 сдано, но плохо отображаются зависимости 2023-05-20 19:23:43 +04:00
ityurner02@mail.ru
01d5b136ef ЛР4 -лишнее 2023-05-15 23:51:24 +04:00
ityurner02@mail.ru
04fea2fcc8 ЛР4 чекбоксы работают с бд! 2023-05-15 23:36:37 +04:00
ityurner02@mail.ru
411eb34bab ЛР4 и как? 2023-05-15 19:18:19 +04:00
ityurner02@mail.ru
3d47fb12ef ЛР4 все работает 2023-05-04 21:57:42 +04:00
ityurner02@mail.ru
361d0a65ff ЛР4 полность работают фильмы и жанры 2023-05-04 20:04:29 +04:00
ityurner02@mail.ru
b07faa67c5 ЛР4 считываются жанры для каждого фильма, но не редактируются 2023-05-03 22:18:30 +04:00
ityurner02@mail.ru
1d1b1404b0 ЛР4 жанры работают 2023-05-01 17:36:10 +04:00
ityurner02@mail.ru
49b8125146 ЛР4 беда на бэке 2023-04-25 13:06:29 +04:00
ityurner02@mail.ru
da683c642b ЛР4 фронт без таблиц 2023-04-24 22:35:59 +04:00
ityurner02@mail.ru
8b69f68e7a ЛР4 картинки 2023-04-24 22:14:20 +04:00
ityurner02@mail.ru
da4a1da4b6 ЛР4 для баннера 2023-04-24 22:12:50 +04:00
ityurner02@mail.ru
b159ec0dd7 ЛР4 убрал лишнее 2023-04-24 22:00:57 +04:00
ityurner02@mail.ru
fab6531bdd ЛР4 добавлен vue проект 2023-04-24 18:37:21 +04:00
ityurner02@mail.ru
52373b5692 ЛР4 исправление валидатора 2023-04-23 18:16:52 +04:00
ityurner02@mail.ru
882ef19a8d ЛР4 бэкенд 2023-04-23 17:36:17 +04:00
ityurner02@mail.ru
78116eb994 ЛР3 сдано! 2023-04-11 10:14:53 +04:00
ityurner02@mail.ru
3e57102a6d ЛР3 доп задание 2023-04-10 22:02:08 +04:00
ityurner02@mail.ru
8baede6bca ЛР3 без доп задания 2023-04-03 16:29:42 +04:00
ityurner02@mail.ru
de105ade49 ЛР3 -import 2023-03-27 19:39:05 +04:00
ityurner02@mail.ru
1880d0dc53 ЛР3 добавление тестов 2023-03-27 19:36:00 +04:00
ityurner02@mail.ru
3ef4a530ee ЛР3 корректировка связи 2023-03-26 21:06:58 +04:00
ityurner02@mail.ru
3df09259bd ЛР3 все кроме тестов 2023-03-25 20:43:23 +04:00
ityurner02@mail.ru
dfe84a7b21 ЛР2 фикс последнего теста 2023-03-14 08:41:04 +04:00
ityurner02@mail.ru
46ecf5eac3 ЛР2 добавление теста 2023-02-28 11:36:07 +04:00
ityurner02@mail.ru
aac82d37ee ЛР2 тесты и корректировка MethodInt 2023-02-28 10:48:49 +04:00
ityurner02@mail.ru
84c206fb61 ЛР2 Все кроме тестов 2023-02-28 10:16:20 +04:00
ityurner02@mail.ru
f68abec3fa ЛР1 2023-02-14 12:37:40 +04:00
76 changed files with 6271 additions and 19 deletions

28
Frontend/vue-project/.gitignore vendored Normal file
View File

@ -0,0 +1,28 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
/cypress/videos/
/cypress/screenshots/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -0,0 +1,29 @@
# vue-project
This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).
## Customize configuration
See [Vite Configuration Reference](https://vitejs.dev/config/).
## Project Setup
```sh
npm install
```
### Compile and Hot-Reload for Development
```sh
npm run dev
```
### Compile and Minify for Production
```sh
npm run build
```

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/node_modules/@fortawesome/fontawesome-free/css/all.min.css">
<title>VIDEO | FILMS</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script type="module" src="/src/main.js"></script>
</body>
</html>

3072
Frontend/vue-project/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,26 @@
{
"name": "vue-project",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@fortawesome/fontawesome-free": "^6.2.1",
"@vuelidate/core": "^2.0.0",
"@vuelidate/validators": "^2.0.0",
"axios": "^1.1.3",
"bootstrap": "^5.2.2",
"vue": "^3.2.47",
"vue-router": "^4.1.6",
"vuelidate": "^0.7.7"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.0.0",
"@vitejs/plugin-vue-jsx": "^3.0.0",
"vite": "^4.3.1"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -0,0 +1,66 @@
<script>
import Header from './components/Header.vue';
import Footer from './components/Footer.vue';
export default {
components: {
Header,
Footer
},
data() {
return {
tokenFromServer: undefined,
userFromServer: undefined,
securityError: false,
}
},
created() {
const self = this
window.addEventListener('storage', function(e){
console.log(e)
if(e.key === "token")
if(this.tokenFromServer !== e.newValue) {
self.storageSecurity()
}
if(e.key === "user")
if(this.userFromServer !== e.newValue) {
self.storageSecurity()
}
})
},
methods: {
storageSecurity(){
localStorage.clear()
this.$router.push("/login")
this.securityError = true
},
saveServerData(data){
this.tokenFromServer = data.token
this.userFromServer = data.user
},
},
}
</script>
<template>
<Header></Header>
<div class="container-fluid">
<router-view></router-view>
</div>
<Footer></Footer>
</template>
<style>
body {
background: fixed;
background-color: blue !important;
min-height: 100vh;
position: relative;
}
.last_info, .block_films{
font-size: 2rem !important;
}
.mock {
width: 100%;
height: 120px;
}
</style>

View File

@ -0,0 +1,272 @@
<script>
import 'axios';
import axios from "axios";
import Collection from "../models/Collection";
import Film from "../models/Film";
export default {
created() {
this.getCollections();
this.getFilms();
},
mounted() {
const addModal = document.getElementById('editModal');
addModal.addEventListener('shown.bs.modal', function () {
})
const openModalForAdd = document.getElementById('openModalForAdd');
openModalForAdd.addEventListener('shown.bs.modal', function () {
})
},
data() {
return{
collections: [],
URL: "http://localhost:8080/api/1.0/",
collection: new Collection(),
films: [],
postParams: {
method:"POST",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
putParams: {
method:"PUT",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
},
},
delParams: {
method:"DELETE",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
getParams: {
method:"GET",
headers:{
"Authorization": "Bearer " + localStorage.getItem("token"),
}
}
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
methods: {
getCollections(){
axios.get(this.URL + "collection", this.getParams)
.then(response => {
this.collections = response.data;
})
.catch(error => {
console.log(error);
});
},
addCollection(collection){
console.log(collection);
axios.post(this.URL + "collection", collection, this.postParams)
.then(() => {
this.getCollections();
this.closeModal();
})
.catch(error => {
console.log(error);
});
},
deleteCollection(id){
axios.delete(this.URL + `collection/${id}`, this.delParams)
.then(() =>{
this.getCollections();
})
},
editCollection(collection){
axios.put(this.URL + `collection/${collection.id}`, collection, this.putParams)
.then(() =>{
const index = this.collections.findIndex((s) => s.id === collection.id);
if (index !== -1) {
this.collections[index] = { ...collection };
}
this.closeModal();
this.getCollections();
})
this.closeModal();
},
openModalForAdd(status, collection = null) {
if (status === "create") {
this.collection = new Collection();
this.collection.status = "create";
} else if (status === "edit" && collection) {
this.collection = { ...collection };
this.collection.status = "edit";
}
document.getElementById("openModalForAdd").style.display = "block";
},
closeModalForAdd() {
document.getElementById("openModalForAdd").style.display = "none";
this.collection = new Collection();
},
openModal(status, collection = null) {
if (status === "create") {
this.collection = new Collection();
this.collection.status = "create";
} else if (status === "edit" && collection) {
this.collection = { ...collection };
this.collection.status = "edit";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
getFilms(){
axios.get(this.URL + "film", this.getParams)
.then(response => {
this.films = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addCollectionFilm(id) {
let filmId = document.getElementById('films').value;
axios.post(this.URL + `collection/add_film/${id}`, filmId, this.postParams)
.then(() => {
this.closeModalForAdd();
this.getCollections();
})
.catch((error) => {
console.log(error);
});
},
delCollectionFilm(id) {
let filmId = document.getElementById('films').value;
axios.delete(this.URL + `collection/del_film/${id}?film_id=${filmId}`, this.delParams)
.then(() => {
this.closeModalForAdd();
this.getCollections();
})
.catch((error) => {
console.log(error);
});
},
itemsGenres(filmIds) {
let result = [];
if (typeof filmIds === 'undefined') {
return;
}
this.films.forEach(film => {
for (let i = 0; i < filmIds.length; i++) {
if (film.id === filmIds[i]) {
result.push(film);
}
}
});
return result;
}
}
}
</script>
<template>
<div class="container mt-4">
<h1 class="text-center text-danger mb-4">Коллекции</h1>
<button class="btn btn-success mr-2" @click="openModal('create')">Добавить</button>
<table class="table text-light">
<thead>
<tr>
<th>Название</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="col in collections" :key="col.id">
<td>{{ col.name }}</td>
<td>
<td>
<button class="btn btn-warning mr-2" @click="openModal('edit', col)">Изменить</button>
</td>
<td>
<button class="btn btn-danger" @click="deleteCollection(col.id)">Удалить</button>
</td>
<td>
<button class="btn btn-success mr-2" @click="openModalForAdd('edit', col);">Добавить фильмы</button>
</td>
</td>
</tr>
</tbody>
</table>
</div>
<!--Форма для создания коллекций-->
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Коллекция</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">Название:</label>
<input type="text" class="form-control" id="name" name="name" v-model="collection.name">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="collection.status === 'create'" @click="addCollection(collection)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editCollection(collection)">Сохранить</button>
</div>
</div>
</div>
</div>
<!--Форма для привязки коллекции и фильма -->
<div class="modal" tabindex="-1" id="openModalForAdd">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Добавление фильмов</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">Название:</label>
<input readonly type="text" class="form-control" id="name" name="name" v-model="collection.name">
</div>
<div class="form-group">
<label for="name">Фильмы:</label>
<ul class="list-group">
<li class="list-group-item" v-for="film in itemsGenres(this.collection.filmIds)" :key="film.id">
<div>
<label>{{ film.name }}</label>
</div>
</li>
</ul>
<div class="mt-4">
<label>Выберите фильм</label>
<select class="form-select" id="films" required>
<option v-for="film in this.films"
:value="film.id">
{{ film.name }}
</option>
</select>
</div>
</div>
<div class="d-flex justify-content-between mt-4">
<button class="btn btn-success" type="button" id="addFilmButton"
@click="addCollectionFilm(this.collection.id)">Добавить</button>
<button class="btn btn-danger" type="button" id="delFilmButton"
@click="delCollectionFilm(this.collection.id)">Удалить</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModalForAdd()">Закрыть</button>
</div>
</div>
</div>
</div>
</template>

View File

@ -0,0 +1,249 @@
<script>
import 'axios';
import axios from "axios";
import Film from "../models/Film";
import Genre from "../models/Genre";
export default {
created() {
this.getFilms();
this.getGenres();
},
mounted() {
const addModal = document.getElementById('editModal');
addModal.addEventListener('shown.bs.modal', function () {
})
const openModalForAdd = document.getElementById('openModalForAdd');
openModalForAdd.addEventListener('shown.bs.modal', function () {
})
},
data() {
return{
films: [],
URL: "http://localhost:8080/api/1.0/",
film: new Film(),
genres: [],
selectedGenres: [],
open: [],
postParams: {
method:"POST",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
putParams: {
method:"PUT",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
},
},
delParams: {
method:"DELETE",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
getParams: {
method:"GET",
headers:{
"Authorization": "Bearer " + localStorage.getItem("token"),
}
}
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
methods: {
getFilms(){
axios.get(this.URL + "film", this.getParams)
.then(response => {
this.films = response.data;
})
.catch(error => {
console.log(error);
});
},
addFilm(film){
console.log(film);
axios.post(this.URL + "film", film, this.postParams)
.then(() => {
this.getFilms();
this.closeModal();
})
.catch(error => {
console.log(error);
});
},
deleteFilm(id){
axios.delete(this.URL + `film/${id}`, this.delParams)
.then(() =>{
this.getFilms();
})
},
editFilm(film){
axios.put(this.URL + `film/${film.id}`, film, this.putParams)
.then(() =>{
const index = this.films.findIndex((s) => s.id === film.id);
if (index !== -1) {
this.films[index] = { ...film };
}
this.closeModal();
this.getFilms();
})
this.closeModal();
},
openModalForAdd(status, film = null) {
if (status === "create") {
this.film = new Film();
this.film.status = "create";
} else if (status === "edit" && film) {
this.film = { ...film };
this.film.status = "edit";
}
this.open = this.film.genreIds ? [...this.film.genreIds] : []; // Создаём новый массив, чтобы избежать проблем с ссылками
this.loadSelectedGenres();
document.getElementById("openModalForAdd").style.display = "block";
},
closeModalForAdd() {
document.getElementById("openModalForAdd").style.display = "none";
this.open = [...this.selectedGenres];
this.selectedGenres = [];
this.film = new Film();
},
openModal(status, film = null) {
if (status === "create") {
this.film = new Film();
this.film.status = "create";
} else if (status === "edit" && film) {
this.film = { ...film };
this.film.status = "edit";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
getGenres(){
axios.get(this.URL + "genre", this.getParams)
.then(response => {
this.genres = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
saveSelectedGenres() {
this.open = [...this.selectedGenres];
},
loadSelectedGenres() {
this.selectedGenres = [...this.open];
},
addFilmGenre(id, list) {
axios
.post(this.URL + `film/add_genres/${id}`, list, this.postParams)
.then(() => {
this.closeModalForAdd();
this.getFilms();
this.open = [...this.selectedGenres];
})
.catch((error) => {
console.log(error);
});
}
}
}
</script>
<template>
<div class="container mt-4">
<h1 class="text-center text-danger mb-4">Фильмы</h1>
<button class="btn btn-success mr-2" @click="openModal('create')">Добавить</button>
<table class="table text-light">
<thead>
<tr>
<th>Название</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="flm in films" :key="flm.id">
<td>{{ flm.name }}</td>
<td>
<td>
<button class="btn btn-warning mr-2" @click="openModal('edit', flm)">Изменить</button>
</td>
<td>
<button class="btn btn-danger" @click="deleteFilm(flm.id)">Удалить</button>
</td>
<td>
<button class="btn btn-success mr-2" @click="openModalForAdd('edit', flm);">Добавить жанры</button>
</td>
</td>
</tr>
</tbody>
</table>
</div>
<!--Форма для создания фильмов-->
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Фильм</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">Название:</label>
<input type="text" class="form-control" id="name" name="name" v-model="film.name">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="film.status === 'create'" @click="addFilm(film)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editFilm(film)">Сохранить</button>
</div>
</div>
</div>
</div>
<!--Форма для привязки фильма и жанра -->
<div class="modal" tabindex="-1" id="openModalForAdd">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Добавление жанров</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">Название:</label>
<input readonly type="text" class="form-control" id="name" name="name" v-model="film.name">
</div>
<div class="form-group">
<label for="name">Выберите жанры для добавления:</label>
<ul class="list-group">
<li class="list-group-item" v-for="genre in genres" :key="genre.id">
<div class="form-check">
<input class="form-check-input" type="checkbox" v-model="selectedGenres" :value="genre.id" v-bind:checked="open.includes(genre.id)" id="genreCheck{{ genre.id }}">
<label class="form-check-label" for="genreCheck{{ genre.id }}">{{ genre.name }}</label>
</div>
</li>
</ul>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModalForAdd()">Закрыть</button>
<button type="button" class="btn btn-primary" @click="addFilmGenre(film.id, selectedGenres)">Добавить</button>
</div>
</div>
</div>
</div>
</template>

View File

@ -0,0 +1,164 @@
<script>
import 'axios';
import axios from 'axios';
import Genre from "../models/Genre";
export default {
created() {
this.getGenres();
},
mounted() {
const addModal = document.getElementById('editModal');
addModal.addEventListener('shown.bs.modal', function () {
})
},
data() {
return {
genres: [],
URL: "http://localhost:8080/api/1.0/",
genre: new Genre(),
editedGenre: new Genre(),
postParams: {
method:"POST",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
putParams: {
method:"PUT",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
},
},
delParams: {
method:"DELETE",
headers:{
"Content-Type":"application/json",
"Authorization": "Bearer " + localStorage.getItem("token"),
}
},
getParams: {
method:"GET",
headers:{
"Authorization": "Bearer " + localStorage.getItem("token"),
}
}
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
methods: {
getGenres(){
axios.get(this.URL + "genre", this.getParams)
.then(response => {
this.genres = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addGenre(genre) {
console.log(genre);
axios
.post(this.URL + "genre", genre, this.postParams)
.then(() => {
this.getGenres();
this.closeModal();
})
.catch((error) => {
console.log(error);
});
},
deleteGenre(id){
axios.delete(this.URL + `genre/${id}`, this.delParams)
.then(() =>{
this.getGenres();
})
},
openModal(status, genre = null) {
if (status === "create") {
this.editedGenre = new Genre();
this.editedGenre.status = "create";
} else if (status === "edit" && genre) {
this.editedGenre = { ...genre };
this.editedGenre.status = "edit";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
editGenre(genre) {
axios.put(this.URL + `genre/${genre.id}`, genre, this.putParams)
.then(() => {
const index = this.genres.findIndex((s) => s.id === genre.id);
if (index !== -1) {
this.genres[index] = { ...genre };
}
this.closeModal();
this.getGenres();
})
.catch((error) => {
console.log(error);
});
}
}
}
</script>
<template>
<div class="container mt-4">
<h1 class="text-center text-danger mb-4">Жанры</h1>
<button class="btn btn-success mr-2" @click="openModal('create')">Добавить</button>
<table class="table text-light">
<thead>
<tr>
<th>Название</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="gen in genres" :key="gen.id">
<td>{{ gen.name }}</td>
<td>
<td>
<button class="btn btn-warning mr-2" @click="openModal('edit', gen)">Изменить</button>
</td>
<td>
<button class="btn btn-danger" @click="deleteGenre(gen.id)">Удалить</button>
</td>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Жанр</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">Название:</label>
<input type="text" class="form-control" id="name" name="name" v-model="editedGenre.name">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="editedGenre.status === 'create'" @click="addGenre(editedGenre)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editGenre(editedGenre)">Сохранить</button>
</div>
</div>
</div>
</div>
</template>

View File

@ -0,0 +1,20 @@
<template>
<footer class="d-flex justify-content-center justify-content-lg-around p-3 bg-success">
<span class="logo text-danger bg-white">VF</span>
<span class="text-white mt-4">более 10 лет только лучшие фильмы</span>
<span class="text-white mt-4">Почта для отзывов и предложений: videofilms@mail.ru</span>
</footer>
</template>
<style scoped>
.logo{
font-size: 64px;
line-height: 76px;
}
footer{
width: 100%;
position: absolute;
bottom: 0;
margin: 0 !important;
}
</style>

View File

@ -0,0 +1,54 @@
<template>
<header>
<nav class="navbar navbar-dark navbar-expand-lg bg-black">
<div class="container-fluid">
<router-link to="/index" class="navbar-brand"><img src="/src/images/name.png" alt="name"></router-link>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Переключатель навигации">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<router-link to="/index" class="nav-link">Главная</router-link>
</li>
<li class="nav-item">
<router-link to="/catalogs/genres" class="nav-link">Жанры</router-link>
</li>
<li class="nav-item">
<router-link to="/catalogs/films" class="nav-link">Фильмы</router-link>
</li>
<li class="nav-item">
<router-link to="/catalogs/collections" class="nav-link">Коллекции</router-link>
</li>
<li class="nav-item">
<router-link to="/report" class="nav-link">Отчет</router-link>
</li>
<li class="nav-item">
<router-link to="/users" class="nav-link">Пользователи</router-link>
</li>
<li class="nav-item">
<router-link to="/login" class="nav-link" @click="logout()">Выход</router-link>
</li>
</ul>
</div>
</div>
</nav>
</header>
</template>
<style scoped>
header{
font-size: 28px;
}
</style>
<script>
export default {
methods: {
logout(){
localStorage.clear();
this.$router.push('/login');
}
}
}
</script>

View File

@ -0,0 +1,62 @@
<script>
export default{
data(){
return{
images: [
{image: "/src/images/banner1.jpg"},
{image: "/src/images/banner2.jpg"},
{image: "/src/images/banner3.jpg"}
],
count: 0,
banner: "/src/images/banner1.jpg"
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
methods: {
change(){
this.banner = this.images[this.count].image;
if(this.count == this.images.length-1) this.count = 0;
else this.count++;
setTimeout(this.change, 3000);
}
},
mounted(){
this.change();
}
}
</script>
<template>
<section class="first_page">
<div id="banner">
<img :src = banner />
</div>
<div class="mock"></div>
</section>
</template>
<style scoped>
.first_page{
background-image: url(/src/images/Фон1.jpg);
min-height: 100vh;
width: 100%;
background-size: cover;
background-position: center;
}
#banner {
margin: 15px;
display: flex;
align-items: center;
flex-direction: column;
min-height: 700px;
}
#banner img {
border-radius: 5px;
height: 700px;
min-width: 300px;
}
</style>

View File

@ -0,0 +1,96 @@
<script>
export default {
methods: {
getUserInfo () {
if (localStorage.getItem("token")) {
this.loginButton.classList.add("visually-hidden");
this.logoutButton.classList.remove("visually-hidden");
this.userSpan.innerText = localStorage.getItem("user");
} else {
this.loginButton.classList.remove("visually-hidden");
this.logoutButton.classList.add("visually-hidden");
this.userSpan.innerText = "";
localStorage.removeItem("user");
}
},
async login (login, password) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({login: login, password: password}),
};
const response = await fetch(this.hostURL + "/jwt/login", requestParams);
const result = await response.text();
if (response.status === 200) {
localStorage.setItem("token", result);
localStorage.setItem("user", login);
this.$router.push("/index");
} else {
localStorage.removeItem("token");
localStorage.removeItem("user");
alert(result);
}
},
loginForm () {
this.login(this.loginInput.value, this.passwordInput.value).then(() => {
this.loginInput.value = "";
this.passwordInput.value = "";
this.getUserInfo();
});
},
logoutForm () {
localStorage.removeItem("token");
localStorage.removeItem("user");
this.getUserInfo();
},
toSignup() {
this.$router.push("/signup");
}
},
data() {
return {
hostURL: "http://localhost:8080",
loginInput: undefined,
passwordInput: undefined,
loginButton: undefined,
logoutButton: undefined,
userSpan: undefined
}
},
mounted() {
this.loginInput = document.getElementById("login");
this.passwordInput = document.getElementById("password");
this.loginButton = document.getElementById("loginBtn");
this.logoutButton = document.getElementById("logoutBtn");
this.userSpan = document.getElementById("user");
this.getUserInfo();
}
}
</script>
<template>
<form id="loginForm" onsubmit="return false">
<div class="row mt-3">
<div class="col-sm-4">
<label for="login" class="form-label visually-hidden">Login</label>
<input type="text" class="form-control" id="login" required placeholder="Логин">
</div>
<div class="col-sm-4 mt-3 mt-sm-0">
<label for="password" class="form-label visually-hidden">Password</label>
<input type="password" class="form-control" id="password" required placeholder="Пароль">
</div>
<div class="d-grid col-sm-2 mx-auto mt-3 mt-sm-0">
<button id="loginBtn" type="submit" class="btn btn-success" @click.prevent="loginForm">Войти</button>
<button id="logoutBtn" type="button" class="btn btn-danger visually-hidden" @click.prevent="logoutForm">Выйти</button>
</div>
<div class="d-grid col-sm-2 mx-auto mt-3 mt-sm-0">
<span id="user" class="align-middle"></span>
</div>
</div>
</form>
<div class="mt-3">
<button class="btn btn-secondary" @click.prevent="toSignup">Регистрация</button>
</div>
</template>

View File

@ -0,0 +1,87 @@
<script>
import 'axios';
import axios from "axios";
import Film from "../models/Film";
import Genre from "../models/Genre";
export default{
created() {
this.getFilms();
this.getGenres();
},
data() {
return{
films: [],
URL: "http://localhost:8080/api/1.0/",
genres: [],
genreId: undefined,
getParams: {
method:"GET",
headers:{
"Authorization": "Bearer " + localStorage.getItem("token"),
}
}
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
methods: {
getFilms(){
axios.get(this.URL + "film", this.getParams)
.then(response => {
this.films = response.data;
})
.catch(error => {
console.log(error);
});
},
getGenres(){
axios.get(this.URL + "genre", this.getParams)
.then(response => {
this.genres = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
filter() {
let genreId = document.getElementById('genreFilterSelect').value;
axios.get(this.URL + `genre/film/${genreId}`, this.getParams)
.then(response => {
this.films = response.data;
})
.catch(error => {
console.log(error);
});
}
}
}
</script>
<template>
<div class="mt-4">
<h2 class="text-danger">Выберите жанр для отчета</h2>
<select class="form-select" id="genreFilterSelect" required>
<option v-for="genre in this.genres" :value="genre.id">{{ genre.name }}</option>
</select>
<button class="btn btn-success" type="button" id="report-button"
@click.prevent="filter">Сформировать</button>
<button class="btn btn-danger" type="button" id="report-button"
@click.prevent="getFilms">Очистить</button>
<table class="table text-light">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
<tr v-for="flm in films" :key="flm.id">
<td>{{ flm.name }}</td>
</tr>
</tbody>
</table>
</div>
</template>

View File

@ -0,0 +1,52 @@
<script>
import 'axios';
import axios from "axios";
export default {
data() {
return {
data: []
}
},
methods: {
async createUser() {
const response = await axios.post("http://localhost:8080/signup", this.toJSON(this.data));
if (response.data !== "error") {
this.$router.push("/login");
} else {
document.getElementById('error').value = "Error!";
}
},
toJSON(data) {
const jsonObj = {};
const fields = Object.getOwnPropertyNames(data);
for (const field of fields) {
if (data[field] === undefined) {
continue;
}
jsonObj[field] = data[field];
}
return jsonObj;
}
}
}
</script>
<template>
<div class="mb-3">
<input type="text" name="login" class="form-control"
placeholder="Логин" required autofocus maxlength="64" v-model="data.login"/>
</div>
<div class="mb-3">
<input type="password" name="password" class="form-control"
placeholder="Пароль" required minlength="6" maxlength="64" v-model="data.password"/>
</div>
<div class="mb-3">
<input type="password" name="passwordConfirm" class="form-control"
placeholder="Пароль (подтверждение)" required minlength="6" maxlength="64" v-model="data.passwordConfirm"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed" @click.prevent="createUser">Создать</button>
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
</div>
<p id="error"></p>
</template>

View File

@ -0,0 +1,64 @@
<script>
import axios from 'axios'
import User from '../models/User.js';
export default {
data() {
return {
users: [],
URL: "http://localhost:8080/api/1.0/",
ifAdmin: Boolean
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
created() {
this.ifAdmin = localStorage.getItem("user") === "admin";
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
axios.get(this.URL + "user", requestParams)
.then(response => {
this.users = response.data;
})
.catch(error => {
console.log(error);
});
}
}
</script>
<template>
<div class="container mt-4" v-if="ifAdmin">
<table class="table text-light">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Логин</th>
<th scope="col">Роль</th>
</tr>
</thead>
<tbody>
<tr v-for="(user, index) in users" :key="index">
<td>{{ user.id }}</td>
<td>{{ user.login }}</td>
<td>{{ user.role }}</td>
</tr>
</tbody>
</table>
</div>
<div v-else>
<h2 class="text-danger">Эта страница доступна только администраторам!</h2>
</div>
</template>

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

View File

@ -0,0 +1,31 @@
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Index from './components/Index.vue'
import CatalogGenres from './components/CatalogGenres.vue'
import CatalogFilms from './components/CatalogFilms.vue'
import CatalogCollections from './components/CatalogCollections.vue'
import Report from './components/Report.vue'
import Users from './components/Users.vue'
import Login from './components/Login.vue'
import Signup from './components/Signup.vue'
const routes = [
{ path: '/', redirect: '/index' },
{ path: '/index', component: Index},
{ path: '/catalogs/genres', component: CatalogGenres},
{ path: '/catalogs/films', component: CatalogFilms},
{ path: '/catalogs/collections', component: CatalogCollections},
{ path: '/report', component: Report},
{ path: '/users', component: Users},
{ path: '/login', component: Login},
{ path: '/signup', component: Signup}
]
const router = createRouter({
history: createWebHistory(),
linkActiveClass: 'active',
routes
})
createApp(App).use(router).mount('#app')

View File

@ -0,0 +1,7 @@
export default class Collection {
constructor(data) {
this.id = data?.id;
this.name = data?.name;
this.filmIds = data?.filmIds;
}
}

View File

@ -0,0 +1,7 @@
export default class Film {
constructor(data) {
this.id = data?.id;
this.name = data?.name;
this.genreIds = data?.genreIds;
}
}

View File

@ -0,0 +1,6 @@
export default class Genre {
constructor(data) {
this.id = data?.id;
this.name = data?.name;
}
}

View File

@ -0,0 +1,7 @@
export default class User {
constructor(data) {
this.id = data?.id;
this.login = data?.login;
this.role = data?.role;
}
}

View File

@ -0,0 +1,15 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})

View File

@ -12,8 +12,26 @@ repositories {
mavenCentral() mavenCentral()
} }
jar {
enabled = false
}
dependencies { dependencies {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.auth0:java-jwt:4.4.0'
implementation 'org.hibernate.validator:hibernate-validator'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.springframework.boot:spring-boot-starter-validation'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
} }

BIN
data.mv.db Normal file

Binary file not shown.

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.lab1.DataBase.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.lab1.DataBase.model.Collection;
public interface ICollectionRepository extends JpaRepository<Collection, Long> {
}

View File

@ -0,0 +1,9 @@
package ru.ulstu.is.lab1.DataBase.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.lab1.DataBase.model.Film;
import java.util.List;
public interface IFilmRepository extends JpaRepository<Film, Long> {
}

View File

@ -0,0 +1,14 @@
package ru.ulstu.is.lab1.DataBase.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulstu.is.lab1.DataBase.model.Film;
import ru.ulstu.is.lab1.DataBase.model.Genre;
import java.util.List;
public interface IGenreRepository extends JpaRepository<Genre, Long> {
@Query("SELECT DISTINCT f FROM Film f where :filmsGenres MEMBER OF f.genres")
List<Film> findFilmsOnGenre(@Param("filmsGenres") Genre genre);
}

View File

@ -0,0 +1,8 @@
package ru.ulstu.is.lab1.DataBase.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.lab1.DataBase.model.User;
public interface IUserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,28 @@
package ru.ulstu.is.lab1.DataBase.configuration;
import ru.ulstu.is.lab1.DataBase.configuration.jwt.JwtFilter;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenAPI30Configuration {
public static final String API_PREFIX = "/api/1.0";
@Bean
public OpenAPI customizeOpenAPI() {
final String securitySchemeName = JwtFilter.TOKEN_BEGIN_STR;
return new OpenAPI()
.addSecurityItem(new SecurityRequirement()
.addList(securitySchemeName))
.components(new Components()
.addSecuritySchemes(securitySchemeName, new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}

View File

@ -0,0 +1,14 @@
package ru.ulstu.is.lab1.DataBase.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,74 @@
package ru.ulstu.is.lab1.DataBase.configuration;
import ru.ulstu.is.lab1.DataBase.configuration.jwt.JwtFilter;
import ru.ulstu.is.lab1.DataBase.controller.UserController;
import ru.ulstu.is.lab1.DataBase.controller.UserSignupController;
import ru.ulstu.is.lab1.DataBase.model.UserRole;
import ru.ulstu.is.lab1.DataBase.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
private final UserService userService;
private final JwtFilter jwtFilter;
public SecurityConfiguration(UserService userService) {
this.userService = userService;
this.jwtFilter = new JwtFilter(userService);
createAdminOnStartup();
}
private void createAdminOnStartup() {
final String admin = "admin";
if (userService.findByLogin(admin) == null) {
log.info("Admin user successfully created");
userService.createUser(admin, admin, admin, UserRole.ADMIN);
}
}
@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, UserController.URL_LOGIN).permitAll()
.antMatchers(HttpMethod.POST, UserSignupController.URL_LOGIN).permitAll()
.anyRequest()
.authenticated()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.anonymous();
}
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userService);
}
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/**/*.{js,html,css,png,jpg}")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/webjars/**")
.antMatchers("/swagger-resources/**")
.antMatchers("/v3/api-docs/**")
.antMatchers("/h2-console/**");
}
}

View File

@ -0,0 +1,28 @@
package ru.ulstu.is.lab1.DataBase.configuration;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
class WebConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
registry.addViewController("/notFound").setViewName("forward:/");
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -0,0 +1,10 @@
package ru.ulstu.is.lab1.DataBase.configuration.jwt;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

@ -0,0 +1,67 @@
package ru.ulstu.is.lab1.DataBase.configuration.jwt;
import com.fasterxml.jackson.databind.ObjectMapper;
import ru.ulstu.is.lab1.DataBase.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JwtFilter extends GenericFilterBean {
private static final String AUTHORIZATION = "Authorization";
public static final String TOKEN_BEGIN_STR = "Bearer ";
private final UserService userService;
public JwtFilter(UserService userService) {
this.userService = userService;
}
private String getTokenFromRequest(HttpServletRequest request) {
String bearer = request.getHeader(AUTHORIZATION);
if (StringUtils.hasText(bearer) && bearer.startsWith(TOKEN_BEGIN_STR)) {
return bearer.substring(TOKEN_BEGIN_STR.length());
}
return null;
}
private void raiseException(ServletResponse response, int status, String message) throws IOException {
if (response instanceof final HttpServletResponse httpResponse) {
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
httpResponse.setStatus(status);
final byte[] body = new ObjectMapper().writeValueAsBytes(message);
response.getOutputStream().write(body);
}
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request instanceof final HttpServletRequest httpRequest) {
final String token = getTokenFromRequest(httpRequest);
if (StringUtils.hasText(token)) {
try {
final UserDetails user = userService.loadUserByToken(token);
final UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (JwtException e) {
raiseException(response, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
return;
} catch (Exception e) {
e.printStackTrace();
raiseException(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
String.format("Internal error: %s", e.getMessage()));
return;
}
}
}
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,27 @@
package ru.ulstu.is.lab1.DataBase.configuration.jwt;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "jwt", ignoreInvalidFields = true)
public class JwtProperties {
private String devToken = "";
private Boolean isDev = true;
public String getDevToken() {
return devToken;
}
public void setDevToken(String devToken) {
this.devToken = devToken;
}
public Boolean isDev() {
return isDev;
}
public void setDev(Boolean dev) {
isDev = dev;
}
}

View File

@ -0,0 +1,99 @@
package ru.ulstu.is.lab1.DataBase.configuration.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;
@Component
public class JwtProvider {
private final static Logger LOG = LoggerFactory.getLogger(JwtProvider.class);
private final static byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
private final static String ISSUER = "auth0";
private final Algorithm algorithm;
private final JWTVerifier verifier;
public JwtProvider(JwtProperties jwtProperties) {
if (!jwtProperties.isDev()) {
LOG.info("Generate new JWT key for prod");
try {
final MessageDigest salt = MessageDigest.getInstance("SHA-256");
salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
LOG.info("Use generated JWT key for prod \n{}", bytesToHex(salt.digest()));
algorithm = Algorithm.HMAC256(bytesToHex(salt.digest()));
} catch (NoSuchAlgorithmException e) {
throw new JwtException(e);
}
} else {
LOG.info("Use default JWT key for dev \n{}", jwtProperties.getDevToken());
algorithm = Algorithm.HMAC256(jwtProperties.getDevToken());
}
verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
}
private static String bytesToHex(byte[] bytes) {
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}
public String generateToken(String login) {
final Date issueDate = Date.from(LocalDate.now()
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
final Date expireDate = Date.from(LocalDate.now()
.plusDays(15)
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
return JWT.create()
.withIssuer(ISSUER)
.withIssuedAt(issueDate)
.withExpiresAt(expireDate)
.withSubject(login)
.sign(algorithm);
}
private DecodedJWT validateToken(String token) {
try {
return verifier.verify(token);
} catch (JWTVerificationException e) {
throw new JwtException(String.format("Token verification error: %s", e.getMessage()));
}
}
public boolean isTokenValid(String token) {
if (!StringUtils.hasText(token)) {
return false;
}
try {
validateToken(token);
return true;
} catch (JwtException e) {
LOG.error(e.getMessage());
return false;
}
}
public Optional<String> getLoginFromToken(String token) {
try {
return Optional.ofNullable(validateToken(token).getSubject());
} catch (JwtException e) {
LOG.error(e.getMessage());
return Optional.empty();
}
}
}

View File

@ -0,0 +1,57 @@
package ru.ulstu.is.lab1.DataBase.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.lab1.DataBase.configuration.OpenAPI30Configuration;
import ru.ulstu.is.lab1.DataBase.service.CollectionService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/collection")
public class CollectionController {
private final CollectionService collectionService;
public CollectionController(CollectionService collectionService) {
this.collectionService = collectionService;
}
@GetMapping("/{id}")
public CollectionDTO getCollection(@PathVariable Long id) {
return new CollectionDTO(collectionService.findCollection(id));
}
@GetMapping
public List<CollectionDTO> getCollection() {
return collectionService.findAllCollections().stream().map(CollectionDTO::new).toList();
}
@PostMapping
public CollectionDTO createCollection(@RequestBody @Valid CollectionDTO collectionDTO) {
return new CollectionDTO(collectionService.addCollection(collectionDTO.getName()));
}
@PutMapping("/{id}")
public CollectionDTO updateCollection(@PathVariable Long id, @RequestBody @Valid CollectionDTO collectionDTO) {
return new CollectionDTO(collectionService.updateCollection(id, collectionDTO.getName()));
}
@DeleteMapping("/{id}")
public CollectionDTO deleteCollection(@PathVariable Long id) {
return new CollectionDTO(collectionService.deleteCollection(id));
}
@DeleteMapping
public void deleteAllCollections(){
collectionService.deleteAllCollections();
}
@PostMapping("/add_film/{id}")
public CollectionDTO addFilm(@PathVariable Long id, @RequestBody @Valid Long film_id) {
return new CollectionDTO(collectionService.addFilm(id, film_id));
}
@DeleteMapping("/del_film/{id}")
public CollectionDTO delFilm(@PathVariable Long id, @RequestParam Long film_id) {
return new CollectionDTO(collectionService.deleteFilm(id, film_id));
}
}

View File

@ -0,0 +1,32 @@
package ru.ulstu.is.lab1.DataBase.controller;
import ru.ulstu.is.lab1.DataBase.model.Collection;
import ru.ulstu.is.lab1.DataBase.model.Film;
import java.util.List;
public class CollectionDTO {
private Long id;
private String name;
private List<Long> filmIds;
public CollectionDTO() {
}
public CollectionDTO(Collection collection){
this.id = collection.getId();
this.name = collection.getName();
if(collection.getFilms() != null) {
this.filmIds = collection.getFilms().stream().map(Film::getId).toList();
}
}
public Long getId(){
return id;
}
public String getName(){
return name;
}
public List<Long> getFilmIds(){
return filmIds;
}
public void setId(long id){ this.id = id; }
public void setName(String name){ this.name = name; }
}

View File

@ -0,0 +1,53 @@
package ru.ulstu.is.lab1.DataBase.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.lab1.DataBase.configuration.OpenAPI30Configuration;
import ru.ulstu.is.lab1.DataBase.service.FilmService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/film")
public class FilmController {
private final FilmService filmService;
public FilmController(FilmService filmService) {
this.filmService = filmService;
}
@GetMapping("/{id}")
public FilmDTO getFilm(@PathVariable Long id) {
return new FilmDTO(filmService.findFilm(id));
}
@GetMapping
public List<FilmDTO> getFilm() {
return filmService.findAllFilms().stream().map(FilmDTO::new).toList();
}
@PostMapping
public FilmDTO createFilm(@RequestBody @Valid FilmDTO filmDTO) {
return new FilmDTO(filmService.addFilm(filmDTO.getName()));
}
@PutMapping("/{id}")
public FilmDTO updateFilm(@PathVariable Long id, @RequestBody @Valid FilmDTO filmDTO) {
return new FilmDTO(filmService.updateFilm(id, filmDTO.getName()));
}
@DeleteMapping("/{id}")
public FilmDTO deleteFilm(@PathVariable Long id) {
return new FilmDTO(filmService.deleteFilm(id));
}
@DeleteMapping
public void deleteAllFilms(){
filmService.deleteAllFilms();
}
@PostMapping("/add_genres/{id}")
public FilmDTO addGenres(@PathVariable Long id, @RequestBody @Valid List<Long> genreIds) {
return new FilmDTO(filmService.addGenres(id, genreIds));
}
}

View File

@ -0,0 +1,32 @@
package ru.ulstu.is.lab1.DataBase.controller;
import ru.ulstu.is.lab1.DataBase.model.Film;
import ru.ulstu.is.lab1.DataBase.model.Genre;
import java.util.List;
public class FilmDTO {
private Long id;
private String name;
private List<Long> genreIds;
public FilmDTO() {
}
public FilmDTO(Film film){
this.id = film.getId();
this.name = film.getName();
if(film.getGenres() != null) {
this.genreIds = film.getGenres().stream().map(Genre::getId).toList();
}
}
public Long getId(){
return id;
}
public String getName(){
return name;
}
public List<Long> getGenreIds(){
return genreIds;
}
public void setId(long id){ this.id = id; }
public void setName(String name){ this.name = name; }
}

View File

@ -0,0 +1,56 @@
package ru.ulstu.is.lab1.DataBase.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.lab1.DataBase.configuration.OpenAPI30Configuration;
import ru.ulstu.is.lab1.DataBase.service.GenreService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/genre")
public class GenreController {
private final GenreService genreService;
public GenreController(GenreService genreService) {
this.genreService = genreService;
}
@GetMapping("/{id}")
public GenreDTO getGenre(@PathVariable Long id) {
return new GenreDTO(genreService.findGenre(id));
}
@GetMapping
public List<GenreDTO> getGenre() {
return genreService.findAllGenres().stream().map(GenreDTO::new).toList();
}
@PostMapping
public GenreDTO createGenre(@RequestBody @Valid GenreDTO genreDTO) {
return new GenreDTO(genreService.addGenre(genreDTO.getName()));
}
@PutMapping("/{id}")
public GenreDTO updateGenre(@PathVariable Long id, @RequestBody @Valid GenreDTO genreDTO) {
return new GenreDTO(genreService.updateGenre(id, genreDTO.getName()));
}
@DeleteMapping("/{id}")
public GenreDTO deleteGenre(@PathVariable Long id) {
return new GenreDTO(genreService.deleteGenre(id));
}
@DeleteMapping
public void deleteAllGenres(){
genreService.deleteAllGenres();
}
@GetMapping("/film/{id}")
public List<FilmDTO> findFilmOnGenre(@PathVariable Long id){
return genreService.findFilmOnGenre(id)
.stream()
.map(FilmDTO::new)
.toList();
}
}

View File

@ -0,0 +1,24 @@
package ru.ulstu.is.lab1.DataBase.controller;
import ru.ulstu.is.lab1.DataBase.model.Genre;
public class GenreDTO {
private Long id;
private String name;
public GenreDTO() {
}
public GenreDTO(Genre genre){
this.id = genre.getId();
this.name = genre.getName();
}
public Long getId(){
return id;
}
public String getName(){
return name;
}
public void setId(long id){ this.id = id; }
public void setName(String name){
this.name = name;
}
}

View File

@ -0,0 +1,32 @@
package ru.ulstu.is.lab1.DataBase.controller;
import ru.ulstu.is.lab1.DataBase.configuration.OpenAPI30Configuration;
import ru.ulstu.is.lab1.DataBase.model.User;
import ru.ulstu.is.lab1.DataBase.model.UserRole;
import ru.ulstu.is.lab1.DataBase.service.UserService;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
@RestController
public class UserController {
public static final String URL_LOGIN = "/jwt/login";
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping(OpenAPI30Configuration.API_PREFIX + "/user")
@Secured({UserRole.AsString.ADMIN})
public List<User> getUsers() {
return userService.findAllUsers();
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid UserDTO userDTO) {
return userService.loginAndGetToken(userDTO);
}
}

View File

@ -0,0 +1,23 @@
package ru.ulstu.is.lab1.DataBase.controller;
import ru.ulstu.is.lab1.DataBase.model.User;
import javax.validation.constraints.NotEmpty;
public class UserDTO {
@NotEmpty
private String login;
@NotEmpty
private String password;
public UserDTO() {}
UserDTO(User user) {
login = user.getLogin();
password = user.getPassword();
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
}

View File

@ -0,0 +1,31 @@
package ru.ulstu.is.lab1.DataBase.controller;
import ru.ulstu.is.lab1.DataBase.model.User;
import ru.ulstu.is.lab1.DataBase.service.UserService;
import ru.ulstu.is.lab1.util.validation.ValidationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@Controller
@RestController
public class UserSignupController {
public static final String URL_LOGIN = "/signup";
private final UserService userService;
public UserSignupController(UserService userService) {
this.userService = userService;
}
@PostMapping(URL_LOGIN)
public String signup(@RequestBody @Valid UserSignupDTO userSignupDTO) {
try {
final User user = userService.createUser(
userSignupDTO.getLogin(), userSignupDTO.getPassword(), userSignupDTO.getPasswordConfirm());
return user.getLogin();
} catch (ValidationException e) {
return "error";
}
}
}

View File

@ -0,0 +1,34 @@
package ru.ulstu.is.lab1.DataBase.controller;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class UserSignupDTO {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,89 @@
package ru.ulstu.is.lab1.DataBase.model;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
public class Collection {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotBlank(message = "Name can't be null")
private String name;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name="collections_films",
joinColumns = @JoinColumn(name="collection_id"),
inverseJoinColumns = @JoinColumn(name="film_id")
)
private List<Film> films;
public Collection() {
}
public Collection(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addFilm(Film film) {
if (films == null){
films = new ArrayList<>();
}
if (!this.films.contains(film)) {
this.films.add(film);
film.addCollection(this);
}
}
public void removeFilm(Film film){
if(films != null){
films.remove(film);
film.removeCollection(this);
}
}
public List<Film> getFilms() {
return films;
}
public void setFilms(List<Film> films) {
this.films = films;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Collection collection = (Collection) o;
return Objects.equals(id, collection.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Collection{" +
"id=" + id +
", name='" + name + '\'' +
"films:" + (films == null ? "[]" : films.toString()) +
'}';
}
}

View File

@ -0,0 +1,114 @@
package ru.ulstu.is.lab1.DataBase.model;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.ArrayList;
import java.util.Objects;
@Entity
public class Film {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotBlank(message = "Name can't be null")
private String name;
@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
@JoinTable(name="films_genres",
joinColumns = @JoinColumn(name="film_id"),
inverseJoinColumns = @JoinColumn(name="genre_id")
)
private List<Genre> genres;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "films")
private List<Collection> collections;
public Film() {
}
public Film(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addGenre(Genre genre) {
if (genres == null){
genres = new ArrayList<>();
}
if (!this.genres.contains(genre))
this.genres.add(genre);
}
public void removeGenre(Genre genre){
if(genres != null){
genres.remove(genre);
}
}
public void removeGenres(){
genres = new ArrayList<>();
}
public void addCollection(Collection collection) {
if(this.collections==null)
collections=new ArrayList<>();
if (!this.genres.contains(collection))
this.collections.add(collection);
}
public void removeCollection(Collection collection){
if(collections != null){
collections.remove(collection);
}
}
public List<Genre> getGenres() {
return genres;
}
public void setGenres(List<Genre> genres) {
this.genres = genres;
}
public List<Collection> getCollections() {
return collections;
}
public void setCollections(List<Collection> collections) {
this.collections = collections;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Film film = (Film) o;
return Objects.equals(id, film.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Film{" +
"id=" + id +
", name='" + name + '\'' +
"genres:" + (genres == null ? "[]" : genres.toString()) +
'}';
}
}

View File

@ -0,0 +1,54 @@
package ru.ulstu.is.lab1.DataBase.model;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Objects;
@Entity
public class Genre {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotBlank(message = "Name can't be null")
private String name;
public Genre() {
}
public Genre(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Genre genre = (Genre) o;
return Objects.equals(id, genre.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Genre{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

View File

@ -0,0 +1,70 @@
package ru.ulstu.is.lab1.DataBase.model;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 64)
@NotBlank
@Size(min = 3, max = 64)
private String login;
@Column(nullable = false, length = 64)
@NotBlank
@Size(min = 6, max = 64)
private String password;
private UserRole role;
public User() {
}
public User(String login, String password) {
this(login, password, UserRole.USER);
}
public User(String login, String password, UserRole role) {
this.login = login;
this.password = password;
this.role = role;
}
public Long getId() {
return id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
'}';
}
}

View File

@ -0,0 +1,17 @@
package ru.ulstu.is.lab1.DataBase.model;
import org.springframework.security.core.GrantedAuthority;
public enum UserRole implements GrantedAuthority {
ADMIN,
USER;
private static final String PREFIX = "ROLE_";
@Override
public String getAuthority() {
return PREFIX + this.name();
}
public static final class AsString {
public static final String ADMIN = PREFIX + "ADMIN";
public static final String USER = PREFIX + "USER";
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.lab1.DataBase.service;
public class CollectionNotFoundException extends RuntimeException {
public CollectionNotFoundException(Long id) {
super(String.format("Collection with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,100 @@
package ru.ulstu.is.lab1.DataBase.service;
import org.springframework.util.StringUtils;
import ru.ulstu.is.lab1.DataBase.model.Film;
import ru.ulstu.is.lab1.DataBase.model.Collection;
import ru.ulstu.is.lab1.DataBase.Repository.ICollectionRepository;
import ru.ulstu.is.lab1.DataBase.model.Genre;
import ru.ulstu.is.lab1.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Optional;
@Service
public class CollectionService {
private final ICollectionRepository collectionRepository;
private final ValidatorUtil validatorUtil;
private final FilmService filmService;
public CollectionService(ICollectionRepository collectionRepository, ValidatorUtil validatorUtil, FilmService filmService){
this.collectionRepository = collectionRepository;
this.validatorUtil = validatorUtil;
this.filmService = filmService;
}
@Transactional
public Collection addCollection(String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Collection name is null or empty");
}
final Collection collection = new Collection(name);
validatorUtil.validate(collection);
return collectionRepository.save(collection);
}
@Transactional(readOnly = true)
public Collection findCollection(Long id) {
final Optional<Collection> collection = collectionRepository.findById(id);
return collection.orElseThrow(() -> new CollectionNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Collection> findAllCollections() {
return collectionRepository.findAll();
}
@Transactional
public Collection updateCollection(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Collection name is null or empty");
}
final Collection currentCollection = findCollection(id);
currentCollection.setName(name);
validatorUtil.validate(currentCollection);
return collectionRepository.save(currentCollection);
}
@Transactional
public Collection deleteCollection(Long id) {
final Collection currentCollection = findCollection(id);
collectionRepository.delete(currentCollection);
return currentCollection;
}
@Transactional
public void deleteAllCollections() {
collectionRepository.deleteAll();
}
@Transactional
public Collection addFilm(Long collectionId, Long filmId) {
Collection collection = findCollection(collectionId);
if (collection == null) {
throw new EntityNotFoundException(String.format("Collection with id [%s] is not found", collectionId));
}
final Film film = filmService.findFilm(filmId);
if (film == null) {
throw new EntityNotFoundException(String.format("Film with id [%s] is not found", filmId));
}
collection.addFilm(film);
return collectionRepository.save(collection);
}
@Transactional
public Collection deleteFilm(Long collectionId, Long filmId) {
Collection collection = findCollection(collectionId);
if (collection == null) {
throw new EntityNotFoundException(String.format("Collection with id [%s] is not found", collectionId));
}
final Film film = filmService.findFilm(filmId);
if (film == null) {
throw new EntityNotFoundException(String.format("Film with id [%s] is not found", filmId));
}
collection.removeFilm(film);
return collectionRepository.save(collection);
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.lab1.DataBase.service;
public class FilmNotFoundException extends RuntimeException {
public FilmNotFoundException(Long id) {
super(String.format("Film with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,84 @@
package ru.ulstu.is.lab1.DataBase.service;
import ru.ulstu.is.lab1.DataBase.model.Genre;
import ru.ulstu.is.lab1.DataBase.model.Film;
import ru.ulstu.is.lab1.DataBase.Repository.IFilmRepository;
import ru.ulstu.is.lab1.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Optional;
@Service
public class FilmService {
private final IFilmRepository filmRepository;
private final ValidatorUtil validatorUtil;
private final GenreService genreService;
public FilmService(IFilmRepository filmRepository, ValidatorUtil validatorUtil, GenreService genreService){
this.filmRepository = filmRepository;
this.validatorUtil = validatorUtil;
this.genreService = genreService;
}
@Transactional
public Film addFilm(String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Film name is null or empty");
}
final Film film = new Film(name);
validatorUtil.validate(film);
return filmRepository.save(film);
}
@Transactional(readOnly = true)
public Film findFilm(Long id) {
final Optional<Film> film = filmRepository.findById(id);
return film.orElseThrow(() -> new FilmNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Film> findAllFilms() {
return filmRepository.findAll();
}
@Transactional
public Film updateFilm(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Film name is null or empty");
}
final Film currentFilm = findFilm(id);
currentFilm.setName(name);
validatorUtil.validate(currentFilm);
return filmRepository.save(currentFilm);
}
@Transactional
public Film deleteFilm(Long id) {
final Film currentFilm = findFilm(id);
filmRepository.delete(currentFilm);
return currentFilm;
}
@Transactional
public void deleteAllFilms() {
filmRepository.deleteAll();
}
@Transactional
public Film addGenres(Long filmId, List<Long> genreIds) {
Film film = findFilm(filmId);
if (film == null) {
throw new EntityNotFoundException(String.format("Film with id [%s] is not found", filmId));
}
film.removeGenres();
for(Long genreId : genreIds) {
final Genre genre = genreService.findGenre(genreId);
film.addGenre(genre);
}
return filmRepository.save(film);
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.lab1.DataBase.service;
public class GenreNotFoundException extends RuntimeException {
public GenreNotFoundException(Long id) {
super(String.format("Genre with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,70 @@
package ru.ulstu.is.lab1.DataBase.service;
import ru.ulstu.is.lab1.DataBase.model.Film;
import ru.ulstu.is.lab1.DataBase.model.Genre;
import ru.ulstu.is.lab1.DataBase.Repository.IGenreRepository;
import ru.ulstu.is.lab1.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Optional;
@Service
public class GenreService {
private final IGenreRepository genreRepository;
private final ValidatorUtil validatorUtil;
public GenreService(IGenreRepository genreRepository, ValidatorUtil validatorUtil){
this.genreRepository = genreRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Genre addGenre(String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Genre name is null or empty");
}
final Genre genre = new Genre(name);
validatorUtil.validate(genre);
return genreRepository.save(genre);
}
@Transactional(readOnly = true)
public Genre findGenre(Long id) {
final Optional<Genre> genre = genreRepository.findById(id);
return genre.orElseThrow(() -> new GenreNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Genre> findAllGenres() {
return genreRepository.findAll();
}
@Transactional
public Genre updateGenre(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Genre name is null or empty");
}
final Genre currentGenre = findGenre(id);
currentGenre.setName(name);
validatorUtil.validate(currentGenre);
return genreRepository.save(currentGenre);
}
@Transactional
public Genre deleteGenre(Long id) {
final Genre currentGenre = findGenre(id);
genreRepository.delete(currentGenre);
return currentGenre;
}
@Transactional
public void deleteAllGenres() {
genreRepository.deleteAll();
}
@Transactional
public List<Film> findFilmOnGenre(Long id){
return genreRepository.findFilmsOnGenre(findGenre(id));
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.lab1.DataBase.service;
public class UserExistsException extends RuntimeException {
public UserExistsException(String login) {
super(String.format("User '%s' already exists", login));
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.lab1.DataBase.service;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String login) {
super(String.format("User not found '%s'", login));
}
}

View File

@ -0,0 +1,91 @@
package ru.ulstu.is.lab1.DataBase.service;
import ru.ulstu.is.lab1.DataBase.configuration.jwt.JwtException;
import ru.ulstu.is.lab1.DataBase.configuration.jwt.JwtProvider;
import ru.ulstu.is.lab1.DataBase.controller.UserDTO;
import ru.ulstu.is.lab1.DataBase.model.User;
import ru.ulstu.is.lab1.DataBase.model.UserRole;
import ru.ulstu.is.lab1.DataBase.service.UserExistsException;
import ru.ulstu.is.lab1.DataBase.service.UserNotFoundException;
import ru.ulstu.is.lab1.DataBase.Repository.IUserRepository;
import ru.ulstu.is.lab1.util.validation.ValidationException;
import ru.ulstu.is.lab1.util.validation.ValidatorUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@Service
public class UserService implements UserDetailsService {
private final IUserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final ValidatorUtil validatorUtil;
private final JwtProvider jwtProvider;
public UserService(IUserRepository userRepository,
PasswordEncoder passwordEncoder,
ValidatorUtil validatorUtil,
JwtProvider jwtProvider) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.validatorUtil = validatorUtil;
this.jwtProvider = jwtProvider;
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
public List<User> findAllUsers() {
return userRepository.findAll();
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public User createUser(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new UserExistsException(login);
}
final User user = new User(login, passwordEncoder.encode(password), role);
validatorUtil.validate(user);
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
return userRepository.save(user);
}
public String loginAndGetToken(UserDTO userDTO) {
final User user = findByLogin(userDTO.getLogin());
if (user == null) {
throw new UserNotFoundException(userDTO.getLogin());
}
if (!passwordEncoder.matches(userDTO.getPassword(), user.getPassword())) {
throw new UserNotFoundException(user.getLogin());
}
return jwtProvider.generateToken(user.getLogin());
}
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
if (!jwtProvider.isTokenValid(token)) {
throw new JwtException("Bad token");
}
final String userLogin = jwtProvider.getLoginFromToken(token)
.orElseThrow(() -> new JwtException("Token is not contain Login"));
return loadUserByUsername(userLogin);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
}
}

View File

@ -2,8 +2,6 @@ package ru.ulstu.is.lab1;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication @SpringBootApplication
@ -13,8 +11,4 @@ public class Lab1 {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(Lab1.class, args); SpringApplication.run(Lab1.class, args);
} }
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
} }

View File

@ -0,0 +1,43 @@
package ru.ulstu.is.lab1.util.error;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import ru.ulstu.is.lab1.DataBase.service.GenreNotFoundException;
import ru.ulstu.is.lab1.DataBase.service.FilmNotFoundException;
import ru.ulstu.is.lab1.DataBase.service.CollectionNotFoundException;
import ru.ulstu.is.lab1.util.validation.ValidationException;
import java.util.stream.Collectors;
@ControllerAdvice
public class AdviceController {
@ExceptionHandler({
GenreNotFoundException.class,
FilmNotFoundException.class,
CollectionNotFoundException.class,
ValidationException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
final ValidationException validationException = new ValidationException(
e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toSet()));
return handleException(validationException);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -0,0 +1,12 @@
package ru.ulstu.is.lab1.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException{
public ValidationException(String message) {
super(message);
}
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
}

View File

@ -0,0 +1,30 @@
package ru.ulstu.is.lab1.util.validation;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class ValidatorUtil{
private final Validator validator;
public ValidatorUtil() {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
this.validator = factory.getValidator();
}
}
public <T> void validate(T object) {
final Set<ConstraintViolation<T>> errors = validator.validate(object);
if (!errors.isEmpty()) {
throw new ValidationException(errors.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toSet()));
}
}
}

View File

@ -0,0 +1,13 @@
spring.main.banner-mode=off
server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false
jwt.dev-token=my-secret-jwt
jwt.dev=true

View File

@ -0,0 +1,80 @@
package ru.ulstu.is.lab1;
import ru.ulstu.is.lab1.DataBase.model.Film;
import ru.ulstu.is.lab1.DataBase.model.Genre;
import ru.ulstu.is.lab1.DataBase.service.FilmService;
import ru.ulstu.is.lab1.DataBase.model.Collection;
import ru.ulstu.is.lab1.DataBase.service.CollectionService;
import javax.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.lab1.DataBase.service.GenreService;
import java.util.List;
@SpringBootTest
public class JpaCollectionTests {
/*private static final Logger log = LoggerFactory.getLogger(JpaFilmTests.class);
@Autowired
private CollectionService collectionService;
@Autowired
private FilmService filmService;
@Test
void testCollectionsCreate(){
collectionService.deleteAllCollections();
filmService.deleteAllFilms();
final Film film1 = filmService.addFilm("Джокер");
final Film film2 = filmService.addFilm("Учитель на замену");
Collection collection1 = collectionService.addCollection("Грустное");
collection1 = collectionService.addFilm(collection1.getId(), film1.getId());
collection1 = collectionService.addFilm(collection1.getId(), film2.getId());
Collection collection2 = collectionService.addCollection("Об антигерое");
collection2 = collectionService.addFilm(collection2.getId(), film1.getId());
log.info("testCreateCollection " + collection1.toString());
log.info("testCreateCollection " + collection2.toString());
Assertions.assertNotNull(collection1.getId());
Assertions.assertNotNull(collection2.getId());
}
@Test
void testCollectionRead() {
collectionService.deleteAllCollections();
filmService.deleteAllFilms();
final Film film = filmService.addFilm("Астрал");
Collection collection = collectionService.addCollection("Пугающее");
collection = collectionService.addFilm(collection.getId(), film.getId());
log.info("testCollectionRead[0]: " + collection.toString());
final Collection findCollection = collectionService.findCollection(collection.getId());
log.info("testCollectionRead[1]: " + findCollection.toString());
Assertions.assertEquals(collection, findCollection);
}
@Test
void testAddFilms(){
collectionService.deleteAllCollections();
filmService.deleteAllFilms();
final Film film1 = filmService.addFilm("Начало");
final Film film2 = filmService.addFilm("Пункт назначения");
final Film film3 = filmService.addFilm("День сурка");
Collection collection = collectionService.addCollection("Избранное");
collection = collectionService.addFilm(collection.getId(), film1.getId());
collection = collectionService.addFilm(collection.getId(), film2.getId());
collection = collectionService.addFilm(collection.getId(), film3.getId());
log.info("testAddFilms[0]: " + collection.toString());
Assertions.assertEquals(collection.getFilms().size(), 3);
}
@Test
void testCollectionReadNotFound() {
collectionService.deleteAllCollections();
Assertions.assertThrows(EntityNotFoundException.class, () -> collectionService.findCollection(-1L));
}
@Test
void testCollectionsReadAllEmpty() {
collectionService.deleteAllCollections();
final List<Collection> collections = collectionService.findAllCollections();
log.info("testCollectionReadAllEmpty: " + collections.toString());
Assertions.assertEquals(collections.size(), 0);
}*/
}

View File

@ -0,0 +1,96 @@
package ru.ulstu.is.lab1;
import ru.ulstu.is.lab1.DataBase.model.Genre;
import ru.ulstu.is.lab1.DataBase.service.GenreService;
import ru.ulstu.is.lab1.DataBase.model.Film;
import ru.ulstu.is.lab1.DataBase.service.FilmService;
import javax.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.math.BigInteger;
import java.util.List;
@SpringBootTest
public class JpaFilmTests {
/*private static final Logger log = LoggerFactory.getLogger(JpaFilmTests.class);
@Autowired
private FilmService filmService;
@Autowired
private GenreService genreService;
@Test
void testFilmsCreate(){
filmService.deleteAllFilms();
genreService.deleteAllGenres();
final Genre genre1 = genreService.addGenre("Фантастика");
final Genre genre2 = genreService.addGenre("Комедия");
Film film1 = filmService.addFilm("Сапожник");
film1 = filmService.addGenre(film1.getId(), genre1.getId());
film1 = filmService.addGenre(film1.getId(), genre2.getId());
Film film2 = filmService.addFilm("Маска");
film2 = filmService.addGenre(film2.getId(), genre1.getId());
log.info("testCreateFilm " + film1.toString());
log.info("testCreateFilm " + film2.toString());
Assertions.assertNotNull(film1.getId());
Assertions.assertNotNull(film2.getId());
}
@Test
void testFilmRead() {
filmService.deleteAllFilms();
genreService.deleteAllGenres();
final Genre genre = genreService.addGenre("Ужасы");
Film film = filmService.addFilm("Оно");
film = filmService.addGenre(film.getId(), genre.getId());
log.info("testFilmRead[0]: " + film.toString());
final Film findFilm = filmService.findFilm(film.getId());
log.info("testFilmRead[1]: " + findFilm.toString());
Assertions.assertEquals(film, findFilm);
}
@Test
void testAddGenres(){
filmService.deleteAllFilms();
genreService.deleteAllGenres();
final Genre genre1 = genreService.addGenre("Драма");
final Genre genre2 = genreService.addGenre("Триллер");
final Genre genre3 = genreService.addGenre("Боевик");
Film film = filmService.addFilm("Брат");
film = filmService.addGenre(film.getId(), genre1.getId());
film = filmService.addGenre(film.getId(), genre2.getId());
film = filmService.addGenre(film.getId(), genre3.getId());
log.info("testAddGenres[0]: " + film.toString());
Assertions.assertEquals(film.getGenres().size(), 3);
}
@Test
void testFilmReadNotFound() {
filmService.deleteAllFilms();
Assertions.assertThrows(EntityNotFoundException.class, () -> filmService.findFilm(-1L));
}
@Test
void testFilmsReadAllEmpty() {
filmService.deleteAllFilms();
final List<Film> films = filmService.findAllFilms();
log.info("testFilmReadAllEmpty: " + films.toString());
Assertions.assertEquals(films.size(), 0);
}
@Test
void testSelect() {
filmService.deleteAllFilms();
genreService.deleteAllGenres();
final Genre genre1 = genreService.addGenre("Драма");
final Genre genre2 = genreService.addGenre("Триллер");
final Genre genre3 = genreService.addGenre("Боевик");
Film film = filmService.addFilm("Брат");
Film film2 = filmService.addFilm("Маска");
film = filmService.addGenre(film.getId(), genre1.getId());
film = filmService.addGenre(film.getId(), genre2.getId());
film = filmService.addGenre(film.getId(), genre3.getId());
film2 = filmService.addGenre(film2.getId(), genre1.getId());
List<Film> list = filmService.findFilmOnGenre(genre1);
log.info("findFilmOnGenre: " + list.toString());
Assertions.assertEquals(list.size(), 2);
}*/
}

View File

@ -0,0 +1,61 @@
package ru.ulstu.is.lab1;
import ru.ulstu.is.lab1.DataBase.model.Genre;
import ru.ulstu.is.lab1.DataBase.service.GenreService;
import javax.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class JpaGenreTests {
/*private static final Logger log = LoggerFactory.getLogger(JpaGenreTests.class);
@Autowired
private GenreService genreService;
@Test
void testGenresCreate(){
genreService.deleteAllGenres();
final Genre genre1 = genreService.addGenre("Фантастика");
final Genre genre2 = genreService.addGenre("Комедия");
log.info("testCreateGenre " + genre1.toString());
log.info("testCreateGenre " + genre2.toString());
Assertions.assertNotNull(genre1.getId());
Assertions.assertNotNull(genre2.getId());
}
@Test
void testGenreRead() {
genreService.deleteAllGenres();
final Genre genre = genreService.addGenre("Ужасы");
log.info("testGenreRead[0]: " + genre.toString());
final Genre findGenre = genreService.findGenre(genre.getId());
log.info("testGenreRead[1]: " + findGenre.toString());
Assertions.assertEquals(genre, findGenre);
}
@Test
void testGenreReadNotFound() {
genreService.deleteAllGenres();
Assertions.assertThrows(EntityNotFoundException.class, () -> genreService.findGenre(-1L));
}
@Test
void testGenreReadAll() {
genreService.deleteAllGenres();
genreService.addGenre("Драма");
genreService.addGenre("Триллер");
final List<Genre> genres = genreService.findAllGenres();
log.info("testGenreReadAll: " + genres.toString());
Assertions.assertEquals(genres.size(), 2);
genreService.deleteAllGenres();
}
@Test
void testGenreReadAllEmpty() {
genreService.deleteAllGenres();
final List<Genre> genres = genreService.findAllGenres();
log.info("testGenreReadAllEmpty: " + genres.toString());
Assertions.assertEquals(genres.size(), 0);
}*/
}

View File

@ -1,13 +0,0 @@
package ru.ulstu.is.lab1;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Lab1ApplicationTests {
@Test
void contextLoads() {
}
}

View File

@ -0,0 +1,6 @@
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop