Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
Yura1204 authored Dec 10, 2023
0 parents commit 1925cf9
Show file tree
Hide file tree
Showing 34 changed files with 1,015 additions and 0 deletions.
37 changes: 37 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.11'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}


group = 'com.example'
sourceCompatibility = '11'

configurations {
compileOnly {
extendsFrom annotationProcessor
}
}

repositories {
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// implementation 'com.h2database:h2:2.1.214'
implementation group: 'org.postgresql', name: 'postgresql', version: '42.6.0'
implementation "javax.persistence:javax.persistence-api:2.2"
implementation "org.liquibase:liquibase-core"
implementation "org.springframework.boot:spring-boot-starter-security"
}

tasks.named('test') {
useJUnitPlatform()
}
2 changes: 2 additions & 0 deletions build_and_push.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
./gradlew clean build
docker build . -t jersonmade/demo:1.0.0
Binary file added gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
5 changes: 5 additions & 0 deletions gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
13 changes: 13 additions & 0 deletions src/main/java/com/example/demo/DemoApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

}
38 changes: 38 additions & 0 deletions src/main/java/com/example/demo/UserDetailsServiceImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.example.demo;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private static UserRepository userRepository;

public UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("Пользователь не найден");
}

Set<GrantedAuthority> authorities = new HashSet<>();
authorities.add(new SimpleGrantedAuthority(user.getRole().name()));

return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
authorities);
}
}

63 changes: 63 additions & 0 deletions src/main/java/com/example/demo/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.example.demo.config;

import com.example.demo.entity.Role;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private UserDetailsService userDetailsService;

public SecurityConfig(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}



