Ну вроде сделал vue

This commit is contained in:
ArtemEmelyanov 2023-05-25 13:06:28 +04:00
parent a47d810d48
commit 9f399ceea6
31 changed files with 1030 additions and 394 deletions

View File

@ -13,11 +13,22 @@ repositories {
} }
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-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.auth0:java-jwt:4.4.0'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'com.h2database:h2:2.1.210' implementation 'com.h2database:h2:2.1.210'
implementation 'jakarta.validation:jakarta.validation-api:3.0.0' implementation 'jakarta.validation:jakarta.validation-api:3.0.0'
implementation 'org.hibernate.validator:hibernate-validator:7.0.1.Final' implementation 'org.hibernate.validator:hibernate-validator:7.0.1.Final'
implementation 'org.springframework.boot:spring-boot-starter-web' implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
} }

Binary file not shown.

View File

@ -1,16 +1,57 @@
<script>
import Header from "./components/Header.vue"
export default {
components:{Header}
}
</script>
<template> <template>
<Header></Header> <Header :user="userFromServer" :role="roleFromServer"></Header>
<div class="container-fluid"> <main class="main mt-2">
<router-view></router-view> <router-view @login="saveServerData"></router-view>
</div> </main>
</template> </template>
<script>
import Header from './components/Header.vue';
export default{
components:{
Header
},
data() {
return {
tokenFromServer: undefined,
userFromServer: undefined,
roleFromServer: 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()
}
if(e.key === "role")
if(this.roleFromServer !== e.newValue) {
self.storageSecurity()
}
})
},
methods: {
storageSecurity(){
localStorage.clear()
this.$router.push("/login")
this.securityError = true
},
saveServerData(data){
this.tokenFromServer = data.token
this.roleFromServer = data.role
this.userFromServer = data.user
},
},
}
</script>
<style> <style>
</style> </style>

View File

@ -12,6 +12,12 @@
<li class="nav-item"> <li class="nav-item">
<router-link to="/subjects" class="nav-link">Предметы</router-link> <router-link to="/subjects" class="nav-link">Предметы</router-link>
</li> </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> </ul>
</div> </div>
</div> </div>
@ -40,7 +46,11 @@
<script> <script>
export default { export default {
methods: {
logout(){
localStorage.clear();
}
}
} }
</script> </script>

View File

View File

@ -0,0 +1,9 @@
<template>
<div>
<a>Ошибка доступа</a>
</div>
</template>
<script>
</script>
<style>
</style>

View File

@ -0,0 +1,83 @@
<template>
<div>
<div class="login">
<form @submit.prevent class="login__form" action="/">
<div class="form__login">
<input class="login-input form-control"
id="login" v-model="newUser.login"
validate="false"
placeholder="Логин"
type="text"
name="Логин">
</div>
<div class="form__password">
<input class="password-input form-control"
id="password" v-model="newUser.password"
validate="false"
placeholder="Пароль"
type="password"
name="Пароль">
</div>
<div class="login__buttons mt-5">
<button type="submit" class="login__confirm" id="login__confirm" @click="login">Войти</button>
<a class="login__registration" href="registration">Регистрация</a>
</div>
</form>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
mounted(){
},
data(){
return{
newUser: new Object,
token: '',
user: '',
role: '',
}
},
methods: {
async login() {
await this.getRole()
try {
const response = await axios.post(`http://localhost:8080/jwt/login`, this.newUser);
if (response.status === 200) {
localStorage.setItem("token", response.data);
localStorage.setItem("user", this.newUser.login);
this.token = response.data;
this.user = this.newUser.login;
this.$emit('login', {
token: this.token,
user: this.newUser.login,
role: this.role,
});
this.$router.push("/")
} else {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
}
} catch (error) {
console.log(error);
}
},
async getRole(){
await axios.get(`http://localhost:8080/who_am_i?userLogin=${this.newUser.login}`)
.then((response) => {
localStorage.setItem("role", response.data)
this.role = response.data
})
.catch(error => {
console.log(error);
})
}
}
}
</script>
<style>
</style>

View File

