Lab6: JWT server-side is ready. It's frontend turn
This commit is contained in:
parent
c1a2e77e4d
commit
75f4b6a178
@ -6,6 +6,7 @@
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
|
||||
<link rel="stylesheet" href="https://unpkg.com/chota@latest">
|
||||
<script src="https://code.jquery.com/jquery-3.7.0.slim.min.js" integrity="sha256-tG5mcZUtJsZvyKAxYLVXrmjKBVLd6VpVccqz/r4ypFE=" crossorigin="anonymous"></script>
|
||||
<title>Социальная сеть</title>
|
||||
</head>
|
||||
<body class="container">
|
||||
|
@ -1,44 +1,66 @@
|
||||
<template>
|
||||
<div class="nav row">
|
||||
<div class="nav-left col-10">
|
||||
<router-link to="/customers" class="button primary clear">Профили</router-link>
|
||||
<router-link to="/posts" class="button primary clear">Посты</router-link>
|
||||
<router-link to="/customers" v-bind:class="'button primary ' + this.$route.path.startsWith('/customers')? 'clear' : ''">Профили</router-link>
|
||||
<router-link to="/feed" v-bind:class="'button primary ' + this.$route.path.startsWith('/feed')? 'clear' : ''">Посты</router-link>
|
||||
<router-link v-if="role === 'ADMIN'" to="/admin" v-bind:class="'button primary ' + this.$route.path.startsWith('/admin')? 'clear' : ''">Администрирование</router-link>
|
||||
</div>
|
||||
<div class="nav-right col-2">
|
||||
<select class="form-select" style="font-size: 16px;" v-model="currentCustomerId">
|
||||
<option value="-1" selected class="button dark outline" :on-click="updateCurrentCustomer()">Не выбран</option>
|
||||
<option v-for="customer in customers" v-bind:value="customer['id']" class="button dark outline" :on-click="updateCurrentCustomer()">{{ customer['username'] }}</option>
|
||||
</select>
|
||||
<router-link v-if="" to="/login" v-bind:class="'button primary ' + this.$route.path.startsWith('/login')? 'clear' : ''">Войти</router-link>
|
||||
<button v-on:click="logout()" v-bind:class="'button primary ' + this.$route.path.startsWith('/signup')? 'clear' : ''">Выйти</button>
|
||||
</div>
|
||||
</div>
|
||||
<router-view></router-view>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import axios from 'axios'
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
currentCustomerId: -1,
|
||||
customers: []
|
||||
token_value: localStorage.getItem("token"),
|
||||
role: ''
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async updateCurrentCustomer() {
|
||||
history.replaceState(this.currentCustomerId, "");
|
||||
logout() {
|
||||
this.token = null
|
||||
this.$router.push('login')
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
token: {
|
||||
get: function() {
|
||||
return this.token_value
|
||||
},
|
||||
set: function(value) {
|
||||
this.token_value = value
|
||||
localStorage.setItem("token", value)
|
||||
}
|
||||
}
|
||||
},
|
||||
async beforeMount() {
|
||||
setInterval(async () => {
|
||||
const response = await axios.get('http://localhost:8080/api/customer');
|
||||
this.customers = [];
|
||||
response.data.forEach(element => {
|
||||
this.customers.push(element);
|
||||
console.log(element);
|
||||
});
|
||||
}, 500)
|
||||
if (localStorage.getItem("token") === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
},
|
||||
let response = await fetch(
|
||||
"http://localhost:8080/api/1.0/customer/role/" + localStorage.getItem("token"),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": "Bearer " + localStorage.getItem("token")
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
this.role = await response.json()
|
||||
|
||||
const component = this
|
||||
|
||||
document.addEventListener('token_changed', function() {
|
||||
component.token = localStorage.getItem("token")
|
||||
})
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
|
@ -4,15 +4,6 @@
|
||||
<div class="row mb-5">
|
||||
<p class='is-center h2'>Профили</p>
|
||||
</div>
|
||||
<div class="row mb-5">
|
||||
<div class="col"></div>
|
||||
<div class="col-10 is-center">
|
||||
<button class="button primary" data-bs-toggle="modal" data-bs-target="#customerCreate">
|
||||
Добавить нового пользователя
|
||||
</button>
|
||||
</div>
|
||||
<div class="col"></div>
|
||||
</div>
|
||||
|
||||
<p class='h3 is-center row mb-5'>Список профилей</p>
|
||||
<div class="row">
|
||||
@ -20,20 +11,19 @@
|
||||
<div v-for="customer in customers" class="row card mb-3">
|
||||
<div class="row">
|
||||
<div class="col is-left h3">ID: {{ customer['id'] }}</div>
|
||||
<div class="col is-center h3">Никнейм: {{ customer['username'] }}</div>
|
||||
<div class="col is-right h3">Пароль: {{ customer['password'] }}</div>
|
||||
<div class="col is-right h3">Никнейм: {{ customer['username'] }}</div>
|
||||
</div>
|
||||
<p class="row">Комментарии:</p>
|
||||
<div class="row" v-if="!(customer['comments'].length == 0)">
|
||||
<div class="row" v-if="customer['comments'].length !== 0">
|
||||
<div class="col">
|
||||
<div v-for="comment in customer['comments']" class="row is-left card mb-3">
|
||||
<div class="row is-left h4">"{{ comment['content'] }}" - к посту '{{ comment['postTitle'] }}' от пользователя {{ comment['postAuthor'] }}</div>
|
||||
<div class="row is-left h4">"{{ comment['content'] }}" - к посту "{{ comment['postTitle'] }}" от пользователя {{ comment['postAuthor'] }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="row">Нет комментариев</p>
|
||||
<p class="row">Посты: </p>
|
||||
<div class="row" v-if="!(customer['posts'].length == 0)">
|
||||
<div class="row" v-if="customer['posts'].length !== 0">
|
||||
<div class="col">
|
||||
<div v-for="post in customer['posts']" class="row is-left card mb-3">
|
||||
<div class="row is-center h1">{{ post['title'] }}</div>
|
||||
@ -42,128 +32,115 @@
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="row">Нет постов</p>
|
||||
<div class="row" v-if="customer['id'] == currentCustomerId">
|
||||
<button v-on:click="deleteUser(customer['id'])" class="col button dark outline">Удалить</button>
|
||||
<button v-on:click="selectedCustomer = customer; usernameModal=customer['username'];passwordModal=customer['password']" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#customerEdit">Редактировать</button>
|
||||
<div class="row" v-if="currentCustomerId === customer['id']">
|
||||
<button v-on:click="deleteCustomer(customer)" class="button dark outline is-full-width">Удалить</button>
|
||||
<button v-on:click="prepareEditModal(customer)" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#customerEdit">Редактировать</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Modal -->
|
||||
<div class="modal fade" id="customerCreate" tabindex="-1" role="dialog" aria-labelledby="customerCreateLabel" aria-hidden="true">
|
||||
<div class="modal-dialog" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="customerCreateLabel">Создать профиль</h5>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<p>Логин</p>
|
||||
<textarea v-model='usernameModal' id="usernameText" cols="30" rows="1"></textarea>
|
||||
<p>Пароль</p>
|
||||
<textarea v-model='passwordModal' id="passwordText" cols="30" rows="1"></textarea>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button type="button" class="btn btn-primary" v-on:click='createUser'>Сохранить</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal -->
|
||||
<div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true">
|
||||
<div class="modal-dialog" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="customerEditLabel">Редактировать профиль</h5>
|
||||
<div class="modal-content" id="edit-customer-form">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="customerEditLabel">Редактировать профиль</h5>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<p>Логин</p>
|
||||
<textarea name="username" id="usernameTextE" cols="30" rows="1"></textarea>
|
||||
<p>Пароль</p>
|
||||
<textarea name="password" id="passwordTextE" cols="30" rows="1"></textarea>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button v-on:click="editCustomer()" type="button" class="btn btn-primary"> data-bs-dismiss="modal"Изменить</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<p>Логин</p>
|
||||
<textarea v-model='usernameModal' id="usernameText" cols="30" rows="1"></textarea>
|
||||
<p>Пароль</p>
|
||||
<textarea v-model='passwordModal' id="passwordText" cols="30" rows="1"></textarea>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button type="button" class="btn btn-primary" v-on:click='editUser'>Изменить</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import axios from 'axios'
|
||||
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
customers: [],
|
||||
usernameModal: '',
|
||||
passwordModal: '',
|
||||
selectedCustomer: {},
|
||||
currentCustomerId: -1
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async createUser(){
|
||||
let customer = {
|
||||
username: this.usernameModal,
|
||||
password: this.passwordModal
|
||||
};
|
||||
const response = await axios.post('http://localhost:8080/api/customer', customer);
|
||||
this.refreshList();
|
||||
},
|
||||
async deleteUser(id) {
|
||||
const response = await axios.delete('http://localhost:8080/api/customer/' + id);
|
||||
this.refreshList();
|
||||
},
|
||||
async editUser() {
|
||||
let customer = {
|
||||
username: this.usernameModal,
|
||||
password: this.passwordModal
|
||||
};
|
||||
const response = await axios.put('http://localhost:8080/api/customer/' + this.selectedCustomer['id'], customer);
|
||||
this.refreshList();
|
||||
},
|
||||
async refreshList() {
|
||||
this.customers = [];
|
||||
if (this.$route.params.id === "") {
|
||||
const response = await axios.get('http://localhost:8080/api/customer');
|
||||
response.data.forEach(element => {
|
||||
this.customers.push(element);
|
||||
console.log(element);
|
||||
});
|
||||
} else {
|
||||
const response = await axios.get('http://localhost:8080/api/customer/' + this.$route.params.id);
|
||||
this.customers.push(response.data)
|
||||
}
|
||||
},
|
||||
async updateCustomers() {
|
||||
const response = await fetch(
|
||||
"http://localhost:8080/api/1.0/customer",
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": "Bearer " + localStorage.getItem("token")
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
this.customers = await response.json()
|
||||
},
|
||||
async getCurrentCustomer() {
|
||||
const response = await fetch(
|
||||
"http://localhost:8080/api/1.0/customer/me",
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": "Bearer " + localStorage.getItem("token")
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
this.currentCustomerId = (await response.json())['id']
|
||||
},
|
||||
prepareEditModal(customer) {
|
||||
$("#usernameTextE").val(customer['username'])
|
||||
},
|
||||
async deleteCustomer() {
|
||||
await fetch(
|
||||
"http://localhost:8080/api/1.0/customer/" + this.currentCustomerId,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Authorization": "Bearer " + localStorage.getItem("token")
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
localStorage.clear()
|
||||
this.$router.push("login")
|
||||
},
|
||||
async editCustomer() {
|
||||
await fetch(
|
||||
"http://localhost:8080/api/1.0/customer/" + this.currentCustomerId,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": "Bearer " + localStorage.getItem("token")
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username: $("usernameTextE").val(),
|
||||
password: $("passwordTextE").val()
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
await this.updateCustomers()
|
||||
}
|
||||
},
|
||||
async mounted() {
|
||||
this.currentCustomerId = history.state;
|
||||
setInterval(async () => this.currentCustomerId = history.state, 50)
|
||||
if (this.$route.params.id === "") {
|
||||
const response = await axios.get('http://localhost:8080/api/customer');
|
||||
response.data.forEach(element => {
|
||||
this.customers.push(element);
|
||||
console.log(element);
|
||||
});
|
||||
} else {
|
||||
const response = await axios.get('http://localhost:8080/api/customer/' + this.$route.params.id);
|
||||
this.customers.push(response.data)
|
||||
async beforeMount() {
|
||||
if (localStorage.getItem("token") === null) {
|
||||
this.$router.replace("login")
|
||||
}
|
||||
|
||||
},
|
||||
async beforeRouteUpdate(to, from) {
|
||||
this.$route.params.id = to.params.id;
|
||||
this.refreshList();
|
||||
},
|
||||
|
||||
|
||||
await Promise.all([this.updateCustomers(), this.getCurrentCustomer()])
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
|
61
frontend/src/components/Login.vue
Normal file
61
frontend/src/components/Login.vue
Normal file
@ -0,0 +1,61 @@
|
||||
<template>
|
||||
<div class="row">
|
||||
<div class="col"></div>
|
||||
<div class="col-6">
|
||||
<div class="row mb-3">
|
||||
<label>Имя пользователя: <input type="text" id="username" required /></label>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<label>Пароль: <input type="password" id="password" required /></label>
|
||||
</div>
|
||||
<div class="row mb-3 alert alert-danger" v-if="error !== null" role="alert">
|
||||
{{ error }}
|
||||
</div>
|
||||
<div class="row mt-3">
|
||||
<div class="col-4"></div>
|
||||
<button v-on:click="login()" type="button" class="button primary col" id="enter">Войти</button>
|
||||
<div class="col-4"></div>
|
||||
</div>
|
||||
<div class="row mt-5">
|
||||
<router-link to="/login" class="button primary outline">Регистрация</router-link>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col"></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
error: null
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async login() {
|
||||
let response = await fetch(
|
||||
"http://localhost:8080/api/1.0/customer/jwt/login",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
username: $("#username").val(),
|
||||
password: $("#password").val()
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
if (response.statusCode !== 200) {
|
||||
this.error = await response.text()
|
||||
} else {
|
||||
localStorage.setItem("token", await response.text())
|
||||
document.dispatchEvent(new Event("token_changed"))
|
||||
this.$router.push("feed")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
|
||||
</style>
|
66
frontend/src/components/Signup.vue
Normal file
66
frontend/src/components/Signup.vue
Normal file
@ -0,0 +1,66 @@
|
||||
<template>
|
||||
<div class="row">
|
||||
<div class="col"></div>
|
||||
<div class="col-6">
|
||||
<div class="row">
|
||||
<label>Имя пользователя: <input type="text" id="username" required /></label>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label>Пароль: <input v-on:change="check()" type="password" id="password" required /></label>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label>Пароль повторно: <input v-on:change="check()" type="password" id="confirm-password" required /></label>
|
||||
</div>
|
||||
<div class="row mb-3 alert alert-danger" v-if="error !== null" role="alert">
|
||||
{{ error }}
|
||||
</div>
|
||||
<div class="row mt-3">
|
||||
<div class="col-4"></div>
|
||||
<button v-on:click="register()" class="button primary col" id="enter" disabled>Регистрация</button>
|
||||
<div class="col-4"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col"></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
error: null
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
check() {
|
||||
if ($("#password").val() !== $("#confirm-password").val()) {
|
||||
$("#enter").removeAttr("disabled")
|
||||
} else {
|
||||
$("#enter").attr("disabled", "disabled")
|
||||
}
|
||||
},
|
||||
async register() {
|
||||
const response = await fetch(
|
||||
"http://localhost:8080/api/1.0/customer",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
username: $("#username").val(),
|
||||
password: $("#password").val()
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
if (response.statusCode !== 200) {
|
||||
this.error = await response.text()
|
||||
} else {
|
||||
this.$router.push("login")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
|
||||
</style>
|
@ -3,20 +3,24 @@ import App from './App'
|
||||
import { createRouter, createWebHistory } from "vue-router"
|
||||
|
||||
import Customers from './components/Customers'
|
||||
import Posts from './components/Posts'
|
||||
import Feed from './components/Feed'
|
||||
import Login from "@/components/Login.vue";
|
||||
|
||||
const routes = [
|
||||
{
|
||||
path: '/customers/:id?',
|
||||
name: "Customers",
|
||||
component: Customers,
|
||||
props: true
|
||||
component: Customers
|
||||
},
|
||||
{
|
||||
path: '/posts',
|
||||
name: "Posts",
|
||||
component: Posts,
|
||||
props: true
|
||||
path: '/feed',
|
||||
name: "Feed",
|
||||
component: Feed
|
||||
},
|
||||
{
|
||||
path: '/login',
|
||||
name: "Login",
|
||||
component: Login
|
||||
}
|
||||
]
|
||||
|
||||
|
11
src/main/java/np/something/Exceptions/JwtException.java
Normal file
11
src/main/java/np/something/Exceptions/JwtException.java
Normal file
@ -0,0 +1,11 @@
|
||||
package np.something.Exceptions;
|
||||
|
||||
public class JwtException extends RuntimeException {
|
||||
public JwtException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
|
||||
public JwtException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
28
src/main/java/np/something/OpenAPI30Configuration.java
Normal file
28
src/main/java/np/something/OpenAPI30Configuration.java
Normal file
@ -0,0 +1,28 @@
|
||||
package np.something;
|
||||
|
||||
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 np.something.security.JwtFilter;
|
||||
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")));
|
||||
}
|
||||
}
|
@ -1,18 +1,31 @@
|
||||
package np.something;
|
||||
|
||||
import np.something.security.SecurityConfiguration;
|
||||
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
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
public static final String REST_API = "/api";
|
||||
public static final String REST_API = OpenAPI30Configuration.API_PREFIX;
|
||||
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
WebMvcConfigurer.super.addViewControllers(registry);
|
||||
registry.addViewController("login");
|
||||
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
|
||||
|
@ -5,6 +5,7 @@ import np.something.DTO.CustomerDto;
|
||||
import np.something.WebConfiguration;
|
||||
import np.something.model.Customer;
|
||||
import np.something.services.*;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
@ -12,6 +13,7 @@ import java.util.List;
|
||||
@RestController
|
||||
@RequestMapping(WebConfiguration.REST_API + "/customer")
|
||||
public class CustomerController {
|
||||
public static final String URL_LOGIN = "/jwt/login";
|
||||
private final CustomerService customerService;
|
||||
|
||||
public CustomerController(CustomerService customerService) {
|
||||
@ -50,4 +52,31 @@ public class CustomerController {
|
||||
public void deleteAllCustomers(){
|
||||
customerService.deleteAllCustomers();
|
||||
}
|
||||
|
||||
@GetMapping("/find/{username}")
|
||||
public CustomerDto getCustomerByUsername(@PathVariable String username) {
|
||||
return new CustomerDto(customerService.findByUsername(username));
|
||||
}
|
||||
|
||||
@PostMapping(URL_LOGIN)
|
||||
public String login(@RequestBody @Valid CustomerDto customerDto) {
|
||||
return customerService.loginAndGetToken(customerDto);
|
||||
}
|
||||
|
||||
@GetMapping ("/me")
|
||||
CustomerDto getCurrentCustomer(@RequestHeader(HttpHeaders.AUTHORIZATION) String token) {
|
||||
return new CustomerDto(customerService.findByUsername(customerService.loadUserByToken(token).getUsername()));
|
||||
}
|
||||
|
||||
@GetMapping("role/{token}")
|
||||
public String getRoleByToken(@PathVariable String token) {
|
||||
var userDetails = customerService.loadUserByToken(token);
|
||||
Customer customer = customerService.findByUsername(userDetails.getUsername());
|
||||
|
||||
if (customer != null) {
|
||||
return customer.getRole().toString();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
73
src/main/java/np/something/security/JwtFilter.java
Normal file
73
src/main/java/np/something/security/JwtFilter.java
Normal file
@ -0,0 +1,73 @@
|
||||
package np.something.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import np.something.Exceptions.JwtException;
|
||||
import np.something.services.CustomerService;
|
||||
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 CustomerService customerService;
|
||||
|
||||
public JwtFilter(CustomerService customerService) {
|
||||
this.customerService = customerService;
|
||||
}
|
||||
|
||||
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 = customerService.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);
|
||||
}
|
||||
}
|
27
src/main/java/np/something/security/JwtProperties.java
Normal file
27
src/main/java/np/something/security/JwtProperties.java
Normal file
@ -0,0 +1,27 @@
|
||||
package np.something.security;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
108
src/main/java/np/something/security/JwtProvider.java
Normal file
108
src/main/java/np/something/security/JwtProvider.java
Normal file
@ -0,0 +1,108 @@
|
||||
package np.something.security;
|
||||
|
||||
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 np.something.Exceptions.JwtException;
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,5 +1,7 @@
|
||||
package np.something.security;
|
||||
|
||||
import np.something.WebConfiguration;
|
||||
import np.something.controllers.CustomerController;
|
||||
import np.something.model.UserRole;
|
||||
import np.something.mvc.UserSignUp;
|
||||
import np.something.services.CustomerService;
|
||||
@ -13,6 +15,8 @@ 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
|
||||
@ -20,10 +24,13 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
|
||||
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||
private static final String LOGIN_URL = "/login";
|
||||
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
|
||||
private final CustomerService customerService;
|
||||
private final JwtFilter jwtFilter;
|
||||
|
||||
public SecurityConfiguration(CustomerService customerService) {
|
||||
this.customerService = customerService;
|
||||
this.jwtFilter = new JwtFilter(customerService);
|
||||
createAdminOnStartup();
|
||||
}
|
||||
|
||||
@ -35,20 +42,38 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
// @Override
|
||||
// protected void configure(HttpSecurity http) throws Exception {
|
||||
// http.headers().frameOptions().sameOrigin().and()
|
||||
// .cors().and()
|
||||
// .csrf().disable()
|
||||
// .authorizeRequests()
|
||||
// .antMatchers(UserSignUp.SIGNUP_URL).permitAll()
|
||||
// .antMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
|
||||
// .anyRequest().authenticated()
|
||||
// .and()
|
||||
// .formLogin()
|
||||
// .loginPage(LOGIN_URL).permitAll()
|
||||
// .and()
|
||||
// .logout().permitAll();
|
||||
// }
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.headers().frameOptions().sameOrigin().and()
|
||||
.cors().and()
|
||||
log.info("Creating security configuration");
|
||||
http.cors()
|
||||
.and()
|
||||
.csrf().disable()
|
||||
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers(UserSignUp.SIGNUP_URL).permitAll()
|
||||
.antMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.antMatchers("/", SPA_URL_MASK).permitAll()
|
||||
.antMatchers(HttpMethod.POST, WebConfiguration.REST_API + "/customer" + CustomerController.URL_LOGIN).permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage(LOGIN_URL).permitAll()
|
||||
.and()
|
||||
.logout().permitAll();
|
||||
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.anonymous();
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -62,6 +87,8 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
.antMatchers("/css/**")
|
||||
.antMatchers("/js/**")
|
||||
.antMatchers("/templates/**")
|
||||
.antMatchers("/webjars/**");
|
||||
.antMatchers("/webjars/**")
|
||||
.antMatchers("/swagger-resources/**")
|
||||
.antMatchers("/v3/api-docs/**");
|
||||
}
|
||||
}
|
@ -1,10 +1,14 @@
|
||||
package np.something.services;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
|
||||
import np.something.DTO.CustomerDto;
|
||||
import np.something.Exceptions.CustomerNotFoundException;
|
||||
import np.something.Exceptions.JwtException;
|
||||
import np.something.model.Customer;
|
||||
import np.something.model.UserRole;
|
||||
import np.something.repositories.CustomerRepository;
|
||||
import np.something.security.JwtProvider;
|
||||
import np.something.util.validation.ValidatorUtil;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
@ -20,12 +24,14 @@ public class CustomerService implements UserDetailsService {
|
||||
private final CustomerRepository customerRepository;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtProvider jwtProvider;
|
||||
|
||||
public CustomerService(CustomerRepository customerRepository,
|
||||
ValidatorUtil validatorUtil, PasswordEncoder passwordEncoder) {
|
||||
ValidatorUtil validatorUtil, PasswordEncoder passwordEncoder, JwtProvider jwtProvider) {
|
||||
this.customerRepository = customerRepository;
|
||||
this.validatorUtil = validatorUtil;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.jwtProvider = jwtProvider;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@ -86,4 +92,29 @@ public class CustomerService implements UserDetailsService {
|
||||
return new org.springframework.security.core.userdetails.User(
|
||||
customerEntity.getUsername(), customerEntity.getPassword(), Collections.singleton(customerEntity.getRole()));
|
||||
}
|
||||
|
||||
public String loginAndGetToken(CustomerDto customerDto) {
|
||||
try {
|
||||
final Customer customer = findByUsername(customerDto.getUsername());
|
||||
if (customer == null) {
|
||||
throw new Exception("Login not found" + customerDto.getUsername());
|
||||
}
|
||||
if (!passwordEncoder.matches(customerDto.getPassword(), customer.getPassword())) {
|
||||
throw new Exception("User not found" + customer.getUsername());
|
||||
}
|
||||
return jwtProvider.generateToken(customer.getUsername());
|
||||
}
|
||||
catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
@ -48,26 +48,6 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Modal -->
|
||||
<div class="modal fade" id="customerCreate" tabindex="-1" role="dialog" aria-labelledby="customerCreateLabel" aria-hidden="true">
|
||||
<div class="modal-dialog" role="document">
|
||||
<form class="modal-content" th:action="@{/customers/}" method="post">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="customerCreateLabel">Создать профиль</h5>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<p>Логин</p>
|
||||
<textarea name="username" id="usernameTextC" cols="30" rows="1"></textarea>
|
||||
<p>Пароль</p>
|
||||
<textarea name="password" id="passwordTextC" cols="30" rows="1"></textarea>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button type="submit" class="btn btn-primary">Сохранить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal -->
|
||||
<div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true">
|
||||
|
Loading…
Reference in New Issue
Block a user