@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/admin/**","/api/timerange/admin/all","/api/schedules/admin/all").hasRole("ADMIN")
.antMatchers("/api/**").hasAnyRole("ADMIN", "USER")
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.defaultSuccessUrl("/") // Устанавливаем стартовую страницу после успешной аутентификации
.and()
.logout()
.logoutSuccessUrl("/login");// Устанавливаем стартовую страницу после выхода пользователя



}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}

}
58 changes: 58 additions & 0 deletions src/main/java/com/example/demo/controller/ScheduleController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.example.demo.controller;

import com.example.demo.dto.ScheduleDTO;
import com.example.demo.dto.UserDTO;
import com.example.demo.entity.Schedule;
import com.example.demo.entity.User;
import com.example.demo.service.ScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.nio.file.AccessDeniedException;
import java.util.List;

@RestController
@RequestMapping("/api/schedules")
public class ScheduleController {
@Autowired
private ScheduleService scheduleService;

@GetMapping("admin/all")
public List<Schedule> allSchedules() {
return scheduleService.getAllSchedule();
}

// @GetMapping("/my")
// public ResponseEntity<ScheduleDTO> viewScheduleById(@PathVariable Long id) {
// // Ищем расписание по id
// Schedule schedule = scheduleService.getScheduleById(id);
//
// // Если расписание не найдено, возвращаем ответ с кодом 404 Not Found
// if (schedule == null) {
// return ResponseEntity.notFound().build();
// }
//
// // Если расписание найдено, возвращаем его данные с кодом 200 OK
// return ResponseEntity.ok(ScheduleDTO.toModel(schedule));
// }


@GetMapping("/{id}")
public Schedule getScheduleById(@PathVariable Long id) {
return scheduleService.getScheduleById(id);
}

@PostMapping()
public void addSchedule(Schedule schedule) {
scheduleService.save(schedule);
}

@DeleteMapping("/{id}")
public Long deleteSchedule(@PathVariable Long id) {
scheduleService.delete(id);
return id;
}
}
32 changes: 32 additions & 0 deletions src/main/java/com/example/demo/controller/TimeRangeController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.example.demo.controller;

import com.example.demo.entity.TimeRange;
import com.example.demo.entity.User;
import com.example.demo.service.TimeRangeService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("api/timerange/")
public class TimeRangeController {
private TimeRangeService timeRangeService;

@Autowired
public TimeRangeController(TimeRangeService timeRangeService) {
this.timeRangeService = timeRangeService;
}

@GetMapping("admin/all")
public List<TimeRange> getAllTimeRange() {
return timeRangeService.getAllTimeRanges();
}

@PostMapping
public void addTimeRange(@RequestBody TimeRange timeRange) {
timeRangeService.save(timeRange);
}

}
105 changes: 105 additions & 0 deletions src/main/java/com/example/demo/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package com.example.demo.controller;

import com.example.demo.dto.UserDTO;
import com.example.demo.dto.UserTimeRangeDTO;
import com.example.demo.entity.Schedule;
import com.example.demo.entity.TimeRange;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.nio.file.AccessDeniedException;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/")
public class UserController {
private final UserService userService;

@Autowired
public UserController(UserService userService) {
this.userService = userService;
}

// Вывод всех пользователей
@GetMapping("admin/users")
public List<UserDTO> allUsers() {
return userService.getAllUser();
}

@GetMapping("user/profile") // Профиль пользователя
public ResponseEntity<UserDTO> viewUserProfile(Authentication authentication) throws AccessDeniedException {
// Проверяем, что пользователь аутентифицирован, если да, то получаем имя из аутентификации, затем данные пользователя по его имени
if (authentication != null && authentication.isAuthenticated()) {
String username = authentication.getName();
User user = userService.getUserByUsername(username);

// Если пользователя не существует, возвращаем ответ с кодом 404 Not Found
if (user == null) {
return ResponseEntity.notFound().build();
}
// Если пользователь найден, возвращаем его данные с кодом 200 OK
return ResponseEntity.ok(UserDTO.toModel(user));
}
// Если пользователь не аутентифицирован, возвращаем ответ с кодом 401 Unauthorized
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}

@GetMapping("/user/profile/my-schedule")
public ResponseEntity<UserTimeRangeDTO> viewUserSchedule(Authentication authentication) throws AccessDeniedException {
// Проверяем, что пользователь аутентифицирован, если да, то получаем имя из аутентификации, затем данные пользователя по его имени
if (authentication != null && authentication.isAuthenticated()) {
String username = authentication.getName();
User user = userService.getUserByUsername(username);

// Если пользователя не существует, возвращаем ответ с кодом 404 Not Found
if (user == null) {
return ResponseEntity.notFound().build();
}

// Получаем список временных диапазонов пользователя
List<TimeRange> timeRanges = user.getTimeRanges();

// Создаем объект UserScheduleDTO с именем пользователя и его списком временных диапазонов
UserTimeRangeDTO userScheduleDTO = new UserTimeRangeDTO();
userScheduleDTO.setUserName(user.getUsername());

// Создаем список расписаний пользователя
List<Schedule> schedules = timeRanges.stream()
.map(TimeRange::getSchedule)
.distinct()
.collect(Collectors.toList());

// Устанавливаем список расписаний в UserTimeRangeDTO
userScheduleDTO.setSchedules(schedules);

// Возвращаем объект UserScheduleDTO с кодом 200 OK
return ResponseEntity.ok(userScheduleDTO);
}

// Если пользователь не аутентифицирован, возвращаем ответ с кодом 401 Unauthorized
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}



@GetMapping("admin/users/{id}")
public UserDTO getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}

@PostMapping
public void addUser(@RequestBody User user) {
userService.save(user);
}

@DeleteMapping("admin/users/{id}")
public void deleteUser(@PathVariable Long id) {
userService.delete(id);
}
}
30 changes: 30 additions & 0 deletions src/main/java/com/example/demo/dto/ScheduleDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.example.demo.dto;

import com.example.demo.entity.Schedule;
import com.example.demo.entity.TimeRange;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ScheduleDTO {
private Long id;
private LocalDate date;
private List<TimeRange> timeRanges;


// Методы преобразования

public static ScheduleDTO toModel(Schedule schedule) {
ScheduleDTO scheduleDTO = new ScheduleDTO();
scheduleDTO.setId(schedule.getId());
scheduleDTO.setDate(schedule.getDate());
scheduleDTO.setTimeRanges(schedule.getTimeRanges());
return scheduleDTO;
}
}
4 changes: 4 additions & 0 deletions src/main/java/com/example/demo/dto/TimeRangeDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.example.demo.dto;

public class TimeRangeDTO {
}
Loading

0 comments on commit 1925cf9

Please sign in to comment.