Skip to content

Commit 1f43374

Browse files
committed
Отрефакторил код
1 parent 7cdfa61 commit 1f43374

20 files changed

Lines changed: 105 additions & 113 deletions

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ target/
33
!.mvn/wrapper/maven-wrapper.jar
44
!**/src/main/**/target/
55
!**/src/test/**/target/
6+
/src/main/resources/application.properties
67

78
### IntelliJ IDEA ###
89
.idea/

src/main/java/com/markelloww/projectmanagement/config/WebSecurityConfig.java

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,51 +6,63 @@
66
import org.springframework.context.annotation.Configuration;
77
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
88
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9+
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
910
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
1011
import org.springframework.security.crypto.password.PasswordEncoder;
1112
import org.springframework.security.web.SecurityFilterChain;
1213
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
1314

14-
/**
15-
* @Author: Markelloww
16-
*/
17-
1815
@Configuration
1916
@EnableWebSecurity
2017
@RequiredArgsConstructor
2118
public class WebSecurityConfig {
19+
public static final String LOGIN_ENDPOINT = "/login";
20+
public static final String LOGOUT_ENDPOINT = "/logout";
21+
public static final String REG_ENDPOINT = "/reg";
22+
2223
private final NewUserDetailsService userDetailsService;
2324

2425
@Bean
2526
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
2627
http
27-
.authorizeHttpRequests((requests) -> requests
28-
.requestMatchers("/login", "/reg", "/css/auth.css").permitAll()
28+
.headers(headers -> headers
29+
.contentSecurityPolicy(csp -> csp
30+
.policyDirectives("default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'")
31+
)
32+
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
33+
)
34+
.sessionManagement(session -> session
35+
.sessionFixation().migrateSession()
36+
.maximumSessions(1)
37+
.expiredUrl(LOGIN_ENDPOINT + "?expired")
38+
)
39+
.authorizeHttpRequests(requests -> requests
40+
.requestMatchers(LOGIN_ENDPOINT, REG_ENDPOINT, "/css/auth.css").permitAll()
2941
.anyRequest().authenticated()
3042
)
3143
.userDetailsService(userDetailsService)
32-
.formLogin((form) -> form
33-
.loginPage("/login")
34-
.loginProcessingUrl("/login")
44+
.formLogin(form -> form
45+
.loginPage(LOGIN_ENDPOINT)
46+
.loginProcessingUrl(LOGIN_ENDPOINT)
3547
.defaultSuccessUrl("/", true)
3648
.permitAll()
3749
)
38-
.logout((logout) -> logout
39-
.logoutUrl("/logout")
40-
.logoutSuccessUrl("/login")
50+
.logout(logout -> logout
51+
.logoutUrl(LOGOUT_ENDPOINT)
52+
.logoutSuccessUrl(LOGIN_ENDPOINT)
4153
.invalidateHttpSession(true)
4254
.deleteCookies("JSESSIONID")
4355
.permitAll()
4456
)
45-
.exceptionHandling((exception) -> exception
46-
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
57+
.exceptionHandling(exception -> exception
58+
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint(LOGIN_ENDPOINT))
4759
);
4860

4961
return http.build();
5062
}
5163

5264
@Bean
5365
public PasswordEncoder passwordEncoder() {
54-
return new BCryptPasswordEncoder();
66+
return new BCryptPasswordEncoder(12);
5567
}
5668
}

src/main/java/com/markelloww/projectmanagement/controller/AuthController.java

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,29 +12,27 @@
1212
import org.springframework.web.bind.annotation.RequestParam;
1313
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
1414

15-
/**
16-
* @Author: Markelloww
17-
*/
18-
1915
@Controller
2016
@RequiredArgsConstructor
2117
public class AuthController {
18+
public static final String ERROR = "error";
19+
2220
private final UserRepository userRepository;
2321
private final PasswordEncoder passwordEncoder;
2422

2523
@GetMapping("/login")
26-
public String loginPage(@RequestParam(value = "error", required = false) String error,
24+
public String loginPage(@RequestParam(value = ERROR, required = false) String error,
2725
Model model) {
2826
if (error != null) {
29-
model.addAttribute("error", "Неверный e-mail или пароль");
27+
model.addAttribute(ERROR, "Неверный e-mail или пароль");
3028
}
3129
return "login";
3230
}
3331

3432
@GetMapping("/reg")
3533
public String regPage(@RequestParam(value = "msg", required = false) String error, Model model) {
3634
if (error != null) {
37-
model.addAttribute("error", "Пользователь с таким e-mail уже зарегистрирован!");
35+
model.addAttribute(ERROR, "Пользователь с таким e-mail уже зарегистрирован!");
3836
}
3937
return "reg";
4038
}
@@ -47,7 +45,7 @@ public String regUser(@RequestParam("username") String username,
4745
@RequestParam("lastname") String lastname,
4846
RedirectAttributes redirectAttributes) {
4947
if (userRepository.findByEmail(username).isPresent()) {
50-
redirectAttributes.addAttribute("msg", "error");
48+
redirectAttributes.addAttribute("msg", ERROR);
5149
return "redirect:/reg";
5250
}
5351

src/main/java/com/markelloww/projectmanagement/controller/ProfileController.java

Lines changed: 45 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import com.markelloww.projectmanagement.repository.UserRepository;
55
import com.markelloww.projectmanagement.service.UserService;
66
import lombok.RequiredArgsConstructor;
7-
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
87
import org.springframework.security.crypto.password.PasswordEncoder;
98
import org.springframework.stereotype.Controller;
109
import org.springframework.ui.Model;
@@ -15,17 +14,14 @@
1514

1615
import java.security.Principal;
1716

18-
/**
19-
* @Author: Markelloww
20-
*/
21-
2217
@Controller
2318
@RequiredArgsConstructor
2419
public class ProfileController {
20+
public static final String ERROR = "error";
21+
public static final String REDIRECT_PROFILE = "redirect:/profile";
2522
private final UserService userService;
2623
private final PasswordEncoder passwordEncoder;
2724
private final UserRepository userRepository;
28-
private final DataSourceTransactionManagerAutoConfiguration dataSourceTransactionManagerAutoConfiguration;
2925

3026
@GetMapping("/profile")
3127
public String profilePage(Model model, Principal principal) {
@@ -44,28 +40,53 @@ public String updateProfile(
4440
Principal principal,
4541
RedirectAttributes redirectAttributes) {
4642
User user = userService.getUserByEmail(principal.getName());
47-
if (!passwordEncoder.matches(currentPassword, user.getPassword())) {
48-
redirectAttributes.addFlashAttribute("error", "Введен неверный пароль");
49-
return "redirect:/profile";
50-
}
51-
if (!email.equalsIgnoreCase(user.getEmail())) {
52-
if (userRepository.existsByEmail(email.toLowerCase())) {
53-
redirectAttributes.addFlashAttribute("error", "Такой e-mail уже занят");
54-
return "redirect:/profile";
55-
}
56-
user.setEmail(email);
43+
44+
if (!hasValidationErrors(user, email, newPassword, confirmPassword, currentPassword, redirectAttributes)) {
45+
updateUser(user, email, firstname, lastname, newPassword);
46+
redirectAttributes.addFlashAttribute("success", "Профиль успешно обновлен");
5747
}
48+
49+
return REDIRECT_PROFILE;
50+
}
51+
52+
private void updateUser(User user, String email, String firstname,
53+
String lastname, String newPassword) {
54+
user.setEmail(email);
55+
user.setFirstname(firstname);
56+
user.setLastname(lastname);
57+
5858
if (newPassword != null && !newPassword.isEmpty()) {
59-
if (!newPassword.equals(confirmPassword)) {
60-
redirectAttributes.addFlashAttribute("error", "Новый пароль и подтверждение не совпадают");
61-
return "redirect:/profile";
62-
}
6359
user.setPassword(passwordEncoder.encode(newPassword));
6460
}
65-
user.setFirstname(firstname);
66-
user.setLastname(lastname);
61+
6762
userRepository.save(user);
68-
redirectAttributes.addFlashAttribute("success", "Профиль успешно обновлен");
69-
return "redirect:/profile";
7063
}
64+
65+
private boolean hasValidationErrors(User user, String email, String newPassword,
66+
String confirmPassword, String currentPassword,
67+
RedirectAttributes redirectAttributes) {
68+
if (!passwordEncoder.matches(currentPassword, user.getPassword())) {
69+
redirectAttributes.addFlashAttribute(ERROR, "Введен неверный пароль");
70+
return true;
71+
}
72+
73+
if (!email.equalsIgnoreCase(user.getEmail()) &&
74+
userRepository.existsByEmail(email.toLowerCase())) {
75+
redirectAttributes.addFlashAttribute(ERROR, "Такой e-mail уже занят");
76+
return true;
77+
}
78+
79+
if (newPassword != null && !newPassword.isEmpty()) {
80+
redirectAttributes.addFlashAttribute(ERROR, "Пароль не может быть пустым");
81+
return true;
82+
}
83+
84+
if (newPassword != null && !newPassword.equals(confirmPassword)) {
85+
redirectAttributes.addFlashAttribute(ERROR, "Новый пароль и подтверждение не совпадают");
86+
return true;
87+
}
88+
89+
return false;
90+
}
91+
7192
}

src/main/java/com/markelloww/projectmanagement/controller/ProjectController.java

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,17 @@
1212
import java.time.LocalDateTime;
1313
import java.time.format.DateTimeFormatter;
1414

15-
/**
16-
* @Author: Markelloww
17-
*/
18-
1915
@Controller
2016
@RequiredArgsConstructor
2117
@RequestMapping("/team/{teamId}/project")
2218
public class ProjectController {
19+
public static final String REDIRECT = "redirect:/";
20+
2321
private final TeamService teamService;
2422
private final ProjectService projectService;
2523
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
2624
private final TaskStatusService taskStatusService;
2725
private final TaskService taskService;
28-
private final UserService userService;
2926

3027

3128
@GetMapping("/{projectId}")
@@ -34,7 +31,7 @@ public String projectInfo(@PathVariable Long projectId,
3431
Principal principal,
3532
Model model) {
3633
if (!teamService.checkUser(teamId, principal.getName())) {
37-
return "redirect:/";
34+
return REDIRECT;
3835
}
3936

4037
Project project = projectService.getProjectById(projectId);
@@ -58,7 +55,7 @@ public String projectInfo(@PathVariable Long projectId,
5855
@GetMapping("/new")
5956
public String showProjectCreate(@PathVariable Long teamId, Model model, Principal principal) {
6057
if (!teamService.checkUser(teamId, principal.getName())) {
61-
return "redirect:/";
58+
return REDIRECT;
6259
}
6360
model.addAttribute("team", teamService.getTeamById(teamId));
6461
return "project-new";
@@ -67,7 +64,7 @@ public String showProjectCreate(@PathVariable Long teamId, Model model, Principa
6764
@PostMapping("/new")
6865
public String createProject(@PathVariable Long teamId, Project project, Principal principal) {
6966
if (!teamService.checkUser(teamId, principal.getName())) {
70-
return "redirect:/";
67+
return REDIRECT;
7168
}
7269
projectService.createProject(project, teamId, principal);
7370
return "redirect:/team/" + teamId;

src/main/java/com/markelloww/projectmanagement/controller/TaskController.java

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package com.markelloww.projectmanagement.controller;
22

3-
import com.markelloww.projectmanagement.model.Project;
43
import com.markelloww.projectmanagement.model.Task;
54
import com.markelloww.projectmanagement.service.ProjectService;
65
import com.markelloww.projectmanagement.service.TaskService;
@@ -11,14 +10,13 @@
1110

1211
import java.security.Principal;
1312

14-
/**
15-
* @Author: Markelloww
16-
*/
17-
1813
@Controller
1914
@RequiredArgsConstructor
2015
@RequestMapping("/team/{teamId}/project/{projectId}/task")
2116
public class TaskController {
17+
public static final String REDIRECT_TEAM = "redirect:/team/";
18+
public static final String PROJECT = "/project/";
19+
2220
private final TaskService taskService;
2321
private final ProjectService projectService;
2422

@@ -33,20 +31,20 @@ public String showCreateTask(@PathVariable Long projectId, @PathVariable Long te
3331
public String createTask(@PathVariable Long projectId, @PathVariable Long teamId,
3432
Task task, Principal principal) {
3533
taskService.createTask(task, projectId, principal.getName());
36-
return "redirect:/team/" + teamId + "/project/" + projectId;
34+
return REDIRECT_TEAM + teamId + PROJECT + projectId;
3735
}
3836

3937
@PostMapping("/update")
4038
public String updateTaskStatus(@PathVariable Long teamId, @PathVariable Long projectId,
4139
@RequestParam Long taskId, @RequestParam Long statusId ) {
4240
taskService.updateStatus(taskId, statusId);
43-
return "redirect:/team/" + teamId + "/project/" + projectId;
41+
return REDIRECT_TEAM + teamId + PROJECT + projectId;
4442
}
4543

4644
@PostMapping("/delete")
4745
public String deleteTask(@PathVariable Long teamId, @PathVariable Long projectId, Principal principal,
4846
@RequestParam Long taskId) {
4947
taskService.deleteTask(taskService.getTaskById(taskId), principal.getName());
50-
return "redirect:/team/" + teamId + "/project/" + projectId;
48+
return REDIRECT_TEAM + teamId + PROJECT + projectId;
5149
}
5250
}

src/main/java/com/markelloww/projectmanagement/controller/TeamController.java

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,9 @@
22

33
import com.markelloww.projectmanagement.model.Team;
44
import com.markelloww.projectmanagement.model.User;
5-
import com.markelloww.projectmanagement.repository.UserRepository;
65
import com.markelloww.projectmanagement.service.TeamService;
76
import com.markelloww.projectmanagement.service.UserService;
87
import lombok.RequiredArgsConstructor;
9-
import org.springframework.security.core.userdetails.UsernameNotFoundException;
108
import org.springframework.stereotype.Controller;
119
import org.springframework.ui.Model;
1210

@@ -16,13 +14,11 @@
1614

1715
import java.security.Principal;
1816

19-
/**
20-
* @Author: Markelloww
21-
*/
22-
2317
@Controller
2418
@RequiredArgsConstructor
2519
public class TeamController {
20+
public static final String REDIRECT_TEAM = "redirect:/team/";
21+
2622
private final UserService userService;
2723
private final TeamService teamService;
2824

@@ -67,18 +63,18 @@ public String deleteTeam(@PathVariable Long teamId, Principal principal) {
6763
@PostMapping("/team/{teamId}/join")
6864
public String joinTeam(@PathVariable Long teamId, Principal principal) {
6965
teamService.joinTeam(teamId, userService.getUserByEmail(principal.getName()));
70-
return "redirect:/team/" + teamId;
66+
return REDIRECT_TEAM + teamId;
7167
}
7268

7369
@PostMapping("/team/{teamId}/leave")
7470
public String leaveTeam(@PathVariable Long teamId, Principal principal) {
7571
teamService.leaveTeam(teamId, userService.getUserByEmail(principal.getName()));
76-
return "redirect:/team/" + teamId;
72+
return REDIRECT_TEAM + teamId;
7773
}
7874

7975
@PostMapping("/team/{teamId}/kick/{userId}")
8076
public String removeMember(@PathVariable Long teamId, @PathVariable Long userId) {
8177
teamService.leaveTeam(teamId, userService.getUserById(userId));
82-
return "redirect:/team/" + teamId;
78+
return REDIRECT_TEAM + teamId;
8379
}
8480
}

src/main/java/com/markelloww/projectmanagement/model/Project.java

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,6 @@
77
import java.util.HashSet;
88
import java.util.Set;
99

10-
/**
11-
* @Author: Markelloww
12-
*/
13-
1410
@Entity
1511
@Table(name = "projects")
1612
@Data

0 commit comments

Comments
 (0)