Compare commits

..
11 Commits
Author SHA1 Message Date
redtea a7a003734a Tag rename, project refactor, user fix 2024-07-08 00:44:54 +03:00
redtea 7d661c52f8 Replace snake case 2023-07-03 21:52:44 +03:00
redtea 60f2de1b5b 0.0.12, new fields of User 2023-07-03 00:20:16 +03:00
redtea ac328d8cef 0.0.11, enable cors 2023-06-29 23:15:08 +03:00
redtea 68ab91e4fc 0.0.10+additions 2023-06-27 14:22:46 +03:00
redtea 470484064a 0.0.10 2023-06-27 14:06:36 +03:00
redtea 93a145b561 fixes 2022-09-16 08:51:59 +03:00
redtea 27f4885a30 fixes 2022-09-15 22:49:10 +03:00
redtea 00374da288 Edited some requests, security fixes 2022-09-02 16:11:25 +03:00
Viktoria c7cca9a77e Merge remote-tracking branch 'origin/main'
# Conflicts:
#	src/main/java/site/easystartup/web/project/controller/ProjectController.java
2022-09-01 17:01:38 +02:00
redtea 3ac444931c Added Post system. Notification system 2022-09-01 17:04:25 +03:00
66 changed files with 1074 additions and 300 deletions

No files matched your search