@ -0,0 +1,46 @@
<template>
<div class="registration">
<form @submit.prevent="registration" class="registration__form" action="#">
<div class="form__login">
<input class="login-input form-control" v-model="login" id="login" required="" validate="false" placeholder="Логин" type="text" name="Логин">
</div>
<div class="form__password">
<input class="password-input form-control" v-model="password" id="password" required="" validate="false" placeholder="Пароль" type="password" name="Пароль">
</div>
<div class="registration__buttons">
<button class="registration__confirm" id="reg_btn" type="submit">Зарегестрироваться</button><a class="registration__login" href="/login">Уже есть аккаунт</a>
</div>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data(){
return{
login: "",
password: "",
}
},
methods:{
registration(){
// Отправляем данные формы на сервер
let user = {
login: this.login,
password: this.password,
passwordConfirm: this.password
}
axios.post(`http://localhost:8080/sign_up`, user)
.then((response) => {
if (response.status === 200) {
alert(response.data);
}
})
.catch(error => {
console.log(error);
});
this.$router.push('/login');
}
}
}
</script>

View File

@ -0,0 +1,52 @@
<template >
<table class="table table-striped table-bordered table-hover">
<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>
</template>
<script>
import axios from 'axios'
export default {
data(){
return{
users: []
}
},
created(){
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
axios.get(`http://localhost:8080`, requestParams)
.then(response => {
this.users = response.data;
})
.catch(error => {
console.log(error);
});
},
methods:{
}
}
</script>
<style >
</style>

View File

@ -1,13 +1,21 @@
import students from "../pages/students.vue" import students from "../pages/students.vue"
import groups from "../pages/groups.vue" import groups from "../pages/groups.vue"
import subjects from "../pages/subjects.vue" import subjects from "../pages/subjects.vue"
import users from "../pages/users.vue";
import login from "../pages/login.vue";
import registration from "../pages/registration.vue";
import Error from "../pages/Error.vue";
import {createRouter, createWebHistory} from "vue-router" import {createRouter, createWebHistory} from "vue-router"
const routes = [ const routes = [
{path: '/students', component: students}, {path: '/students', component: students, meta: { requiresAuth: true }},
{path: '/groups', component: groups}, {path: '/groups', component: groups, meta: { requiresAuth: true }},
{path: '/subjects', component: subjects}, {path: '/subjects', component: subjects, meta: { requiresAuth: true }},
{ path: "/users", component: users, meta: { requiresAuth: true, requiresAdmin: true }},
{ path: "/login", component: login},
{ path: "/registration", component: registration},
{ path: "/error", component: Error, meta: { requiresAuth: true }},
] ]
const router = createRouter({ const router = createRouter({
@ -16,4 +24,22 @@ const router = createRouter({
routes routes
}) })
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem("token");
if (to.matched.some((route) => route.meta.requiresAuth)) {
if (!isAuthenticated) {
next("/login");
return;
}
}
const isAdmin = localStorage.getItem("role") === "ADMIN";
if (to.matched.some((route) => route.meta.requiresAdmin)) {
if (!isAdmin) {
next("/error");
return;
}
}
next();
});
export default router; export default router;

View File

@ -0,0 +1,28 @@
package ru.IP_LabWorks.IP.University.Configuration;
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;
import ru.IP_LabWorks.IP.University.Configuration.jwt.JwtFilter;
@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.IP_LabWorks.IP.University.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 createPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,84 @@
package ru.IP_LabWorks.IP.University.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import ru.IP_LabWorks.IP.University.Configuration.jwt.JwtFilter;
import ru.IP_LabWorks.IP.University.Contoller.REST.UserController;
import ru.IP_LabWorks.IP.University.Model.Role;
import ru.IP_LabWorks.IP.University.Service.UserService;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(
securedEnabled = true
)
public class SecurityConfiguration {
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 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.addUser(admin, admin, admin, Role.ADMIN);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.requestMatchers("", SPA_URL_MASK).permitAll()
.requestMatchers("/", SPA_URL_MASK).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_SIGN_UP).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_WHO_AM_I).permitAll()
.anyRequest()
.authenticated()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.anonymous();
return http.userDetailsService(userService).build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers(HttpMethod.OPTIONS, "/**")
.requestMatchers("/*.js")
.requestMatchers("/*.html")
.requestMatchers("/*.css")
.requestMatchers("/assets/**")
.requestMatchers("/favicon.ico")
.requestMatchers("/.js", "/.css")
.requestMatchers("/swagger-ui/index.html")
.requestMatchers("/webjars/**")
.requestMatchers("/swagger-resources/**")
.requestMatchers("/v3/api-docs/**")
.requestMatchers("/h2-console/**");
}
}

View File

@ -1,4 +1,4 @@
package ru.IP_LabWorks.IP; package ru.IP_LabWorks.IP.University.Configuration;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.CorsRegistry;

