commit
This commit is contained in:
1 parent
ff67f31cf3
commit
cc068fc3a8
26 files changed
+104
-519
No files matched your search
@@ -20,6 +20,7 @@ repositories {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springdoc:springdoc-openapi-ui:1.6.9'
|
||||
implementation 'com.google.code.gson:gson:2.9.0'
|
||||
implementation 'com.auth0:java-jwt:4.0.0'
|
||||
implementation 'org.springframework:spring-websocket:5.3.22'
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
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.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@SpringBootApplication
|
||||
@SecurityScheme(type = SecuritySchemeType.OAUTH2, name = "api_key", in = SecuritySchemeIn.HEADER)
|
||||
public class EasyStartupApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
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 org.modelmapper.ModelMapper;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -16,6 +18,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
import site.easystartup.web.domain.model.User;
|
||||
import site.easystartup.web.domain.request.LoginRequest;
|
||||
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.SuccessAuthenticationResponse;
|
||||
import site.easystartup.web.domain.validation.ResponseErrorValidation;
|
||||
@@ -26,10 +29,12 @@ import site.easystartup.web.service.AuthService;
|
||||
import site.easystartup.web.service.UserService;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.security.Principal;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "Авторизация")
|
||||
public class AuthController {
|
||||
private final JWTUtil jwtUtil;
|
||||
private final UserService userService;
|
||||
@@ -39,6 +44,7 @@ public class AuthController {
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
@PostMapping("/signup")
|
||||
@Operation(summary = "Создание нового аккаунта")
|
||||
public ResponseEntity<Object> registration(@Valid @RequestBody SignupRequest signupRequest,
|
||||
BindingResult bindingResult) {
|
||||
ResponseEntity<Object> errors = responseErrorValidation.mapValidationService(bindingResult);
|
||||
@@ -50,6 +56,7 @@ public class AuthController {
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
@Operation(summary = "Логин, получение JWT ключа и данных текущего пользователя")
|
||||
public ResponseEntity<Object> authentication(@Valid @RequestBody LoginRequest loginRequest,
|
||||
BindingResult bindingResult) {
|
||||
ResponseEntity<Object> errors = responseErrorValidation.mapValidationService(bindingResult);
|
||||
@@ -68,5 +75,28 @@ public class AuthController {
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package site.easystartup.web.domain.request;
|
||||
|
||||
import lombok.Data;
|
||||
import site.easystartup.web.domain.annotation.PasswordMatches;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
@Data
|
||||
@PasswordMatches
|
||||
public class UpdatePassportRequest {
|
||||
@NotEmpty(message = "Password is required")
|
||||
@Size(min = 6, max = 30, message = "Password should be no less 6 and no more 30 signs")
|
||||
private String password;
|
||||
|
||||
private String confirmPassword;
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
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.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);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package site.easystartup.web.notification.domian;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class Notification {
|
||||
private String text;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
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 {
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package site.easystartup.web.notification.event;
|
||||
|
||||
public interface NotificationEvent {
|
||||
void invoke();
|
||||
|
||||
String getRecipient();
|
||||
|
||||
String getMessage();
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package site.easystartup.web.notification.event;
|
||||
|
||||
public interface NotificationListener {
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
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.service.NotificationService;
|
||||
import site.easystartup.web.post.domain.event.RepostEvent;
|
||||
|
||||
@RequiredArgsConstructor(onConstructor_ = @Autowired)
|
||||
public class RealTimeListener implements NotificationListener {
|
||||
private final NotificationService notificationService;
|
||||
|
||||
//Обрабатывает все ивенты
|
||||
@EventHandler
|
||||
public void onEvent(NotificationEvent event) {
|
||||
notificationService.sendNotification(
|
||||
new Notification(event.getMessage()));
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
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.notification.domian.Notification;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor(onConstructor_ = @Autowired)
|
||||
public class NotificationService {
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
|
||||
public void sendNotification(Notification notification) {
|
||||
messagingTemplate.convertAndSendToUser("server", "queue/notification", notification);
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
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, PostRequest.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);
|
||||
}
|
||||
|
||||
@GetMapping("/{post_id}/edit/")
|
||||
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, PostRequest.class));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{post_id}/delete")
|
||||
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("/{post_id}/like/")
|
||||
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("/{post_id}/dislike/")
|
||||
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));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package site.easystartup.web.post.domain.exception;
|
||||
|
||||
public class AlreadyLikedException extends RuntimeException {
|
||||
public AlreadyLikedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package site.easystartup.web.post.domain.exception;
|
||||
|
||||
public class DontLickedException extends RuntimeException{
|
||||
public DontLickedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
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 javax.persistence.*;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@RequiredArgsConstructor
|
||||
@Entity
|
||||
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;
|
||||
private long like;
|
||||
|
||||
@ElementCollection(targetClass = Long.class, fetch = FetchType.EAGER)
|
||||
@CollectionTable(name = "post_answers", joinColumns = @JoinColumn(name = "post_id"))
|
||||
private List<Long> answers;
|
||||
|
||||
@ElementCollection(targetClass = Long.class, fetch = FetchType.EAGER)
|
||||
@CollectionTable(name = "post_licked_users", joinColumns = @JoinColumn(name = "post_id"))
|
||||
private List<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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
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> liked_users;
|
||||
private long like;
|
||||
private List<Long> answers;
|
||||
private long answered_post;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
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> {
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
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.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@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()));
|
||||
List<Long> answers = answered.getAnswers() != null ? answered.getAnswers() : new ArrayList<>();
|
||||
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);
|
||||
List<String> liked = post.getLiked_users() == null ? new ArrayList<>() : 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);
|
||||
List<String> liked = post.getLiked_users() == null ? new ArrayList<>() : post.getLiked_users();
|
||||
liked.remove(principal.getName());
|
||||
return postRepo.save(post);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package site.easystartup.web.project.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -24,6 +26,7 @@ import java.util.stream.Collectors;
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/project")
|
||||
@Tag(name = "Проекты", description = "контроллер для работы с проектами")
|
||||
public class ProjectController {
|
||||
private final ProjectService projectService;
|
||||
private final ResponseErrorValidation responseErrorValidation;
|
||||
@@ -32,6 +35,7 @@ public class ProjectController {
|
||||
private final ParticipantService participantService;
|
||||
|
||||
@PostMapping
|
||||
@Operation(summary = "Создание проекта")
|
||||
public ResponseEntity<Object> createProject(@Valid @RequestBody ProjectRequest projectRequest,
|
||||
BindingResult bindingResult,
|
||||
Principal principal) {
|
||||
@@ -43,6 +47,7 @@ public class ProjectController {
|
||||
}
|
||||
|
||||
@PutMapping("/{projectId}")
|
||||
@Operation(summary = "Изменение проекта")
|
||||
public ResponseEntity<Object> editProject(@Valid @RequestBody ProjectRequest projectRequest,
|
||||
@PathVariable("projectId") Long projectId,
|
||||
BindingResult bindingResult,
|
||||
@@ -55,6 +60,7 @@ public class ProjectController {
|
||||
}
|
||||
|
||||
@PutMapping("/{projectId}/{partId}/part")
|
||||
@Operation(summary = "Изменение позиции в проекте: Дизайнер/Ui designer")
|
||||
public ResponseEntity<Object> editPart(@Valid @RequestBody ParticipantDto participantDto,
|
||||
@PathVariable("projectId") Long projectId,
|
||||
@PathVariable("partId") Long partId,
|
||||
@@ -69,6 +75,7 @@ public class ProjectController {
|
||||
|
||||
|
||||
@DeleteMapping("/{projectId}")
|
||||
@Operation(summary = "Удаление проекта")
|
||||
public ResponseEntity<Object> deleteProject(@PathVariable("projectId") Long projectId,
|
||||
Principal principal) {
|
||||
projectService.deleteProject(projectId, principal);
|
||||
@@ -76,12 +83,14 @@ public class ProjectController {
|
||||
}
|
||||
|
||||
@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());
|
||||
@@ -89,6 +98,7 @@ public class ProjectController {
|
||||
}
|
||||
|
||||
@GetMapping("/{technology}/tech")
|
||||
@Operation(summary = "Получение всех проектов с опредлененной технологией")
|
||||
public ResponseEntity<List<ProjectDto>> getAllProjectsWithTechnology(@PathVariable("technology") String technology) {
|
||||
List<ProjectDto> projects = projectService.getAllProjectsWithTechnology(technology)
|
||||
.stream().map(project -> modelMapper.map(project, ProjectDto.class)).collect(Collectors.toList());
|
||||
@@ -96,6 +106,7 @@ public class ProjectController {
|
||||
}
|
||||
|
||||
@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());
|
||||
@@ -104,6 +115,7 @@ public class ProjectController {
|
||||
|
||||
|
||||
@GetMapping("/{nameOfPosition}/positions")
|
||||
@Operation(summary = "Получение всех проектов с указанной позицией : Дизайнер")
|
||||
public ResponseEntity<List<ProjectDto>> getAllProjectsWithPosition(@PathVariable("nameOfPosition") String nameOfPosition) {
|
||||
List<ProjectDto> projects = projectService.getAllProjectsWithPosition(nameOfPosition)
|
||||
.stream().map(project -> modelMapper.map(project, ProjectDto.class)).collect(Collectors.toList());
|
||||
@@ -111,6 +123,7 @@ public class ProjectController {
|
||||
}
|
||||
|
||||
@GetMapping("/{commercialStatus}/commercial_status")
|
||||
@Operation(summary = "получение всех проектов по коммерческому статусу")
|
||||
public ResponseEntity<List<ProjectDto>> getAllProjectsWithCommercialStatus(@PathVariable("commercialStatus") int commercialStatus) {
|
||||
List<ProjectDto> projects = projectService.getAllProjectsWithCommercialStatus(commercialStatus)
|
||||
.stream().map(project -> modelMapper.map(project, ProjectDto.class)).collect(Collectors.toList());
|
||||
@@ -118,6 +131,7 @@ public class ProjectController {
|
||||
}
|
||||
|
||||
@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());
|
||||
@@ -125,6 +139,7 @@ public class ProjectController {
|
||||
}
|
||||
|
||||
@PostMapping("/apply")
|
||||
@Operation(summary = "подать заявку на участие в проекте")
|
||||
public ResponseEntity<ProjectDto> applyOnProject(@RequestBody ParticipantRequest participantRequest,
|
||||
Principal principal) {
|
||||
Project project = projectService
|
||||
@@ -133,6 +148,7 @@ public class ProjectController {
|
||||
}
|
||||
|
||||
@PostMapping("/participant")
|
||||
@Operation(summary = "утвердить участница на проект")
|
||||
public ResponseEntity<ProjectDto> confirmParticipant(@RequestBody ParticipantRequest participantRequest,
|
||||
Principal principal) {
|
||||
Project project = projectService.confirmParticipant(participantRequest.getProjectId(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package site.easystartup.web.project.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
|
||||
@@ -33,18 +33,29 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.cors().and().csrf().disable()
|
||||
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
|
||||
.and()
|
||||
.sessionManagement()
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers(SecurityConstants.SIGN_UP_URLS).permitAll()
|
||||
// .antMatchers("/").permitAll();
|
||||
.anyRequest().authenticated();
|
||||
// http
|
||||
// .authorizeRequests()
|
||||
// .antMatchers("/swagger-ui.html").permitAll()
|
||||
// .antMatchers("/swagger-ui/index.html").permitAll()
|
||||
// .antMatchers("/webjars/**").permitAll()
|
||||
// .antMatchers("/swagger-resources/**").permitAll()
|
||||
// .antMatchers("/v3/*").permitAll()
|
||||
// .antMatchers("/csrf").permitAll()
|
||||
// .antMatchers("/").permitAll()
|
||||
// .and()
|
||||
|
||||
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
|
||||
|
||||
@@ -7,8 +7,10 @@ import site.easystartup.web.domain.exception.UserExistException;
|
||||
import site.easystartup.web.domain.model.Role;
|
||||
import site.easystartup.web.domain.model.User;
|
||||
import site.easystartup.web.domain.request.SignupRequest;
|
||||
import site.easystartup.web.domain.request.UpdatePassportRequest;
|
||||
import site.easystartup.web.repo.UserRepo;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -16,6 +18,7 @@ import java.util.Set;
|
||||
@RequiredArgsConstructor
|
||||
public class AuthService {
|
||||
private final UserRepo userRepo;
|
||||
private final UserService userService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public User createUser(SignupRequest signupRequest) {
|
||||
@@ -33,4 +36,11 @@ public class AuthService {
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user