+3 -2
View File
@@ -6,7 +6,7 @@ plugins {
} }
group = 'site.easy-startup' group = 'site.easy-startup'
version = '0.0.1-SNAPSHOT' version = '0.0.12'
sourceCompatibility = "17" sourceCompatibility = "17"
configurations { configurations {
@@ -20,7 +20,8 @@ repositories {
} }
dependencies { dependencies {
implementation 'org.springdoc:springdoc-openapi-ui:1.6.9' implementation 'mysql:mysql-connector-java:8.0.30'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.11'
implementation 'com.google.code.gson:gson:2.9.0' implementation 'com.google.code.gson:gson:2.9.0'
implementation 'com.auth0:java-jwt:4.0.0' implementation 'com.auth0:java-jwt:4.0.0'
implementation 'org.springframework:spring-websocket:5.3.22' implementation 'org.springframework:spring-websocket:5.3.22'
@@ -1,17 +1,10 @@
package site.easystartup.web; package site.easystartup.web;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication @SpringBootApplication
@SecurityScheme(type = SecuritySchemeType.OAUTH2, name = "api_key", in = SecuritySchemeIn.HEADER)
public class EasyStartupApplication { public class EasyStartupApplication {
public static void main(String[] args) { public static void main(String[] args) {
@@ -1,24 +1,20 @@
package site.easystartup.web.auth.controller; package site.easystartup.web.auth.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper; import org.modelmapper.ModelMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import site.easystartup.web.domain.model.User; import site.easystartup.web.domain.model.User;
import site.easystartup.web.domain.request.LoginRequest; import site.easystartup.web.domain.request.LoginRequest;
import site.easystartup.web.domain.request.SignupRequest; import site.easystartup.web.domain.request.SignupRequest;
import site.easystartup.web.domain.request.UpdatePassportRequest;
import site.easystartup.web.domain.response.MessageResponse; import site.easystartup.web.domain.response.MessageResponse;
import site.easystartup.web.domain.response.SuccessAuthenticationResponse; import site.easystartup.web.domain.response.SuccessAuthenticationResponse;
import site.easystartup.web.domain.validation.ResponseErrorValidation; import site.easystartup.web.domain.validation.ResponseErrorValidation;
@@ -34,7 +30,6 @@ import java.security.Principal;
@RestController @RestController
@RequestMapping("/auth") @RequestMapping("/auth")
@RequiredArgsConstructor @RequiredArgsConstructor
@Tag(name = "Авторизация")
public class AuthController { public class AuthController {
private final JWTUtil jwtUtil; private final JWTUtil jwtUtil;
private final UserService userService; private final UserService userService;
@@ -43,10 +38,14 @@ public class AuthController {
private final ResponseErrorValidation responseErrorValidation; private final ResponseErrorValidation responseErrorValidation;
private final ModelMapper modelMapper; private final ModelMapper modelMapper;
//@
@PostMapping("/signup") @PostMapping("/signup")
@Operation(summary = "Создание нового аккаунта")
public ResponseEntity<Object> registration(@Valid @RequestBody SignupRequest signupRequest, public ResponseEntity<Object> registration(@Valid @RequestBody SignupRequest signupRequest,
BindingResult bindingResult) { BindingResult bindingResult) {
if(userService.userExists(signupRequest.getUsername())) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(new MessageResponse("A user with this username already exists"));
}
ResponseEntity<Object> errors = responseErrorValidation.mapValidationService(bindingResult); ResponseEntity<Object> errors = responseErrorValidation.mapValidationService(bindingResult);
if (!ObjectUtils.isEmpty(errors)) return errors; if (!ObjectUtils.isEmpty(errors)) return errors;
@@ -55,17 +54,22 @@ public class AuthController {
return ResponseEntity.ok(new MessageResponse("Account registered successfully!")); return ResponseEntity.ok(new MessageResponse("Account registered successfully!"));
} }
//@
@PostMapping("/login") @PostMapping("/login")
@Operation(summary = "Логин, получение JWT ключа и данных текущего пользователя")
public ResponseEntity<Object> authentication(@Valid @RequestBody LoginRequest loginRequest, public ResponseEntity<Object> authentication(@Valid @RequestBody LoginRequest loginRequest,
BindingResult bindingResult) { BindingResult bindingResult) {
ResponseEntity<Object> errors = responseErrorValidation.mapValidationService(bindingResult); ResponseEntity<Object> errors = responseErrorValidation.mapValidationService(bindingResult);
if (!ObjectUtils.isEmpty(errors)) return errors; if (!ObjectUtils.isEmpty(errors)) return errors;
Authentication authentication;
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( try {
authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
loginRequest.getUsername(), loginRequest.getUsername(),
loginRequest.getPassword() loginRequest.getPassword()
)); ));
} catch (BadCredentialsException e) {
return ResponseEntity.status(401).body(new MessageResponse("Invalid login or password"));
}
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
@@ -75,28 +79,5 @@ public class AuthController {
return ResponseEntity.ok().body(response); return ResponseEntity.ok().body(response);
} }
@PostMapping("/password")
@Operation(summary = "обновление пароля и получение нового JWT")
public ResponseEntity<Object> updatePassword(@Valid @RequestBody UpdatePassportRequest passportRequest,
BindingResult bindingResult,
Principal principal) {
ResponseEntity<Object> errors = responseErrorValidation.mapValidationService(bindingResult);
if (!ObjectUtils.isEmpty(errors)) return errors;
User user = authService.updatePassword(passportRequest, principal);
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
user.getUsername(),
user.getPassword()
));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = SecurityConstants.TOKEN_PREFIX + jwtUtil.generateToken(user.getUsername());
SuccessAuthenticationResponse response = new SuccessAuthenticationResponse(jwt, modelMapper.map(user, UserDto.class));
return ResponseEntity.ok().body(response);
}
} }
@@ -5,6 +5,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import site.easystartup.web.domain.model.Role; import site.easystartup.web.domain.model.Role;
@@ -20,11 +21,13 @@ public class RegistrationController {
private final UserRepo userRepo; private final UserRepo userRepo;
//@
@GetMapping("/registration") @GetMapping("/registration")
public String registration() { public String registration() {
return "registration"; return "registration";
} }
//@
@PostMapping("/registration") @PostMapping("/registration")
public String addUser(User user, Model model) { public String addUser(User user, Model model) {
User userFromDb = userRepo.findByUsername(user.getUsername()); User userFromDb = userRepo.findByUsername(user.getUsername());
@@ -0,0 +1,18 @@
package site.easystartup.web.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@ComponentScan
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("PUT", "GET", "DELETE", "OPTIONS", "PATCH", "POST");
}
}
@@ -0,0 +1,12 @@
package site.easystartup.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MainController {
@GetMapping("/")
public String main() {
return "/main";
}
}
@@ -4,13 +4,12 @@ import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper; import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import site.easystartup.web.domain.model.User; import site.easystartup.web.domain.model.User;
import site.easystartup.web.domain.response.MessageResponse;
import site.easystartup.web.domain.validation.ResponseErrorValidation; import site.easystartup.web.domain.validation.ResponseErrorValidation;
import site.easystartup.web.dto.UserDto; import site.easystartup.web.dto.UserDto;
import site.easystartup.web.exception.NoPermissionException; import site.easystartup.web.exception.NoPermissionException;
@@ -20,29 +19,49 @@ import site.easystartup.web.project.dto.ProjectDto;
import site.easystartup.web.project.service.ProjectService; import site.easystartup.web.project.service.ProjectService;
import site.easystartup.web.request.UserRequest; import site.easystartup.web.request.UserRequest;
import site.easystartup.web.service.UserService; import site.easystartup.web.service.UserService;
import site.easystartup.web.util.FastChecksUtil;
import javax.validation.Valid;
import java.security.Principal; import java.security.Principal;
@RestController @RestController
@RequiredArgsConstructor(onConstructor_ = @Autowired) @RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UserController { public class UserController {
private final UserService userService; private final site.easystartup.web.service.UserService userService;
private final ModelMapper modelMapper; private final ModelMapper modelMapper;
private final ResponseErrorValidation responseErrorValidation; private final ResponseErrorValidation responseErrorValidation;
private final FastChecksUtil checksUtil;
@GetMapping("/user/{username}") //@
public ResponseEntity<UserDto> user(@PathVariable String username) { @GetMapping("/user/current")
return ResponseEntity.ok().body(modelMapper.map(userService.getUserByUsername(username), UserDto.class)); public ResponseEntity<Object> getCurrentUser(Principal principal) {
//if(principal == null)
try {
return ResponseEntity.ok().body(modelMapper.map(userService.getUserByPrincipal(principal), UserDto.class));
} catch(Throwable e) {
return ResponseEntity.badRequest().body(new MessageResponse("User not found"));
} }
@PostMapping("/user/{username}/edit") }
public ResponseEntity<Object> userEdit(@PathVariable String username, UserRequest userRequest,
//@
@GetMapping("/user/{username}")
public ResponseEntity<UserDto> getUser(@PathVariable String username) {
Long id = Long.parseLong(username);
ResponseEntity<UserDto> result = checksUtil.nullIfValid(username);
return result == null ? ResponseEntity.ok().body(modelMapper.map(userService.getUserByUsername(username), UserDto.class)) : result;
}
//@
@PutMapping("/user/edit/{username}")
public ResponseEntity<Object> userEdit(@PathVariable String username,@Valid @RequestBody UserRequest userRequest,
BindingResult bindingResult, Principal principal) { BindingResult bindingResult, Principal principal) {
if(!principal.getName().equals(username) && !userService.getUserByPrincipal(principal).isAdmin()) if(!userService.getCurrent().getUsername().equals(username) && !userService.getUserByPrincipal(principal).isAdmin())
throw new NoPermissionException(String.format("User %s can not edit profile of user %s", principal.getName(), throw new NoPermissionException(String.format("User %s can not edit profile of user %s", principal.getName(),
username)); username));
var errors = responseErrorValidation.mapValidationService(bindingResult); ResponseEntity<Object> errors = responseErrorValidation.mapValidationService(bindingResult);
if (!ObjectUtils.isEmpty(errors)) return errors; if (!ObjectUtils.isEmpty(errors)) return errors;
User editedUser = userService.editUser(username, userRequest); User editedUser = userService.editUser(username, userRequest);
@@ -22,31 +22,45 @@ public class User implements UserDetails {
private String username; private String username;
private String password; private String password;
private boolean active; private boolean active;
private String full_name; private String fullName;
private String status; private String status;
private String iconPath; private String iconPath;
private String email; private String email;
private String about;
private String country;
private String city;
private String birthday;
@ElementCollection(targetClass = String.class, fetch = FetchType.EAGER) @ElementCollection(targetClass = String.class, fetch = FetchType.EAGER)
@CollectionTable(name = "user_tag", joinColumns = @JoinColumn(name = "user_id")) @CollectionTable(name = "technologies", joinColumns = @JoinColumn(name = "user_id"))
private Set<String> tags; private Set<String> technologies;
@ElementCollection(targetClass = String.class, fetch = FetchType.EAGER) @ElementCollection(targetClass = String.class, fetch = FetchType.EAGER)
@CollectionTable(name = "user_profession", joinColumns = @JoinColumn(name = "user_id")) @CollectionTable(name = "profession", joinColumns = @JoinColumn(name = "user_id"))
private Set<String> professions; private Set<String> professions;
@ElementCollection(targetClass = Long.class, fetch = FetchType.EAGER) @ElementCollection(targetClass = Long.class, fetch = FetchType.EAGER)
@CollectionTable(name = "user_projects", joinColumns = @JoinColumn(name = "user_id")) @CollectionTable(name = "projects", joinColumns = @JoinColumn(name = "user_id"))
private Set<Long> projects; private Set<Long> projects;
@ManyToMany(mappedBy = "requests") @ManyToMany(mappedBy = "requests")
private List<Participant> requests; private List<Participant> requests;
@ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER) @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
@CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id")) @CollectionTable(name = "role", joinColumns = @JoinColumn(name = "user_id"))
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
private Set<Role> roles; private Set<Role> roles;
@ElementCollection(targetClass = String.class, fetch = FetchType.EAGER)
@CollectionTable(name = "languages", joinColumns = @JoinColumn(name = "user_id"))
private Set<String> languages;
@ElementCollection
@CollectionTable(name = "user_contact",
joinColumns = {@JoinColumn(name = "user_id")})
@MapKeyColumn(name = "media")
private Map<String, String> contacts;
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
@@ -1,6 +1,10 @@
package site.easystartup.web.domain.request; package site.easystartup.web.domain.request;
import lombok.Data; import lombok.Data;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import site.easystartup.web.domain.annotation.PasswordMatches; import site.easystartup.web.domain.annotation.PasswordMatches;
import site.easystartup.web.domain.model.Role; import site.easystartup.web.domain.model.Role;
@@ -14,7 +14,7 @@ import java.util.Map;
@Service @Service
public class ResponseErrorValidation { public class ResponseErrorValidation {
public ResponseEntity<Object> mapValidationService(BindingResult result) { public<T> ResponseEntity<Object> mapValidationService(BindingResult result) {
if (result.hasErrors()) { if (result.hasErrors()) {
Map<String, String> errorMap = new HashMap<>(); Map<String, String> errorMap = new HashMap<>();
@@ -6,6 +6,7 @@ import site.easystartup.web.project.domain.model.Participant;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
@Data @Data
@@ -13,13 +14,19 @@ public class UserDto implements Serializable {
private long id; private long id;
private String username; private String username;
private boolean active; private boolean active;
private String full_name; private String fullName;
private String status; private String status;
private String iconPath; private String iconPath;
private String email; private String email;
private Set<String> tags; private Set<String> technologies;
private Set<String> professions; private Set<String> professions;
private Set<Long> projects; private Set<Long> projects;
private List<Participant> requests; private List<Participant> requests;
private Set<Role> roles; private Set<Role> roles;
private String about;
private String country;
private String city;
private String birthday;
private Set<String> languages;
private Map<String, String> contacts;
} }
@@ -1,5 +1,9 @@
package site.easystartup.web.exception; package site.easystartup.web.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.FORBIDDEN)
public class NoPermissionException extends RuntimeException { public class NoPermissionException extends RuntimeException {
public NoPermissionException(String username) { public NoPermissionException(String username) {
super("User " + username + " do not have access for this action"); super("User " + username + " do not have access for this action");
@@ -38,6 +38,7 @@ public class ForumController {
private final ModelMapper modelMapper; private final ModelMapper modelMapper;
private final ResponseErrorValidation responseErrorValidation; private final ResponseErrorValidation responseErrorValidation;
//@
@GetMapping("/") @GetMapping("/")
public ResponseEntity<List<TopicDto>> main(@Valid @RequestBody ProjectRequest projectRequest, public ResponseEntity<List<TopicDto>> main(@Valid @RequestBody ProjectRequest projectRequest,
BindingResult bindingResult, BindingResult bindingResult,
@@ -47,13 +48,16 @@ public class ForumController {
return ResponseEntity.ok().body(topics); return ResponseEntity.ok().body(topics);
} }
//@
@GetMapping("/my") @GetMapping("/my")
public ResponseEntity<List<DiscussionDto>> my(Principal principal) { public ResponseEntity<List<DiscussionDto>> my(Principal principal) {
var discussions = forumService.getDiscussionsByAuthor(principal) var discussions = forumService.getDiscussionsByAuthor(principal)
.stream().map(discussion -> modelMapper.map(discussion, DiscussionDto.class)).toList(); .stream().map(discussion -> modelMapper.map(discussion, DiscussionDto.class)).toList();
System.out.println(principal.getName());
return ResponseEntity.ok().body(discussions); return ResponseEntity.ok().body(discussions);
} }
//@
@GetMapping("/takepart") @GetMapping("/takepart")
public ResponseEntity<List<DiscussionDto>> takePart(Principal principal) { public ResponseEntity<List<DiscussionDto>> takePart(Principal principal) {
var discussions = forumService.getDiscussionsByMember(principal) var discussions = forumService.getDiscussionsByMember(principal)
@@ -61,6 +65,7 @@ public class ForumController {
return ResponseEntity.ok().body(discussions); return ResponseEntity.ok().body(discussions);
} }
//@
@Secured({"ADMIN", "MODER"}) @Secured({"ADMIN", "MODER"})
@PostMapping("/new") @PostMapping("/new")
public ResponseEntity<Object> forumNew(@Valid @RequestBody TopicRequest topicRequest, public ResponseEntity<Object> forumNew(@Valid @RequestBody TopicRequest topicRequest,
@@ -73,6 +78,7 @@ public class ForumController {
return ResponseEntity.ok().body(modelMapper.map(topic, TopicDto.class)); return ResponseEntity.ok().body(modelMapper.map(topic, TopicDto.class));
} }
//@
@GetMapping("/{topic_id}/{page_id}") @GetMapping("/{topic_id}/{page_id}")
public ResponseEntity<List<DiscussionDto>> topicPage(@PathVariable long topic_id, public ResponseEntity<List<DiscussionDto>> topicPage(@PathVariable long topic_id,
@PathVariable long page_id) { @PathVariable long page_id) {
@@ -81,12 +87,14 @@ public class ForumController {
return ResponseEntity.ok().body(discussions); return ResponseEntity.ok().body(discussions);
} }
//@
@GetMapping("/discussion/{discussion_id}") @GetMapping("/discussion/{discussion_id}")
public ResponseEntity<DiscussionDto> discussion(@PathVariable(value = "discussion_id") long discussion_id) { public ResponseEntity<DiscussionDto> discussion(@PathVariable(value = "discussion_id") long discussion_id) {
return ResponseEntity.ok().body(modelMapper.map(forumService.getDiscussionById(discussion_id), DiscussionDto.class)); return ResponseEntity.ok().body(modelMapper.map(forumService.getDiscussionById(discussion_id), DiscussionDto.class));
} }
@PostMapping("/{topic_id}/new") //@
@PostMapping("/new/{topic_id}")
public ResponseEntity<Object> discussionNew(@PathVariable long topic_id, public ResponseEntity<Object> discussionNew(@PathVariable long topic_id,
@Valid @RequestBody DiscussionRequest discussionRequest, @Valid @RequestBody DiscussionRequest discussionRequest,
BindingResult bindingResult, BindingResult bindingResult,
@@ -98,7 +106,8 @@ public class ForumController {
return ResponseEntity.ok().body(modelMapper.map(discussion, DiscussionDto.class)); return ResponseEntity.ok().body(modelMapper.map(discussion, DiscussionDto.class));
} }
@PutMapping("/discussion/{discussion_id}/edit") //@
@PutMapping("/discussion/edit/{discussion_id}")
public ResponseEntity<Object> discussionEdit(@Valid @RequestBody DiscussionRequest discussionRequest, public ResponseEntity<Object> discussionEdit(@Valid @RequestBody DiscussionRequest discussionRequest,
@PathVariable long discussion_id, @PathVariable long discussion_id,
BindingResult bindingResult, BindingResult bindingResult,
@@ -110,7 +119,8 @@ public class ForumController {
return ResponseEntity.ok().body(modelMapper.map(discussionUpdated, DiscussionDto.class)); return ResponseEntity.ok().body(modelMapper.map(discussionUpdated, DiscussionDto.class));
} }
@PostMapping("/discussion/{discussion_id}/new") //@
@PostMapping("/discussion/new/{discussion_id}")
public ResponseEntity<Object> messageAdd(@PathVariable long discussion_id, public ResponseEntity<Object> messageAdd(@PathVariable long discussion_id,
@Valid @RequestBody DiscussionMessageRequest messageRequest, @Valid @RequestBody DiscussionMessageRequest messageRequest,
BindingResult bindingResult, BindingResult bindingResult,
@@ -122,12 +132,14 @@ public class ForumController {
return ResponseEntity.ok().body(modelMapper.map(discussionMessage, DiscussionMessageDto.class)); return ResponseEntity.ok().body(modelMapper.map(discussionMessage, DiscussionMessageDto.class));
} }
//@
@GetMapping("/message/{message_id}") @GetMapping("/message/{message_id}")
public ResponseEntity<DiscussionMessageDto> message(@PathVariable long message_id) { public ResponseEntity<DiscussionMessageDto> message(@PathVariable long message_id) {
return ResponseEntity.ok().body(modelMapper.map(forumService.getDiscussionMessageById(message_id), DiscussionMessageDto.class)); return ResponseEntity.ok().body(modelMapper.map(forumService.getDiscussionMessageById(message_id), DiscussionMessageDto.class));
} }
@PutMapping("/message/{message_id}/edit") //@
@PutMapping("/message/edit/{message_id}")
public ResponseEntity<Object> messageEdit(@Valid @RequestBody DiscussionMessageRequest messageRequest, public ResponseEntity<Object> messageEdit(@Valid @RequestBody DiscussionMessageRequest messageRequest,
@PathVariable long message_id, @PathVariable long message_id,
BindingResult bindingResult, BindingResult bindingResult,
@@ -139,7 +151,8 @@ public class ForumController {
return ResponseEntity.ok().body(modelMapper.map(messageUpdated, DiscussionMessageDto.class)); return ResponseEntity.ok().body(modelMapper.map(messageUpdated, DiscussionMessageDto.class));
} }
@DeleteMapping("/message/{message_id}/delete") //@
@DeleteMapping("/message/delete/{message_id}")
public ResponseEntity<Object> messageDelete(@PathVariable long message_id, Principal principal) { public ResponseEntity<Object> messageDelete(@PathVariable long message_id, Principal principal) {
DiscussionMessage message = forumService.getDiscussionMessageById(message_id); DiscussionMessage message = forumService.getDiscussionMessageById(message_id);
User user = userService.getUserByPrincipal(principal); User user = userService.getUserByPrincipal(principal);
@@ -17,10 +17,9 @@ public class DiscussionDto implements Serializable {
private String title; private String title;
private String author; private String author;
private Date date; private Date date;
private Date last_update; private Date lastUpdate;
private boolean pinned; private boolean pinned;
private DiscussionStatus status; private DiscussionStatus status;
private long topic; private long topic;
private List<Long> messages; private List<Long> messages;
} }
@@ -16,5 +16,5 @@ public class DiscussionMessageDto implements Serializable {
private String sender; private String sender;
private Date date; private Date date;
private boolean edited; private boolean edited;
private long discussion_id; private long discussionId;
} }
@@ -16,5 +16,5 @@ public class TopicDto implements Serializable {
private String author; private String author;
private int size; private int size;
private String description; private String description;
private Date last_update; private Date lastUpdate;
} }
@@ -0,0 +1,30 @@
package site.easystartup.web.notification.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import site.easystartup.web.notification.domian.Notification;
import java.security.Principal;
import java.util.logging.Logger;
@Controller
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class NotificationController {
private final SimpMessagingTemplate messagingTemplate;
Logger logger = Logger.getGlobal();
//@
@GetMapping("/notify")
public void notification(Principal principal, @Payload Notification notification) {
logger.info("Web socket sent notification to " + principal.getName());
messagingTemplate.convertAndSendToUser(principal.getName(), "queue/notification", notification);
}
}
@@ -0,0 +1,31 @@
package site.easystartup.web.notification.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import site.easystartup.web.notification.domian.Notification;
import site.easystartup.web.notification.repo.NotificationRepo;
import site.easystartup.web.notification.service.NotificationService;
import java.security.Principal;
import java.util.List;
@RestController
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class NotificationRestController {
private final NotificationService notificationService;
//@
@GetMapping("/notifications/{username}")
public ResponseEntity<List<Notification>> notification(@PathVariable String username, Principal principal) {
return ResponseEntity.ok().body(notificationService.getNotificationByRecipient(username, principal));
}
//@
@DeleteMapping("/notifications/{id}/delete")
public void delete(@PathVariable long id,
Principal principal) {
notificationService.delete(id, principal);
}
}
@@ -0,0 +1,17 @@
package site.easystartup.web.notification.domian;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
@Getter
@Setter
@ToString
@Entity
public class Notification {
@Id
private long id;
private String text;
private String recipient;
}
@@ -0,0 +1,12 @@
package site.easystartup.web.notification.event;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EventHandler {
}
@@ -0,0 +1,9 @@
package site.easystartup.web.notification.event;
public interface NotificationEvent {
void invoke();
String getRecipient();
String getMessage();
}
@@ -0,0 +1,36 @@
package site.easystartup.web.notification.event;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Component
@Scope("singleton")
public class NotificationEventManager {
private List<NotificationListener> listeners = new ArrayList<>();
public void registerListener(NotificationListener listener) {
listeners.add(listener);
}
public void removeListener(NotificationListener listener) {
listeners.remove(listener);
}
public void notifyListeners(Class<? extends NotificationEvent> event) {
listeners.forEach(listener -> Arrays.stream(listener.getClass().getMethods()).
filter(m -> m.isAnnotationPresent(EventHandler.class)).forEach(method -> {
if (method.getParameterTypes()[0].equals(event.getClass())) {
try {
method.invoke(listener, event);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}));
}
}
@@ -0,0 +1,4 @@
package site.easystartup.web.notification.event;
public interface NotificationListener {
}
@@ -0,0 +1,26 @@
package site.easystartup.web.notification.event.realtime;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import site.easystartup.web.notification.domian.Notification;
import site.easystartup.web.notification.event.EventHandler;
import site.easystartup.web.notification.event.NotificationEvent;
import site.easystartup.web.notification.event.NotificationListener;
import site.easystartup.web.notification.repo.NotificationRepo;
import site.easystartup.web.notification.service.NotificationService;
import site.easystartup.web.post.domain.event.RepostEvent;
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class RealTimeListener implements NotificationListener {
private final NotificationService notificationService;
private final NotificationRepo repo;
@EventHandler
public void onEvent(NotificationEvent event) {
Notification notification = new Notification();
notification.setText(event.getMessage());
notification.setRecipient(event.getRecipient());
notificationService.sendNotification(repo.save(notification));
}
}
@@ -0,0 +1,7 @@
package site.easystartup.web.notification.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import site.easystartup.web.notification.domian.Notification;
public interface NotificationRepo extends JpaRepository<Notification, Long> {
}
@@ -0,0 +1,43 @@
package site.easystartup.web.notification.service;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import site.easystartup.web.exception.NoPermissionException;
import site.easystartup.web.notification.domian.Notification;
import site.easystartup.web.notification.repo.NotificationRepo;
import site.easystartup.web.service.UserService;
import java.security.Principal;
import java.util.List;
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class NotificationService {
private final SimpMessagingTemplate messagingTemplate;
private final NotificationRepo repo;
private final UserService userService;
public void sendNotification(Notification notification) {
messagingTemplate.convertAndSendToUser(notification.getRecipient(), "queue/notification", notification);
}
public List<Notification> getNotificationByRecipient(String recipient, Principal principal) {
if(!recipient.equals(principal.getName()) && !userService.getUserByPrincipal(principal).isAdmin())
throw new NoPermissionException(String.format("User %s dont have access to see notifications of user %s",
principal.getName(), recipient));
return repo.findAll().stream()
.filter(notification -> notification.getRecipient().equals(recipient)).toList();
}
public void delete(long id, Principal principal) {
Notification notification = repo.findById(id).orElseThrow();
if(!notification.getRecipient().equals(principal.getName()) && !userService.getUserByPrincipal(principal).isAdmin())
throw new NoPermissionException(String.format("User %s dont have access to delete notifications of user %s",
principal.getName(), notification.getRecipient()));
repo.delete(notification);
}
}
@@ -0,0 +1,103 @@
package site.easystartup.web.post.controller;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import site.easystartup.web.domain.model.User;
import site.easystartup.web.domain.response.MessageResponse;
import site.easystartup.web.domain.validation.ResponseErrorValidation;
import site.easystartup.web.exception.NoPermissionException;
import site.easystartup.web.post.domain.model.Post;
import site.easystartup.web.post.domain.request.PostRequest;
import site.easystartup.web.post.dto.PostDto;
import site.easystartup.web.post.service.PostService;
import site.easystartup.web.project.domain.requst.ProjectRequest;
import site.easystartup.web.service.UserService;
import javax.validation.Valid;
import java.security.Principal;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/post")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class PostController {
private final PostService postService;
private final UserService userService;
private final ModelMapper modelMapper;
private final ResponseErrorValidation responseErrorValidation;
//@
@GetMapping("/")
public ResponseEntity<List<PostDto>> main(Principal principal) {
var posts = postService.getAllPostsByAuthor(principal.getName())
.stream().map(post -> modelMapper.map(post, PostDto.class)).toList();
return ResponseEntity.ok().body(posts);
}
//@
@PostMapping("/new")
public ResponseEntity<Object> createPost(@Valid @RequestBody PostRequest postRequest, BindingResult bindingResult,
Principal principal) {
var errors = responseErrorValidation.mapValidationService(bindingResult);
if (!ObjectUtils.isEmpty(errors)) return errors;
Post post = postService.createPost(postRequest, principal);
return ResponseEntity.ok().body(modelMapper.map(post, PostDto.class));
}
//@
@GetMapping("/user/{username}")
public ResponseEntity<List<PostDto>> user(@PathVariable String username) {
var posts = postService.getAllPostsByAuthor(username)
.stream().map(post -> modelMapper.map(post, PostDto.class)).toList();
return ResponseEntity.ok().body(posts);
}
//@
@PutMapping("/edit/{post_id}")
public ResponseEntity<Object> edit(@Valid @RequestBody PostRequest postRequest, BindingResult bindingResult,
Principal principal, @PathVariable long post_id) {
var errors = responseErrorValidation.mapValidationService(bindingResult);
if (!ObjectUtils.isEmpty(errors)) return errors;
Post post = postService.edit(postRequest, post_id, principal);
return ResponseEntity.ok().body(modelMapper.map(post, PostDto.class));
}
//@
@DeleteMapping("/delete/{post_id}/")
public void delete(@PathVariable long post_id,
Principal principal) {
Post post = postService.getPostById(post_id);
if(!post.getSender().equals(principal.getName()) && !userService.getUserByPrincipal(principal).isAdmin())
throw new NoPermissionException(String.format("User %s cant delete post %s", principal.getName(), post_id));
else postService.delete(post);
}
//@
@PutMapping("/like/{post_id}/")
public ResponseEntity<Object> like(Principal principal, @PathVariable long post_id) {
Post post = postService.getPostById(post_id);
Post edited = postService.addLike(post, principal);
return ResponseEntity.ok().body(modelMapper.map(edited, PostRequest.class));
}
//@
@PutMapping("/dislike/{post_id}/")
public ResponseEntity<Object> dislike(Principal principal, @PathVariable long post_id) {
Post post = postService.getPostById(post_id);
Post edited = postService.disLike(post, principal);
return ResponseEntity.ok().body(modelMapper.map(edited, PostRequest.class));
}
}
@@ -0,0 +1,27 @@
package site.easystartup.web.post.domain.event;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import site.easystartup.web.notification.event.NotificationEvent;
import site.easystartup.web.notification.event.NotificationEventManager;
@RequiredArgsConstructor
public class RepostEvent implements NotificationEvent {
@Autowired
private NotificationEventManager notificationEventManager;
@Getter
private final String recipient;
@Getter
private final String reportedUser;
@Getter
private final String message;
@Override
public void invoke() {
notificationEventManager.notifyListeners(getClass());
}
}
@@ -0,0 +1,7 @@
package site.easystartup.web.post.domain.exception;
public class AlreadyLikedException extends RuntimeException {
public AlreadyLikedException(String message) {
super(message);
}
}
@@ -0,0 +1,7 @@
package site.easystartup.web.post.domain.exception;
public class DontLickedException extends RuntimeException{
public DontLickedException(String message) {
super(message);
}
}
@@ -0,0 +1,21 @@
package site.easystartup.web.post.domain.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.function.Supplier;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class PostNotFoundException extends RuntimeException implements Supplier<PostNotFoundException> {
private String message;
public PostNotFoundException(String message) {
super(message);
this.message = message;
}
@Override
public PostNotFoundException get() {
return this;
}
}
@@ -0,0 +1,70 @@
package site.easystartup.web.post.domain.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.Hibernate;
import site.easystartup.web.domain.model.Role;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Entity
@Table(name = "pst")
public class Post implements Comparable<Post>{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "post_id")
private long id;
@Column(columnDefinition="varchar(1024)")
private String text;
private String sender;
@Column(name = "lk")
private long like;
@ElementCollection(targetClass = Long.class, fetch = FetchType.LAZY)
@CollectionTable(name = "post_answers", joinColumns = @JoinColumn(name = "post_id"))
private Set<Long> answers;
@ElementCollection(targetClass = String.class, fetch = FetchType.LAZY)
@CollectionTable(name = "post_liked", joinColumns = @JoinColumn(name = "post_id"))
private Set<String> liked_users;
private Long answered_post;
@Column(name = "date", updatable = false)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date date;
private boolean edited;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
Post that = (Post) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@Override
public int compareTo(Post o) {
if (getDate() == null || o.getDate() == null)
return 0;
return getDate().compareTo(o.getDate());
}
}
@@ -0,0 +1,26 @@
package site.easystartup.web.post.domain.request;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Builder;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.List;
@Data
@Builder
public class PostRequest {
@Size(min = 3, max = 1024, message = "Text should be no less 3 and no more 1024 signs")
@NotNull
private String text;
private String sender;
private Date date;
private boolean edited;
private List<String> liked_users;
private long like;
private List<Long> answers;
private Long answered_post;
}
@@ -0,0 +1,24 @@
package site.easystartup.web.post.dto;
import lombok.Data;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Data
public class PostDto implements Serializable {
private long id;
@Size(min = 3, max = 1024, message = "Text should be no less 3 and no more 1024 signs")
@NotNull
private String text;
private String sender;
private Date date;
private boolean edited;
private List<String> likedUsers;
private long like;
private List<Long> answers;
private long answeredPost;
}
@@ -0,0 +1,7 @@
package site.easystartup.web.post.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import site.easystartup.web.post.domain.model.Post;
public interface PostRepo extends JpaRepository<Post, Long> {
}
@@ -0,0 +1,87 @@
package site.easystartup.web.post.service;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import site.easystartup.web.post.domain.event.RepostEvent;
import site.easystartup.web.post.domain.exception.AlreadyLikedException;
import site.easystartup.web.post.domain.exception.PostNotFoundException;
import site.easystartup.web.post.domain.model.Post;
import site.easystartup.web.post.domain.request.PostRequest;
import site.easystartup.web.post.repo.PostRepo;
import java.security.Principal;
import java.util.*;
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class PostService {
private final PostRepo postRepo;
public Post getPostById(long id) {
return postRepo.findById(id).orElseThrow(new PostNotFoundException("Post with id " + id + " dont exists!"));
}
public List<Post> getAllPostsByAuthor(String username) {
return postRepo.findAll().stream().filter(post -> post.getSender().equals(username)).toList();
}
public Post createPost(PostRequest postRequest, Principal principal) {
Post post = new Post();
post.setAnswered_post(post.getAnswered_post());
post.setAnswers(post.getAnswers());
post.setDate(new Date());
post.setEdited(false);
post.setLike(0);
post.setSender(principal.getName());
post.setText(postRequest.getText());
checkAnswers(post);
return postRepo.save(post);
}
public Post edit(PostRequest postRequest, long post_id, Principal principal) {
Post post = postRepo.findById(post_id).orElseThrow(
new PostNotFoundException("Post with id " + post_id + " didnt exists"));
post.setEdited(true);
post.setSender(principal.getName());
post.setText(postRequest.getText());
checkAnswers(post);
return postRepo.save(post);
}
public void delete(Post post) {
postRepo.delete(post);
}
public void checkAnswers(Post post) {
if(post.getAnswered_post() != null) {
Post answered = postRepo.findById(post.getAnswered_post()).orElseThrow(
new PostNotFoundException("Post didnt exists: " + post.getAnswered_post()));
Set<Long> answers = answered.getAnswers() != null ? answered.getAnswers() : new TreeSet<>();
answers.add(post.getId());
answered.setAnswers(answers);
new RepostEvent(answered.getSender(),
post.getSender(),
String.format("Пользователь %s ответил на вашу запись!", answered.getSender())).invoke();
postRepo.save(answered);
}
}
public Post addLike(Post post, Principal principal) {
if (post.getLiked_users().contains(principal.getName()))
throw new AlreadyLikedException(String.format("User %s already liked post %s", principal.getName(), post.getId()));
post.setLike(post.getLike() + 1);
Set<String> liked = post.getLiked_users() == null ? new TreeSet<>() : post.getLiked_users();
liked.add(principal.getName());
return postRepo.save(post);
}
public Post disLike(Post post, Principal principal) {
if (!post.getLiked_users().contains(principal.getName()))
throw new AlreadyLikedException(String.format("User %s already liked post %s", principal.getName(), post.getId()));
post.setLike(post.getLike() - 1);
Set<String> liked = post.getLiked_users() == null ? new TreeSet<>() : post.getLiked_users();
liked.remove(principal.getName());
return postRepo.save(post);
}
}
@@ -25,7 +25,7 @@ import java.util.stream.Collectors;
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/project") @RequestMapping("/projects")
@Tag(name = "Проекты", description = "контроллер для работы с проектами") @Tag(name = "Проекты", description = "контроллер для работы с проектами")
public class ProjectController { public class ProjectController {
private final ProjectService projectService; private final ProjectService projectService;
@@ -34,6 +34,20 @@ public class ProjectController {
private final ParticipantService participantService; private final ParticipantService participantService;
// new
//@
@GetMapping
@Operation(summary = "Получение всех проектов для пользователя")
public ResponseEntity<List<ProjectDto>> getAllProjects() {
List<ProjectDto> projects = projectService.getAllProjects()
.stream().map(project -> modelMapper.map(project, ProjectDto.class)).collect(Collectors.toList());
return ResponseEntity.ok().body(projects);
}
@PostMapping @PostMapping
@Operation(summary = "Создание проекта") @Operation(summary = "Создание проекта")
public ResponseEntity<Object> createProject(@Valid @RequestBody ProjectRequest projectRequest, public ResponseEntity<Object> createProject(@Valid @RequestBody ProjectRequest projectRequest,
@@ -46,6 +60,13 @@ public class ProjectController {
return ResponseEntity.ok().body(modelMapper.map(project, ProjectDto.class)); return ResponseEntity.ok().body(modelMapper.map(project, ProjectDto.class));
} }
//@
@GetMapping("/{projectId}")
@Operation(summary = "получение проекта по id")
public ResponseEntity<ProjectDto> getProject(@PathVariable("projectId") Long projectId) {
return ResponseEntity.ok().body(modelMapper.map(projectService.getProjectById(projectId), ProjectDto.class));
}
@PutMapping("/{projectId}") @PutMapping("/{projectId}")
@Operation(summary = "Изменение проекта") @Operation(summary = "Изменение проекта")
public ResponseEntity<Object> editProject(@Valid @RequestBody ProjectRequest projectRequest, public ResponseEntity<Object> editProject(@Valid @RequestBody ProjectRequest projectRequest,
@@ -59,6 +80,79 @@ public class ProjectController {
return ResponseEntity.ok().body(modelMapper.map(projectUpdated, ProjectDto.class)); return ResponseEntity.ok().body(modelMapper.map(projectUpdated, ProjectDto.class));
} }
//@
@DeleteMapping("/{projectId}")
@Operation(summary = "Удаление проекта")
public ResponseEntity<Object> deleteProject(@PathVariable("projectId") Long projectId,
Principal principal) {
projectService.deleteProject(projectId, principal);
return ResponseEntity.ok(new MessageResponse("Project was deleted!"));
}
//@
@GetMapping("/user/{userId}")
@Operation(summary = "Получение всех проектов для пользователя")
public ResponseEntity<List<ProjectDto>> getAllProjectsForUser(@PathVariable("userId") Long userId) {
List<ProjectDto> projects = projectService.getAllProjectsForUser(userId)
.stream().map(project -> modelMapper.map(project, ProjectDto.class)).collect(Collectors.toList());
return ResponseEntity.ok().body(projects);
}
@GetMapping("/requests")
@Operation(summary = "получение всех проектов для текущего пользователя")
public ResponseEntity<List<ProjectDto>> getAllProjectsForCurrentUser(Principal principal) {
List<ProjectDto> projects = projectService.getAllProjectsForCurrentUser(principal)
.stream().map(project -> modelMapper.map(project, ProjectDto.class)).collect(Collectors.toList());
return ResponseEntity.ok().body(projects);
}
//@
@GetMapping("/{projectId}/requests")
@Operation(summary = "получение всех поданных заявок на проект")
public ResponseEntity<List<ParticipantDto>> getAllRequestsForProject(@PathVariable Long projectId) {
List<ParticipantDto> requests = projectService.getAllRequestsForProject(projectId)
.stream().map(project -> modelMapper.map(project, ParticipantDto.class)).collect(Collectors.toList());
return ResponseEntity.ok().body(requests);
}
//@
@PostMapping("/requests")
@Operation(summary = "утвердить участника на проект")
public ResponseEntity<ProjectDto> confirmParticipant(
@RequestBody ParticipantRequest participantRequest,
Principal principal) {
Project project;
if(participantRequest.isApproved())
project = projectService.confirmParticipant(participantRequest.getProjectId(),
participantRequest.getNameOfPosition(),
participantRequest.getParticipantId(),
principal);
else {
project = projectService.rejectParticipant(participantRequest.getProjectId(),
participantRequest.getNameOfPosition(),
participantRequest.getParticipantId(),
principal);
}
return ResponseEntity.ok().body(modelMapper.map(project, ProjectDto.class));
}
// old
//@
//@
//@
@PutMapping("/{projectId}/{partId}/part") @PutMapping("/{projectId}/{partId}/part")
@Operation(summary = "Изменение позиции в проекте: Дизайнер/Ui designer") @Operation(summary = "Изменение позиции в проекте: Дизайнер/Ui designer")
public ResponseEntity<Object> editPart(@Valid @RequestBody ParticipantDto participantDto, public ResponseEntity<Object> editPart(@Valid @RequestBody ParticipantDto participantDto,
@@ -74,29 +168,17 @@ public class ProjectController {
} }
@DeleteMapping("/{projectId}")
@Operation(summary = "Удаление проекта")
public ResponseEntity<Object> deleteProject(@PathVariable("projectId") Long projectId,
Principal principal) {
projectService.deleteProject(projectId, principal);
return ResponseEntity.ok(new MessageResponse("Project was deleted!"));
}
@GetMapping("/{projectId}")
@Operation(summary = "получение проекта по id")
public ResponseEntity<ProjectDto> getProject(@PathVariable("projectId") Long projectId) {
return ResponseEntity.ok().body(modelMapper.map(projectService.getProjectById(projectId), ProjectDto.class));
}
//
@GetMapping("/{userId}/all")
@Operation(summary = "Получение всех проектов для пользователя")
public ResponseEntity<List<ProjectDto>> getAllProjectsForUser(@PathVariable("userId") Long userId) {
List<ProjectDto> projects = projectService.getAllProjectsForUser(userId)
.stream().map(project -> modelMapper.map(project, ProjectDto.class)).collect(Collectors.toList());
return ResponseEntity.ok().body(projects);
}
//@
@GetMapping("/{technology}/tech") @GetMapping("/{technology}/tech")
@Operation(summary = "Получение всех проектов с опредлененной технологией") @Operation(summary = "Получение всех проектов с опредлененной технологией")
public ResponseEntity<List<ProjectDto>> getAllProjectsWithTechnology(@PathVariable("technology") String technology) { public ResponseEntity<List<ProjectDto>> getAllProjectsWithTechnology(@PathVariable("technology") String technology) {
@@ -105,15 +187,9 @@ public class ProjectController {
return ResponseEntity.ok().body(projects); return ResponseEntity.ok().body(projects);
} }
@GetMapping("/my")
@Operation(summary = "получение всех проектов для текущего пользователя")
public ResponseEntity<List<ProjectDto>> getAllProjectsForCurrentUser(Principal principal) {
List<ProjectDto> projects = projectService.getAllProjectsForCurrentUser(principal)
.stream().map(project -> modelMapper.map(project, ProjectDto.class)).collect(Collectors.toList());
return ResponseEntity.ok().body(projects);
}
//@
@GetMapping("/{nameOfPosition}/positions") @GetMapping("/{nameOfPosition}/positions")
@Operation(summary = "Получение всех проектов с указанной позицией : Дизайнер") @Operation(summary = "Получение всех проектов с указанной позицией : Дизайнер")
public ResponseEntity<List<ProjectDto>> getAllProjectsWithPosition(@PathVariable("nameOfPosition") String nameOfPosition) { public ResponseEntity<List<ProjectDto>> getAllProjectsWithPosition(@PathVariable("nameOfPosition") String nameOfPosition) {
@@ -122,6 +198,7 @@ public class ProjectController {
return ResponseEntity.ok().body(projects); return ResponseEntity.ok().body(projects);
} }
//@
@GetMapping("/{commercialStatus}/commercial_status") @GetMapping("/{commercialStatus}/commercial_status")
@Operation(summary = "получение всех проектов по коммерческому статусу") @Operation(summary = "получение всех проектов по коммерческому статусу")
public ResponseEntity<List<ProjectDto>> getAllProjectsWithCommercialStatus(@PathVariable("commercialStatus") int commercialStatus) { public ResponseEntity<List<ProjectDto>> getAllProjectsWithCommercialStatus(@PathVariable("commercialStatus") int commercialStatus) {
@@ -130,14 +207,9 @@ public class ProjectController {
return ResponseEntity.ok().body(projects); return ResponseEntity.ok().body(projects);
} }
@GetMapping("/requests")
@Operation(summary = "получение всех поданных заявок на проект")
public ResponseEntity<List<ParticipantDto>> getAllRequestsForProject(@RequestBody Long projectId) {
List<ParticipantDto> requests = projectService.getAllRequestsForProject(projectId)
.stream().map(project -> modelMapper.map(project, ParticipantDto.class)).collect(Collectors.toList());
return ResponseEntity.ok().body(requests);
}
//@
@PostMapping("/apply") @PostMapping("/apply")
@Operation(summary = "подать заявку на участие в проекте") @Operation(summary = "подать заявку на участие в проекте")
public ResponseEntity<ProjectDto> applyOnProject(@RequestBody ParticipantRequest participantRequest, public ResponseEntity<ProjectDto> applyOnProject(@RequestBody ParticipantRequest participantRequest,
@@ -147,15 +219,5 @@ public class ProjectController {
return ResponseEntity.ok().body(modelMapper.map(project, ProjectDto.class)); return ResponseEntity.ok().body(modelMapper.map(project, ProjectDto.class));
} }
@PostMapping("/participant")
@Operation(summary = "утвердить участница на проект")
public ResponseEntity<ProjectDto> confirmParticipant(@RequestBody ParticipantRequest participantRequest,
Principal principal) {
Project project = projectService.confirmParticipant(participantRequest.getProjectId(),
participantRequest.getNameOfPosition(),
participantRequest.getParticipantId(),
principal);
return ResponseEntity.ok().body(modelMapper.map(project, ProjectDto.class));
}
} }
@@ -16,24 +16,24 @@ import java.util.Objects;
public class Participant { public class Participant {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "participant_id") @Column(name = "participantId")
private Long participantId; private Long participantId;
@ManyToOne @ManyToOne
@JoinColumn(name = "project_id", updatable = false) @JoinColumn(name = "projectId", updatable = false)
private Project project; private Project project;
@Column(name = "name_of_position") @Column(name = "nameOfPosition")
@NotNull @NotNull
private String nameOfPosition; private String nameOfPosition;
@ManyToOne @ManyToOne
@JoinColumn(name = "user_id") @JoinColumn(name = "userId")
private User user; private User user;
@ManyToMany @ManyToMany
@JoinTable(name = "user_request", @JoinTable(name = "userRequest",
joinColumns = @JoinColumn(name = "participant_id"), joinColumns = @JoinColumn(name = "participantId"),
inverseJoinColumns = @JoinColumn(name = "user_id")) inverseJoinColumns = @JoinColumn(name = "userId"))
@ToString.Exclude @ToString.Exclude
private List<User> requests; private List<User> requests;
@@ -2,7 +2,6 @@ package site.easystartup.web.project.domain.model;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*; import lombok.*;
import org.hibernate.Hibernate;
import site.easystartup.web.domain.model.User; import site.easystartup.web.domain.model.User;
import javax.persistence.*; import javax.persistence.*;
@@ -10,7 +9,6 @@ import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.Objects;
@Data @Data
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -19,10 +17,10 @@ import java.util.Objects;
public class Project { public class Project {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "project_id") @Column(name = "projectId")
private Long projectId; private Long projectId;
@Column(name = "cover_link") @Column(name = "coverLink")
private String coverLink; private String coverLink;
@Column(name = "title") @Column(name = "title")
@@ -35,26 +33,25 @@ public class Project {
@NotNull @NotNull
private String description; private String description;
@Column(name = "commercial_status") // 1 - commercial, 0 - non-commercial @Column(name = "commercialStatus") // 1 - commercial, 0 - non-commercial
private int commercialStatus; private int commercialStatus;
@ManyToMany @ManyToMany
@JoinTable(name = "project_tag", @JoinTable(name = "projectTag",
joinColumns = @JoinColumn(name = "project_id"), joinColumns = @JoinColumn(name = "projectId"),
inverseJoinColumns = @JoinColumn(name = "tag_id") inverseJoinColumns = @JoinColumn(name = "technologyId")
) )
@ToString.Exclude private List<Technology> technology;
private List<Tag> technology;
@ManyToOne @ManyToOne
@JoinColumn(name = "owner_id", updatable = false) @JoinColumn(name = "ownerId", updatable = false)
private User owner; private User owner;
@OneToMany(mappedBy = "project", cascade = {CascadeType.ALL}) @OneToMany(mappedBy = "project", cascade = {CascadeType.ALL})
// @ToString.Exclude // @ToString.Exclude
private List<Participant> participants; private List<Participant> participants;
@Column(name = "created_date", updatable = false) @Column(name = "createdDate", updatable = false)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createdDate; private LocalDateTime createdDate;
@@ -13,25 +13,24 @@ import java.util.Set;
@RequiredArgsConstructor @RequiredArgsConstructor
@Entity @Entity
@Table(name = "tag") @Table(name = "tag")
public class Tag { public class Technology {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "tag_id") @Column(name = "technologyId")
private Long tagId; private Long technologyId;
@Column(name = "tage_name") @Column(name = "technologyName")
private String tagName; private String technologyName;
@ManyToMany(mappedBy = "technology") @ManyToMany(mappedBy = "technology")
@ToString.Exclude
private Set<Project> projects; private Set<Project> projects;
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
Tag tag = (Tag) o; Technology technology = (Technology) o;
return tagId != null && Objects.equals(tagId, tag.tagId); return technologyId != null && Objects.equals(technologyId, technology.technologyId);
} }
@Override @Override
@@ -9,4 +9,5 @@ public class ParticipantRequest {
private Long projectId; private Long projectId;
private Long participantId; private Long participantId;
private String nameOfPosition; private String nameOfPosition;
private boolean approved;
} }
@@ -2,9 +2,7 @@ package site.easystartup.web.project.domain.requst;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor; import site.easystartup.web.project.domain.model.Technology;
import org.springframework.web.multipart.MultipartFile;
import site.easystartup.web.project.domain.model.Tag;
import site.easystartup.web.project.dto.ParticipantDto; import site.easystartup.web.project.dto.ParticipantDto;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@@ -25,6 +23,6 @@ public class ProjectRequest {
private String description; private String description;
private int commercialStatus; private int commercialStatus;
@NotNull @NotNull
private List<Tag> technology; private List<Technology> technology;
private List<ParticipantDto> participants; private List<ParticipantDto> participants;
} }
@@ -1,6 +1,5 @@
package site.easystartup.web.project.dto; package site.easystartup.web.project.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
@@ -14,7 +14,7 @@ public class UserDto implements Serializable {
private String username; private String username;
private String password; private String password;
private boolean active; private boolean active;
private String full_name; private String fullName;
private String status; private String status;
private String iconPath; private String iconPath;
private String email; private String email;
@@ -1,12 +1,10 @@
package site.easystartup.web.project.repo; package site.easystartup.web.project.repo;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import site.easystartup.web.domain.model.User; import site.easystartup.web.domain.model.User;
import site.easystartup.web.project.domain.model.Project; import site.easystartup.web.project.domain.model.Project;
import site.easystartup.web.project.domain.model.Tag; import site.easystartup.web.project.domain.model.Technology;
import java.util.List; import java.util.List;
@@ -14,7 +12,7 @@ import java.util.List;
public interface ProjectRepo extends JpaRepository<Project, Long> { public interface ProjectRepo extends JpaRepository<Project, Long> {
List<Project> findAllByOwnerOrderByCreatedDate(User owner); List<Project> findAllByOwnerOrderByCreatedDate(User owner);
List<Project> findAllByTechnology(Tag tag); List<Project> findAllByTechnology(Technology technology);
List<Project> findAllByCommercialStatusOrderByCreatedDateAsc(int commercialStatus); List<Project> findAllByCommercialStatusOrderByCreatedDateAsc(int commercialStatus);
@@ -1,13 +0,0 @@
package site.easystartup.web.project.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import site.easystartup.web.project.domain.model.Tag;
import java.util.Optional;
@Repository
public interface TagRepo extends JpaRepository<Tag, Long> {
Optional<Tag> findTagByTagNameIgnoreCase(String tagName);
}
@@ -0,0 +1,13 @@
package site.easystartup.web.project.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import site.easystartup.web.project.domain.model.Technology;
import java.util.Optional;
@Repository
public interface TechnologyRepo extends JpaRepository<Technology, Long> {
Optional<Technology> findTechnologyByTechnologyName(String technologyName);
}
@@ -15,7 +15,6 @@ import site.easystartup.web.storage.service.StorageService;
import java.security.Principal; import java.security.Principal;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -25,7 +24,7 @@ public class ProjectService {
private final ModelMapper modelMapper; private final ModelMapper modelMapper;
private final StorageService storageService; private final StorageService storageService;
private final ParticipantRepo participantRepo; private final ParticipantRepo participantRepo;
private final TagService tagService; private final TechnologyService technologyService;
@@ -79,8 +78,12 @@ public class ProjectService {
return projectRepo.findAllByOwnerOrderByCreatedDate(user); return projectRepo.findAllByOwnerOrderByCreatedDate(user);
} }
public List<Project> getAllProjects() {
return projectRepo.findAll();
}
public List<Project> getAllProjectsWithTechnology(String technology) { public List<Project> getAllProjectsWithTechnology(String technology) {
return projectRepo.findAllByTechnology(tagService.getTechnologyByName(technology.trim())); return projectRepo.findAllByTechnology(technologyService.getTechnologyByName(technology.trim()));
} }
public List<Project> getAllProjectsForCurrentUser(Principal principal) { public List<Project> getAllProjectsForCurrentUser(Principal principal) {
@@ -127,12 +130,28 @@ public class ProjectService {
return projectRepo.save(project); return projectRepo.save(project);
} }
public Project rejectParticipant(Long projectId, String nameOfPosition, Long participantId, Principal principal) {
Project project = getProjectById(projectId);
if (!projectIsBelongUser(project, principal))
throw new RuntimeException("This project cannot be changed");
User user = userService.getUserById(participantId);
project.getParticipants().forEach(participant -> {
if (participant.getNameOfPosition().equals(nameOfPosition)) {
participant.getRequests().remove(user);
}
});
projectRepo.save(project);
return projectRepo.save(project);
}
private Project projectRequestToProject(ProjectRequest projectRequest, Principal principal) { private Project projectRequestToProject(ProjectRequest projectRequest, Principal principal) {
Project project = new Project(); Project project = new Project();
project.setTitle(projectRequest.getTitle()); project.setTitle(projectRequest.getTitle());
project.setDescription(projectRequest.getDescription()); project.setDescription(projectRequest.getDescription());
project.setTechnology(tagService.convertTechnology(projectRequest.getTechnology())); project.setTechnology(technologyService.convertTechnology(projectRequest.getTechnology()));
project.setCommercialStatus(project.getCommercialStatus()); project.setCommercialStatus(project.getCommercialStatus());
// project.setCoverLink(projectRequest.getCover().getName()); // project.setCoverLink(projectRequest.getCover().getName());
project.setOwner(userService.getUserByPrincipal(principal)); project.setOwner(userService.getUserByPrincipal(principal));
@@ -1,38 +0,0 @@
package site.easystartup.web.project.service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import site.easystartup.web.project.domain.model.Tag;
import site.easystartup.web.project.repo.TagRepo;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class TagService {
private final TagRepo tagRepo;
public List<Tag> getAllTags() {
return tagRepo.findAll();
}
public List<Tag> convertTechnology(List<Tag> technology) {
List<Tag> tags = new ArrayList<>();
technology.forEach(tag -> {
Optional<Tag> foundTag = tagRepo.findTagByTagNameIgnoreCase(tag.getTagName());
if (foundTag.isPresent()) {
tags.add(foundTag.get());
}
else {
tagRepo.save(tag);
tags.add(tagRepo.findTagByTagNameIgnoreCase(tag.getTagName()).get());
}
});
return tags;
}
public Tag getTechnologyByName(String tag) {
return tagRepo.findTagByTagNameIgnoreCase(tag).orElseThrow(() -> new RuntimeException("Technolohy not found"));
}
}
@@ -0,0 +1,38 @@
package site.easystartup.web.project.service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import site.easystartup.web.project.domain.model.Technology;
import site.easystartup.web.project.repo.TechnologyRepo;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class TechnologyService {
private final TechnologyRepo technologyRepo;
public List<Technology> getAllTags() {
return technologyRepo.findAll();
}
public List<Technology> convertTechnology(List<Technology> technology) {
List<Technology> technologies = new ArrayList<>();
technology.forEach(tag -> {
Optional<Technology> foundTag = technologyRepo.findTechnologyByTechnologyName(tag.getTechnologyName());
if (foundTag.isPresent()) {
technologies.add(foundTag.get());
}
else {
technologyRepo.save(tag);
technologies.add(technologyRepo.findTechnologyByTechnologyName(tag.getTechnologyName()).get());
}
});
return technologies;
}
public Technology getTechnologyByName(String tag) {
return technologyRepo.findTechnologyByTechnologyName(tag).orElseThrow(() -> new RuntimeException("Technolohy not found"));
}
}
@@ -9,7 +9,9 @@ import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
@Data @Data
@@ -17,8 +19,7 @@ public class UserRequest {
@NotNull @NotNull
private boolean active; private boolean active;
@NotNull private String fullName;
private String full_name;
@Size(max = 60, message = "Status should be no more 60 signs") @Size(max = 60, message = "Status should be no more 60 signs")
private String status; private String status;
@@ -29,9 +30,18 @@ public class UserRequest {
@NotBlank(message = "Email is required") @NotBlank(message = "Email is required")
private String email; private String email;
private Set<String> tags; private Set<String> technologies;
private Set<String> professions; private Set<String> professions;
private Set<Long> projects; private Set<Long> projects;
private List<Participant> requests; private List<Participant> requests;
private Set<Role> roles; private Set<Role> roles;
@Size(max = 1000, message = "Status should be no more 1000 signs")
private String about;
@Size(max = 100, message = "Status should be no more 100 signs")
private String country;
@Size(max = 100, message = "Status should be no more 100 signs")
private String city;
private String birthday;
private Set<String> languages;
private Map<String, String> contacts;
} }
@@ -5,6 +5,7 @@ import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
@@ -36,6 +37,7 @@ public class JWTFilter extends OncePerRequestFilter {
} else { } else {
try { try {
String email = jwtUtil.validateTokenAndRetrieveClaim(jwt); String email = jwtUtil.validateTokenAndRetrieveClaim(jwt);
UserDetails userDetails = userDetailService.loadUserByUsername(email); UserDetails userDetails = userDetailService.loadUserByUsername(email);
UsernamePasswordAuthenticationToken authenticationToken = UsernamePasswordAuthenticationToken authenticationToken =
@@ -48,7 +50,7 @@ public class JWTFilter extends OncePerRequestFilter {
} }
} catch (JWTVerificationException ex) { } catch (JWTVerificationException ex) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, " Invalid JWT token"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, " Invalid JWT token");
} } catch(UsernameNotFoundException ignored) {} //TODO untag this filter from signup request
} }
} }
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
@@ -34,4 +34,6 @@ public class JWTUtil {
return decodedJWT.getClaim("username").asString(); return decodedJWT.getClaim("username").asString();
} }
} }
@@ -33,29 +33,18 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
// http http.cors().and().csrf().disable()
// .authorizeRequests() .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
// .antMatchers("/swagger-ui.html").permitAll() .and()
// .antMatchers("/swagger-ui/index.html").permitAll() .sessionManagement()
// .antMatchers("/webjars/**").permitAll() .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// .antMatchers("/swagger-resources/**").permitAll() .and()
// .antMatchers("/v3/*").permitAll() .authorizeRequests()
// .antMatchers("/csrf").permitAll() .antMatchers(SecurityConstants.SIGN_UP_URLS).permitAll()
// .antMatchers("/").permitAll() .anyRequest().authenticated().and()
// .and() .antMatcher("/auth/*").anonymous();
http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
// .cors().and().csrf().disable()
// .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
// .and()
// .sessionManagement()
// .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// .and()
// .authorizeRequests()
// .antMatchers(SecurityConstants.SIGN_UP_URLS).permitAll()
// .anyRequest().authenticated();
//
// http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
} }
@Bean @Bean
@@ -1,16 +1,16 @@
package site.easystartup.web.service; package site.easystartup.web.service;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import site.easystartup.web.domain.exception.UserExistException; import site.easystartup.web.domain.exception.UserExistException;
import site.easystartup.web.domain.model.Role; import site.easystartup.web.domain.model.Role;
import site.easystartup.web.domain.model.User; import site.easystartup.web.domain.model.User;
import site.easystartup.web.domain.request.SignupRequest; import site.easystartup.web.domain.request.SignupRequest;
import site.easystartup.web.domain.request.UpdatePassportRequest;
import site.easystartup.web.repo.UserRepo; import site.easystartup.web.repo.UserRepo;
import java.security.Principal; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
@@ -18,29 +18,24 @@ import java.util.Set;
@RequiredArgsConstructor @RequiredArgsConstructor
public class AuthService { public class AuthService {
private final UserRepo userRepo; private final UserRepo userRepo;
private final UserService userService;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
public User createUser(SignupRequest signupRequest) { public User createUser(SignupRequest signupRequest) {
boolean exists = false;
try {
if (userRepo.findUserByUsername(signupRequest.getUsername()).isPresent()) { if (userRepo.findUserByUsername(signupRequest.getUsername()).isPresent()) {
throw new UserExistException("An account with this username already exists."); exists = true;
} }
} catch (UsernameNotFoundException e) {}
if(exists) throw new UserExistException("An account with this username already exists.");
User user = new User(); User user = new User();
user.setEmail(signupRequest.getEmail()); user.setEmail(signupRequest.getEmail());
user.setUsername(signupRequest.getUsername()); user.setUsername(signupRequest.getUsername());
user.setPassword(passwordEncoder.encode(signupRequest.getPassword())); user.setPassword(passwordEncoder.encode(signupRequest.getPassword()));
Set<Role> roles = new HashSet<>(); user.setRoles(Collections.singleton(Role.USER));
signupRequest.getRoles().forEach(role -> roles.add(Role.valueOf(role))); user.setActive(true);
user.setRoles(roles);
return userRepo.save(user);
}
public User updatePassword(UpdatePassportRequest passportRequest, Principal principal) {
User user = userService.getUserByPrincipal(principal);
user.setPassword(passwordEncoder.encode(passportRequest.getPassword()));
return userRepo.save(user); return userRepo.save(user);
} }
} }
@@ -1,7 +1,6 @@
package site.easystartup.web.service; package site.easystartup.web.service;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
@@ -12,7 +11,7 @@ import site.easystartup.web.request.UserRequest;
import site.easystartup.web.storage.service.StorageService; import site.easystartup.web.storage.service.StorageService;
import java.security.Principal; import java.security.Principal;
import java.util.TreeSet; import java.util.Collections;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -22,6 +21,7 @@ public class UserService {
private final StorageService storageService; private final StorageService storageService;
public User getUserByPrincipal(Principal principal) { public User getUserByPrincipal(Principal principal) {
if(principal == null) return getCurrent();
return userRepo.findByUsername(principal.getName()); return userRepo.findByUsername(principal.getName());
} }
@@ -29,6 +29,11 @@ public class UserService {
return userRepo.findById(userId).orElseThrow(() -> new UsernameNotFoundException("User not found")); return userRepo.findById(userId).orElseThrow(() -> new UsernameNotFoundException("User not found"));
} }
public boolean userExists(String username) {
return userRepo.findUserByUsername(username).isPresent();
}
public User getUserByUsername(String username) { public User getUserByUsername(String username) {
return userRepo.findUserByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found")); return userRepo.findUserByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found"));
} }
@@ -36,17 +41,27 @@ public class UserService {
public User editUser(String username, UserRequest userRequest) { public User editUser(String username, UserRequest userRequest) {
User user = userRepo.findByUsername(username); User user = userRepo.findByUsername(username);
user.setActive(userRequest.isActive()); user.setActive(userRequest.isActive());
user.setFull_name(userRequest.getFull_name()); user.setFullName(userRequest.getFullName());
user.setStatus(userRequest.getStatus()); user.setStatus(userRequest.getStatus());
if(userRequest.getIcon() != null) storageService.saveImage(userRequest.getIcon(), username + "-icon"); if(userRequest.getIcon() != null) storageService.saveImage(userRequest.getIcon(), username + "-icon");
user.setIconPath(user.getIconPath() == null ? user.getIconPath() : username + "-icon.jpg"); user.setIconPath(user.getIconPath() == null ? "" : username + "-icon.jpg");
user.setEmail(userRequest.getEmail() == null ? "" : userRequest.getEmail());
user.setEmail(userRequest.getEmail() == null ? user.getEmail() : userRequest.getEmail()); user.setTechnologies(userRequest.getTechnologies() == null ? Collections.emptySet() : userRequest.getTechnologies());
user.setTags(userRequest.getTags() == null ? user.getTags() : userRequest.getTags()); user.setProfessions(userRequest.getProfessions() == null ? Collections.emptySet() : userRequest.getProfessions());
user.setProfessions(userRequest.getProfessions() == null ? user.getProfessions() : userRequest.getProfessions()); user.setProjects(userRequest.getProjects() == null ? Collections.emptySet() : userRequest.getProjects());
user.setProjects(userRequest.getProjects() == null ? user.getProjects() : userRequest.getProjects()); user.setRequests(userRequest.getRequests() == null ? Collections.emptyList() : userRequest.getRequests());
user.setRequests(userRequest.getRequests() == null ? user.getRequests() : userRequest.getRequests()); user.setAbout(userRequest.getAbout() == null ? "" : userRequest.getAbout());
user.setCountry(userRequest.getCountry() == null ? "" : userRequest.getCountry());
user.setCity(userRequest.getCity() == null ? "" : userRequest.getCity());
user.setLanguages(userRequest.getLanguages() == null ? Collections.emptySet() : userRequest.getLanguages());
user.setContacts(userRequest.getContacts() == null ? Collections.emptyMap() : userRequest.getContacts());
return userRepo.save(user); return userRepo.save(user);
} }
public User getCurrent() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String login = authentication.getName();
return getUserByUsername(login);
}
} }
@@ -25,7 +25,8 @@ public class FileUploadController {
this.storageService = storageService; this.storageService = storageService;
} }
@GetMapping("/upload") //@
@GetMapping("/files/upload")
public String listUploadedFiles(Model model) { public String listUploadedFiles(Model model) {
if(storageService.loadAll() == null) { if(storageService.loadAll() == null) {
model.addAttribute("message", model.addAttribute("message",
@@ -43,13 +44,15 @@ public class FileUploadController {
@SneakyThrows @SneakyThrows
@GetMapping("/files/{filename:.+}") @GetMapping("/files/{filename:.+}")
@ResponseBody @ResponseBody
//@
public ResponseEntity<Resource> serveFile(@PathVariable String filename) { public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
Resource file = storageService.load(filename); Resource file = storageService.load(filename);
return ResponseEntity.ok() return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file);
} }
@PostMapping("/upload") @PostMapping("/files/upload")
//@
public String handleFileUpload(@RequestParam("file") MultipartFile file, public String handleFileUpload(@RequestParam("file") MultipartFile file,
Model model) { Model model) {
storageService.save(file); storageService.save(file);
@@ -1,11 +1,14 @@
package site.easystartup.web.storage.service; package site.easystartup.web.storage.service;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource; import org.springframework.core.io.UrlResource;
import org.springframework.util.FileSystemUtils; import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import java.io.IOException; import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.nio.file.Files; import java.nio.file.Files;
@@ -14,7 +17,10 @@ import java.nio.file.Paths;
import java.util.stream.Stream; import java.util.stream.Stream;
public class FileLocalStorageService implements StorageService { public class FileLocalStorageService implements StorageService {
private final Path root = Paths.get("uploads"); @Autowired
ServletContext context;
private final Path root = Path.of(new FileSystemResource("").getFile().getAbsolutePath());
public FileLocalStorageService() { public FileLocalStorageService() {
init(); init();
@@ -0,0 +1,21 @@
package site.easystartup.web.util;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import site.easystartup.web.service.UserService;
@Configuration
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class FastChecksUtil {
private final UserService userService;
public<T> ResponseEntity<T> nullIfValid(String user) {
if(!userService.userExists(user)) {
return ResponseEntity.notFound().build();
}
return null;
}
}
+10 -4
View File
@@ -4,9 +4,15 @@ spring.jpa.hibernate.ddl-auto=update
spring.sql.init.mode=always spring.sql.init.mode=always
spring.sql.init.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/testdb #spring.sql.init.platform=postgres
spring.datasource.username=postgres #spring.datasource.url=jdbc:postgresql://localhost:5432/testdb
spring.datasource.password=root #spring.datasource.username=postgres
#spring.datasource.password=root
spring.datasource.url=jdbc:mysql://mysql.joinserver.xyz:3306/s45925_test
spring.datasource.username=u45925_MqxGXdRT8T
spring.datasource.password=K=9KkskkTa3.IAW!fkJx95JE
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.security.filter.order=10 spring.security.filter.order=10
+5
View File
@@ -0,0 +1,5 @@
<html>
<body>
<p>API</p>
</body>
</html>
-30
View File
@@ -1,30 +0,0 @@
const connect = () => {
const Stomp = require("stompjs");
var SockJS = require("sockjs-client");
SockJS = new SockJS("http://localhost:8080/ws");
stompClient = Stomp.over(SockJS);
stompClient.connect({}, onConnected, onError);
};
const onConnected = () => {
console.log("connected");
stompClient.subscribe(
"/user/" + currentUser.id + "/queue/messages",
onMessageReceived
);
};
const sendMessage = (msg) => {
if (msg.trim() !== "") {
const message = {
senderId: currentUser.id,
recipientId: activeContact.id,
senderName: currentUser.name,
recipientName: activeContact.name,
content: msg,
};
stompClient.send("/app/chat", {}, JSON.stringify(message));
}
};
Whitespace-only changes.
+15
View File
@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>k</title>
</head>
<body>
<h1>API</h1>
</body>
</html>
Binary file not shown.
@@ -50,7 +50,7 @@ public class ProjectServiceTests {
ProjectRequest projectRequest = new ProjectRequest(); ProjectRequest projectRequest = new ProjectRequest();
projectRequest.setDescription("testDesc"); projectRequest.setDescription("testDesc");
projectRequest.setTitle("testTitle"); projectRequest.setTitle("testTitle");
projectRequest.setCover(file); //projectRequest.setCover(file);
projectRequest.setTechnology(new ArrayList<>()); projectRequest.setTechnology(new ArrayList<>());
project = projectService.createProject(projectRequest, principal); project = projectService.createProject(projectRequest, principal);
} }