View File

@ -0,0 +1,11 @@
package ru.IP_LabWorks.IP.University.Configuration.jwt;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

@ -0,0 +1,72 @@
package ru.IP_LabWorks.IP.University.Configuration.jwt;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
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 ru.IP_LabWorks.IP.University.Service.UserService;
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.IP_LabWorks.IP.University.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,108 @@
package ru.IP_LabWorks.IP.University.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());
var temp = JWT.create();
var temp2 = temp.withIssuer(ISSUER);
var temp3 = temp2.withIssuedAt(issueDate);
var temp4 = temp3.withExpiresAt(expireDate);
var temp5 = temp4.withSubject(login);
var temp6 = temp5.sign(algorithm);
return temp6;
}
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,52 @@
package ru.IP_LabWorks.IP.University.Contoller.DTO;
import ru.IP_LabWorks.IP.University.Model.Role;
import ru.IP_LabWorks.IP.University.Model.User;
public class UserDTO {
private Long id;
private Role role;
private String login;
private String password;
public UserDTO(){}
public UserDTO(User user) {
this.id=user.getId();
this.login= user.getLogin();
this.password = user.getPassword();
this.role = user.getRole();
}
public Long getId() {
return id;
}
public String getLogin()
{
return login;
}
public String getPassword()
{
return password;
}
public Role getRole() {
return role;
}
public void setId(Long id) {
this.id = id;
}
public void setLogin(String login)
{
this.login = login;
}
public void setPassword(String password)
{
this.password = password;
}
}

View File

@ -0,0 +1,33 @@
package ru.IP_LabWorks.IP.University.Contoller.DTO;
public class UserSignUpDTO {
private String login;
private String password;
private String passwordConfirm;
public String getLogin() {
return login;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public String getPassword() {
return password;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = password;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,66 @@
package ru.IP_LabWorks.IP.University.Contoller.REST;
import jakarta.validation.Valid;
import jakarta.validation.ValidationException;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import ru.IP_LabWorks.IP.University.Contoller.DTO.UserDTO;
import ru.IP_LabWorks.IP.University.Contoller.DTO.UserSignUpDTO;
import ru.IP_LabWorks.IP.University.Model.Role;
import ru.IP_LabWorks.IP.University.Model.User;
import ru.IP_LabWorks.IP.University.Service.UserService;
import java.util.List;
@RestController
public class UserController {
public static final String URL_LOGIN = "/jwt/login";
public static final String URL_SIGN_UP = "/sign_up";
public static final String URL_WHO_AM_I = "/who_am_i";
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid UserDTO userDto) {
return userService.loginAndGetToken(userDto);
}
@GetMapping(URL_WHO_AM_I)
public String role(@RequestParam("userLogin") String userLogin) {
return userService.findByLogin(userLogin).getRole().name();
}
@PostMapping(URL_SIGN_UP)
public String signUp(@RequestBody @Valid UserSignUpDTO userSignupDto) {
try {
final User user = userService.addUser(userSignupDto.getLogin(),
userSignupDto.getPassword(), userSignupDto.getPasswordConfirm(), Role.USER);
return "created " + user.getLogin();
} catch (ValidationException e) {
return e.getMessage();
}
}
@GetMapping("/{id}")
@Secured({Role.AsString.ADMIN})
public UserDTO getUser(@PathVariable Long id) {
return new UserDTO(userService.findUser(id));
}
@GetMapping("/")
@Secured({Role.AsString.ADMIN})
public List<UserDTO> getUsers() {
return userService.findAllUsers().stream()
.map(UserDTO::new)
.toList();
}
@PutMapping("/{id}")
public UserDTO updateUser(@RequestBody @Valid UserDTO userDto){
return new UserDTO(userService.updateUser(userDto));
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}

View File

@ -0,0 +1,20 @@
package ru.IP_LabWorks.IP.University.Model;
import org.springframework.security.core.GrantedAuthority;
public enum Role 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,72 @@
package ru.IP_LabWorks.IP.University.Model;
import jakarta.persistence.*;
import ru.IP_LabWorks.IP.University.Contoller.DTO.UserSignUpDTO;
import java.util.Objects;
@Entity
@Table(name = "user_list")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String login;
private String password;
private Role role;
public User(){
}
public User(UserSignUpDTO userDto){
this.login = userDto.getLogin();
this.password = userDto.getPassword();
this.role = Role.USER;
}
public User(String login, String password, Role 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 Role 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,8 @@
package ru.IP_LabWorks.IP.University.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.IP_LabWorks.IP.University.Model.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,8 @@
package ru.IP_LabWorks.IP.University.Service.NotFoundException;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
super(String.format("User with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,129 @@
package ru.IP_LabWorks.IP.University.Service;
import jakarta.validation.ValidationException;
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 org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.IP_LabWorks.IP.University.Configuration.jwt.JwtException;
import ru.IP_LabWorks.IP.University.Configuration.jwt.JwtProvider;
import ru.IP_LabWorks.IP.University.Contoller.DTO.UserDTO;
import ru.IP_LabWorks.IP.University.Contoller.DTO.UserSignUpDTO;
import ru.IP_LabWorks.IP.University.Model.Role;
import ru.IP_LabWorks.IP.University.Model.User;
import ru.IP_LabWorks.IP.University.Repository.UserRepository;
import ru.IP_LabWorks.IP.University.Service.NotFoundException.UserNotFoundException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtProvider jwtProvider;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
JwtProvider jwtProvider){
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.jwtProvider = jwtProvider;
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
@Transactional
public User addUser(UserSignUpDTO userDto){
final User user = new User(userDto);
userRepository.save(user);
return user;
}
@Transactional
public User addUser(String login, String password,
String passwordConfirm,
Role role){
if (findByLogin(login) != null) {
throw new ValidationException(String.format("User '%s' already exists", login));
}
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
final User user = new User(login,passwordEncoder.encode(password),role);
return userRepository.save(user);
}
@Transactional(readOnly = true)
public User findUser(Long id) {
final Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() -> new UserNotFoundException(id));
}
@Transactional(readOnly = true)
public List<User> findAllUsers() {
return userRepository.findAll();
}
@Transactional
public User updateUser(UserDTO userDto) {
final User currentUser = findUser(userDto.getId());
currentUser.setLogin(userDto.getLogin());
currentUser.setPassword(userDto.getPassword());
return userRepository.save(currentUser);
}
@Transactional
public User updateUser(Long id,String login, String password) {
if (!StringUtils.hasText(login) || !StringUtils.hasText(password)) {
throw new IllegalArgumentException("User name, login or password is null or empty");
}
final User currentUser = findUser(id);
currentUser.setLogin(login);
currentUser.setPassword(password);
return userRepository.save(currentUser);
}
@Transactional
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
@Transactional
public void deleteAllUsers() {
userRepository.deleteAll();
}
@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()));
}
public String loginAndGetToken(UserDTO userDto) {
final User user = findByLogin(userDto.getLogin());
if (user == null) {
}
if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
}
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);
}
}

View File

@ -9,3 +9,6 @@ spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true spring.h2.console.enabled=true
spring.h2.console.settings.trace=false spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false spring.h2.console.settings.web-allow-others=false
jwt.dev-token=my-secret-jwt
jwt.dev=true
jwt.secret = my-secret-jwt

View File

@ -1,78 +0,0 @@
package ru.IP_LabWorks.IP;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.IP_LabWorks.IP.University.Model.Group;
import ru.IP_LabWorks.IP.University.Model.Student;
import ru.IP_LabWorks.IP.University.Service.GroupService;
import ru.IP_LabWorks.IP.University.Service.StudentService;
import java.time.LocalDate;
import java.util.List;
@SpringBootTest
public class GroupServiceTests {
@Autowired
private GroupService groupService;
@Autowired
private StudentService studentService;
@Test
void TestAddGroup(){
groupService.deleteAllGroups();
final Group group = groupService.addGroup("ПИбд-21");
Assertions.assertNotNull(group.getId());
}
@Test
void TestFindGroup(){
groupService.deleteAllGroups();
final Group group = groupService.addGroup("ПИбд-21");
final Group findGroup = groupService.findGroup(group.getId());
Assertions.assertEquals(group, findGroup);
}
@Test
void TestFindAllGroup(){
groupService.deleteAllGroups();
final Group group1 = groupService.addGroup("ПИбд-21");
final Group group2 = groupService.addGroup("ПИбд-22");
final List<Group> groups = groupService.findAllGroups();
Assertions.assertEquals(groups.size(), 2);
}
@Test
void TestUpdateGroup(){
groupService.deleteAllGroups();
Group group = groupService.addGroup("ПИбд-21");
group = groupService.updateGroup(group.getId(), "ПИбд-22");
Assertions.assertEquals(group.getName(), "ПИбд-22");
}
@Test
void TestDeleteGroup(){
groupService.deleteAllGroups();
Group group = groupService.addGroup("ПИбд-21");
groupService.deleteGroup(group.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> {
groupService.findGroup(group.getId());
});
}
@Test
void TestFindStudentsInGroup(){
studentService.deleteAllStudent();
groupService.deleteAllGroups();
Student student1 = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
Student student2 = studentService.addStudent("Емельянов Артём Сергеевич", LocalDate.of(2003,7,26));
Group group = groupService.addGroup("ПИбд-21");
groupService.addStudentToGroup(group.getId(), student1.getId());
groupService.addStudentToGroup(group.getId(), student2.getId());
final List<Student> students = groupService.findStudentsInGroup(group.getId());
Assertions.assertEquals(students.size(), 2);
}
}

View File

@ -1,113 +0,0 @@
package ru.IP_LabWorks.IP;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.IP_LabWorks.IP.TypeCalculator.service.TypeService;
@SpringBootTest
class IpApplicationTests {
@Autowired
TypeService Service;
@Test
void contextLoads() {
}
@Test
void testIntPlus() {
final String res = (String) Service.Method1( "100", "10", "int");
Assertions.assertEquals("110", res);
}
@Test
void testIntMinus() {
final String res = (String)Service.Method2( "100", "10", "int");
Assertions.assertEquals("90", res);
}
@Test
void testIntMultiply() {
final String res = (String)Service.Method3( "100", "10", "int");
Assertions.assertEquals("1000", res);
}
@Test
void testIntDivision() {
final String res = (String)Service.Method4( "100", "10", "int");
Assertions.assertEquals("10", res);
}
@Test
void testStringPlus() {
final String res = (String)Service.Method1( "abc", "dfe", "str");
Assertions.assertEquals("abcdfe", res);
}
@Test
void testStringtoUpper() {
final String res = (String)Service.Method2( "abc", "dfe", "str");
Assertions.assertEquals("ABCDFE", res);
}
@Test
void testStringtoLower() {
final String res = (String)Service.Method3( "abc", "dfe", "str");
Assertions.assertEquals("abcdfe", res);
}
@Test
void testStringStrange() {
final String res = (String)Service.Method4( "abc", "dfe", "str");
Assertions.assertEquals("abcDFE", res);
}
@Test
void testDoublePlus() {
final String res = (String)Service.Method1( "1.01", "2.76", "double");
Assertions.assertEquals("3.7699999999999996", res);
}
@Test
void testDoubleMinus() {
final String res = (String)Service.Method2( "1.01", "2.76", "double");
Assertions.assertEquals("-1.7499999999999998", res);
}
@Test
void testDoubleMyltiply() {
final String res = (String)Service.Method3( "1.01", "2.76", "double");
Assertions.assertEquals("2.7876", res);
}
@Test
void testDoubleDivision() {
final String res = (String)Service.Method4( "1.01", "2.76", "double");
Assertions.assertEquals("0.36594202898550726", res);
}
@Test
void testArrayPlus(){
final String res = (String)Service.Method1( "1,2,3", "1,2,3", "array");
Assertions.assertEquals("[2, 4, 6]", res);
}
@Test
void testArrayMinus(){
final String res = (String)Service.Method2( "1,2,3", "1,2,3", "array");
Assertions.assertEquals("[0, 0, 0]", res);
}
@Test
void testArrayMult(){
final String res = (String)Service.Method3( "1,2,3", "1,2,3", "array");
Assertions.assertEquals("[1, 4, 9]", res);
}
@Test
void testArrayDiv(){
final String res = (String)Service.Method4( "1,2,3", "1,2,3", "array");
Assertions.assertEquals("[1, 1, 1]", res);
}
}

View File

@ -1,79 +0,0 @@
package ru.IP_LabWorks.IP;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.IP_LabWorks.IP.University.Model.Group;
import ru.IP_LabWorks.IP.University.Model.Student;
import ru.IP_LabWorks.IP.University.Service.GroupService;
import ru.IP_LabWorks.IP.University.Service.StudentService;
import java.time.LocalDate;
import java.util.List;
@SpringBootTest
public class StudentServiceTests {
@Autowired
private StudentService studentService;
@Autowired
private GroupService groupService;
@Test
void TestAddStudent(){
studentService.deleteAllStudent();
final Student student = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
Assertions.assertNotNull(student.getId());
}
@Test
void TestFindStudent(){
studentService.deleteAllStudent();
final Student student = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
final Student findStudent = studentService.findStudent(student.getId());
Assertions.assertEquals(student, findStudent);
}
@Test
void TestFindAllStudent(){
studentService.deleteAllStudent();
final Student student1 = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
final Student student2 = studentService.addStudent("Емельянов Артём Сергеевич", LocalDate.of(2003,7,26));
final List<Student> students = studentService.findAllStudents();
Assertions.assertEquals(students.size(), 2);
}
@Test
void TestUpdateStudent(){
studentService.deleteAllStudent();
Student student = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
student = studentService.updateStudent(student.getId(), "Емельянов Артём Сергеевич", LocalDate.of(2003,7,26));
Assertions.assertEquals(student.getName(), "Емельянов Артём Сергеевич");
}
@Test
void TestDeleteStudent(){
studentService.deleteAllStudent();
Student student = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
studentService.deleteStudent(student.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> {
studentService.findStudent(student.getId());
});
}
@Test
void TestAddStudentToGroup(){
studentService.deleteAllStudent();
groupService.deleteAllGroups();
Student student = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
Group group = groupService.addGroup("ПИбд-21");
studentService.AddStudentToGroup(student.getId(), group.getId());
Assertions.assertEquals(group,studentService.findStudent(student.getId()).getGroup());
}
}

View File

@ -1,107 +0,0 @@
package ru.IP_LabWorks.IP;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.IP_LabWorks.IP.University.Model.Group;
import ru.IP_LabWorks.IP.University.Model.Subject;
import ru.IP_LabWorks.IP.University.Service.GroupService;
import ru.IP_LabWorks.IP.University.Service.SubjectService;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest
public class SubjectServiceTests {
@Autowired
private SubjectService subjectService;
@Autowired
private GroupService groupService;
@Test
void TestAddSubject(){
subjectService.deleteAllSubjects();
final Subject subject = subjectService.addSubject("Философия");
Assertions.assertNotNull(subject.getId());
}
@Test
void TestFindSubject(){
subjectService.deleteAllSubjects();
final Subject subject = subjectService.addSubject("Философия");
final Subject findSubject = subjectService.findSubject(subject.getId());
assertEquals(subject, findSubject);
}
@Test
void TestFindAllSubject(){
subjectService.deleteAllSubjects();
final Subject subject1 = subjectService.addSubject("Философия");
final Subject subject2 = subjectService.addSubject("Математика");
final List<Subject> subjects = subjectService.findAllSubjects();
assertEquals(subjects.size(), 2);
}
@Test
void TestUpdateSubject(){
subjectService.deleteAllSubjects();
Subject subject = subjectService.addSubject("Философия");
subject = subjectService.updateSubject(subject.getId(), "Математика");
assertEquals(subject.getName(), "Математика");
}
@Test
void TestDeleteSubject(){
subjectService.deleteAllSubjects();
Subject subject = subjectService.addSubject("Математика");
subjectService.deleteSubject(subject.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> {
subjectService.findSubject(subject.getId());
});
}
@Test
void testAddAndFindGroupsInSubject() {
subjectService.deleteAllSubjects();
groupService.deleteAllGroups();
Subject subject = subjectService.addSubject("Math");
Group group1 = groupService.addGroup("PIBD-21");
Group group2 = groupService.addGroup("PIBD-22");
subjectService.addGroupToSubject(subject.getId(), group1.getId());
subjectService.addGroupToSubject(subject.getId(), group2.getId());
List<Group> groups = subjectService.findGroupsBySubject(subject.getId());
System.out.println(groups);
assertEquals(2, groups.size());
}
@Test
void testRemoveGroupFromSubject() {
subjectService.deleteAllSubjects();
groupService.deleteAllGroups();
Subject subject = subjectService.addSubject("Math");
Group group1 = groupService.addGroup("PIBD-21");
Group group2 = groupService.addGroup("PIBD-22");
subjectService.addGroupToSubject(subject.getId(), group1.getId());
subjectService.addGroupToSubject(subject.getId(), group2.getId());
List<Group> groupsBeforeRemove = subjectService.findGroupsBySubject(subject.getId());
assertEquals(2, groupsBeforeRemove.size());
subjectService.removeGroupFromSubject(subject.getId(), group1.getId());
List<Group> groupsAfterRemove = subjectService.findGroupsBySubject(subject.getId());
assertEquals(1, groupsAfterRemove.size());
assertTrue(groupsAfterRemove.contains(group2));
}
}