Залутал отлично
This commit is contained in:
parent
bebea782c7
commit
4e50547d43
58
src/main/java/np/something/DTO/AlbumDto.java
Normal file
58
src/main/java/np/something/DTO/AlbumDto.java
Normal file
@ -0,0 +1,58 @@
|
||||
package np.something.DTO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import np.something.model.Album;
|
||||
import np.something.model.Photo;
|
||||
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
public class AlbumDto {
|
||||
private Long id;
|
||||
@Size(min=3, max=32, message="Album's name's size must be from 3 to 32 letters")
|
||||
private String name;
|
||||
private Long ownerId;
|
||||
private String ownerName;
|
||||
private List<PhotoDto> photos;
|
||||
|
||||
|
||||
public AlbumDto() {
|
||||
}
|
||||
|
||||
public AlbumDto(Album album) {
|
||||
this.id = album.getId();
|
||||
this.name = album.getName();
|
||||
this.ownerId = album.getOwner().getId();
|
||||
this.ownerName = album.getOwner().getUsername();
|
||||
this.photos = album.getPhotos().stream().map(PhotoDto::new).toList();
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getOwnerId() {
|
||||
return ownerId;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public String getOwnerName() {
|
||||
return ownerName;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public List<PhotoDto> getPhotos() {
|
||||
return photos;
|
||||
}
|
||||
}
|
@ -1,101 +0,0 @@
|
||||
package np.something.DTO;
|
||||
|
||||
import np.something.model.Comment;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class CommentDto {
|
||||
public long id;
|
||||
public String content;
|
||||
public long customerId;
|
||||
public String customerName;
|
||||
public long postId;
|
||||
public String postTitle;
|
||||
public String postAuthor;
|
||||
public long postAuthorId;
|
||||
public String createDate;
|
||||
|
||||
public CommentDto() {
|
||||
|
||||
}
|
||||
|
||||
public CommentDto(Comment comment) {
|
||||
this.id = comment.getId();
|
||||
this.content = comment.getContent();
|
||||
this.customerId = comment.getCustomer().getId();
|
||||
this.customerName = comment.getCustomer().getUsername();
|
||||
this.postId = comment.getPost().getId();
|
||||
this.postTitle = comment.getPost().getTitle();
|
||||
this.postAuthor = comment.getPost().getCustomer().getUsername();
|
||||
this.postAuthorId = comment.getPost().getCustomer().getId();
|
||||
this.createDate = comment.getCreateDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public long getCustomerId() {
|
||||
return customerId;
|
||||
}
|
||||
|
||||
public void setCustomerId(long customerId) {
|
||||
this.customerId = customerId;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public String getCustomerName() {
|
||||
return customerName;
|
||||
}
|
||||
|
||||
public long getPostId() {
|
||||
return postId;
|
||||
}
|
||||
|
||||
public void setPostId(long postId) {
|
||||
this.postId = postId;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public String getPostTitle() {return postTitle;}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public String getPostAuthor() {
|
||||
return postAuthor;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public long getPostAuthorId() {
|
||||
return postAuthorId;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public String getCreateDate() {
|
||||
return createDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
CommentDto that = (CommentDto) o;
|
||||
|
||||
return id == that.id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return (int) (id ^ (id >>> 32));
|
||||
}
|
||||
}
|
@ -1,35 +1,35 @@
|
||||
package np.something.DTO;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.List;
|
||||
import np.something.model.Customer;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
public class CustomerDto {
|
||||
public long id;
|
||||
public String username;
|
||||
public String password;
|
||||
public List<CommentDto> comments;
|
||||
public List<PostDto> posts;
|
||||
|
||||
public CustomerDto() {
|
||||
|
||||
}
|
||||
private Long id;
|
||||
@Size(min=3, max=32, message="Username string length must be from 3 to 32 letters")
|
||||
private String username;
|
||||
private List<AlbumDto> ownedAlbums;
|
||||
private List<AlbumDto> albums;
|
||||
|
||||
public CustomerDto(Customer customer) {
|
||||
this.id = customer.getId();
|
||||
this.username = customer.getUsername();
|
||||
this.password = customer.getPassword();
|
||||
this.comments = customer.getComments().stream().map(CommentDto::new).toList();
|
||||
this.posts = customer.getPosts().stream().map(PostDto::new).toList();
|
||||
this.ownedAlbums = customer.getOwnedAlbums().stream().map(AlbumDto::new).toList();
|
||||
this.albums = customer.getAlbums().stream().map(AlbumDto::new).toList();
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public long getId() {
|
||||
public CustomerDto() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
@ -38,21 +38,19 @@ public class CustomerDto {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
public List<AlbumDto> getOwnedAlbums() {
|
||||
return ownedAlbums;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
public void setOwnedAlbums(List<AlbumDto> ownedAlbums) {
|
||||
this.ownedAlbums = ownedAlbums;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public List<CommentDto> getComments() {
|
||||
return comments;
|
||||
public List<AlbumDto> getAlbums() {
|
||||
return albums;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public List<PostDto> getPosts() {
|
||||
return posts;
|
||||
public void setAlbums(List<AlbumDto> albums) {
|
||||
this.albums = albums;
|
||||
}
|
||||
}
|
||||
|
37
src/main/java/np/something/DTO/PhotoDto.java
Normal file
37
src/main/java/np/something/DTO/PhotoDto.java
Normal file
@ -0,0 +1,37 @@
|
||||
package np.something.DTO;
|
||||
|
||||
import np.something.model.Photo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class PhotoDto {
|
||||
private Long id;
|
||||
private List<TagDto> tags;
|
||||
private Long albumId;
|
||||
|
||||
public PhotoDto() {
|
||||
|
||||
}
|
||||
|
||||
public PhotoDto(Photo photo) {
|
||||
this.id = photo.getId();
|
||||
this.tags = photo.getTags().stream().map(TagDto::new).toList();
|
||||
this.albumId = photo.getAlbum().getId();
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public List<TagDto> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(List<TagDto> tags) {
|
||||
this.tags = tags;
|
||||
}
|
||||
}
|
@ -1,77 +0,0 @@
|
||||
package np.something.DTO;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import np.something.model.Post;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PostDto {
|
||||
public long id;
|
||||
public String title;
|
||||
public String content;
|
||||
public String customerName;
|
||||
public long customerId;
|
||||
public ArrayList<CommentDto> comments;
|
||||
|
||||
public String createDate;
|
||||
|
||||
public PostDto() {
|
||||
|
||||
}
|
||||
|
||||
public PostDto(Post post) {
|
||||
this.id = post.getId();
|
||||
this.title = post.getTitle();
|
||||
this.content = post.getContent();
|
||||
this.customerName = post.getCustomer().getUsername();
|
||||
this.customerId = post.getCustomer().getId();
|
||||
this.comments = new ArrayList<>(post.getComments().stream().map(CommentDto::new).toList());
|
||||
this.createDate = post.getCreateDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public String getCustomerName() {
|
||||
return customerName;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public List<CommentDto> getComments() {
|
||||
return comments;
|
||||
}
|
||||
|
||||
public long getCustomerId() {
|
||||
return customerId;
|
||||
}
|
||||
|
||||
public void setCustomerId(long customerId) {
|
||||
this.customerId = customerId;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public String getCreateDate() {
|
||||
return createDate;
|
||||
}
|
||||
}
|
35
src/main/java/np/something/DTO/TagDto.java
Normal file
35
src/main/java/np/something/DTO/TagDto.java
Normal file
@ -0,0 +1,35 @@
|
||||
package np.something.DTO;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import np.something.model.Tag;
|
||||
|
||||
import javax.validation.constraints.Size;
|
||||
import java.util.List;
|
||||
|
||||
public class TagDto {
|
||||
private Long id;
|
||||
@Size(min=3, max=32, message="Tag's name must be from 3 to 32 letters")
|
||||
private String name;
|
||||
|
||||
public TagDto() {
|
||||
|
||||
}
|
||||
|
||||
public TagDto(Tag tag) {
|
||||
this.id = tag.getId();
|
||||
this.name = tag.getName();
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package np.something.Exceptions;
|
||||
|
||||
public class AlbumNotFoundException extends RuntimeException {
|
||||
public AlbumNotFoundException(Long id) {
|
||||
super(String.format("Album with id [%s] is not found", id));
|
||||
}
|
||||
}
|
@ -1,7 +0,0 @@
|
||||
package np.something.Exceptions;
|
||||
|
||||
public class CommentNotFoundException extends RuntimeException {
|
||||
public CommentNotFoundException(Long id) {
|
||||
super(String.format("Comment with id [%s] is not found", id));
|
||||
}
|
||||
}
|
@ -4,4 +4,4 @@ public class CustomerNotFoundException extends RuntimeException {
|
||||
public CustomerNotFoundException(Long id) {
|
||||
super(String.format("Customer with id [%s] is not found", id));
|
||||
}
|
||||
}
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
package np.something.Exceptions;
|
||||
|
||||
public class JwtException extends RuntimeException {
|
||||
public JwtException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
|
||||
public JwtException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
@ -1,7 +0,0 @@
|
||||
package np.something.Exceptions;
|
||||
|
||||
public class PostNotFoundException extends RuntimeException {
|
||||
public PostNotFoundException(Long id) {
|
||||
super(String.format("Post with id [%s] is not found", id));
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
package np.something;
|
||||
|
||||
import io.swagger.v3.oas.models.Components;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import np.something.security.JwtFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class OpenAPI30Configuration {
|
||||
public static final String API_PREFIX = "/api/1.0";
|
||||
|
||||
@Bean
|
||||
public OpenAPI customizeOpenAPI() {
|
||||
final String securitySchemeName = JwtFilter.TOKEN_BEGIN_STR;
|
||||
return new OpenAPI()
|
||||
.addSecurityItem(new SecurityRequirement()
|
||||
.addList(securitySchemeName))
|
||||
.components(new Components()
|
||||
.addSecuritySchemes(securitySchemeName, new SecurityScheme()
|
||||
.name(securitySchemeName)
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")
|
||||
.bearerFormat("JWT")));
|
||||
}
|
||||
}
|
@ -13,13 +13,11 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
public static final String REST_API = OpenAPI30Configuration.API_PREFIX;
|
||||
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
WebMvcConfigurer.super.addViewControllers(registry);
|
||||
registry.addViewController("login");
|
||||
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
|
||||
registry.addViewController("/notFound").setViewName("forward:/");
|
||||
}
|
||||
|
||||
|
@ -1,61 +0,0 @@
|
||||
package np.something.controllers;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import np.something.DTO.CommentDto;
|
||||
import np.something.WebConfiguration;
|
||||
import np.something.model.Comment;
|
||||
import np.something.services.*;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(WebConfiguration.REST_API + "/comment")
|
||||
public class CommentController {
|
||||
private final CommentService commentService;
|
||||
private final CustomerService customerService;
|
||||
private final PostService postService;
|
||||
|
||||
public CommentController(CommentService commentService, CustomerService customerService, PostService postService) {
|
||||
this.commentService = commentService;
|
||||
this.customerService = customerService;
|
||||
this.postService = postService;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public CommentDto getComment(@PathVariable Long id) {
|
||||
return new CommentDto(commentService.findComment(id));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<CommentDto> getComments() {
|
||||
return commentService.findAllComments().stream()
|
||||
.map(CommentDto::new)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public CommentDto createComment(@RequestBody @Valid CommentDto commentDto){
|
||||
final Comment comment = commentService.addComment(
|
||||
customerService.findCustomer(commentDto.getCustomerId()),
|
||||
postService.findPost(commentDto.getPostId()),
|
||||
commentDto.getContent()
|
||||
);
|
||||
return new CommentDto(comment);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public CommentDto updateComment(@RequestBody @Valid CommentDto commentDto, @PathVariable Long id) {
|
||||
return new CommentDto(commentService.updateComment(id, commentDto.getContent()));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public CommentDto deleteComment(@PathVariable Long id) {
|
||||
return new CommentDto(commentService.deleteComment(id));
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
public void deleteAllComments(){
|
||||
commentService.deleteAllComments();
|
||||
}
|
||||
}
|
@ -1,82 +0,0 @@
|
||||
package np.something.controllers;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import np.something.DTO.CustomerDto;
|
||||
import np.something.WebConfiguration;
|
||||
import np.something.model.Customer;
|
||||
import np.something.services.*;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(WebConfiguration.REST_API + "/customer")
|
||||
public class CustomerController {
|
||||
public static final String URL_LOGIN = "/jwt/login";
|
||||
private final CustomerService customerService;
|
||||
|
||||
public CustomerController(CustomerService customerService) {
|
||||
this.customerService = customerService;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public CustomerDto getCustomer(@PathVariable Long id) {
|
||||
return new CustomerDto(customerService.findCustomer(id));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<CustomerDto> getCustomers() {
|
||||
return customerService.findAllCustomers().stream()
|
||||
.map(CustomerDto::new)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public CustomerDto createCustomer(@RequestBody @Valid CustomerDto customerDto){
|
||||
final Customer customer = customerService.addCustomer(customerDto.getUsername(), customerDto.getPassword());
|
||||
return new CustomerDto(customer);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public CustomerDto updateCustomer(@RequestBody @Valid CustomerDto customerDto, @PathVariable Long id) {
|
||||
return new CustomerDto(customerService.updateCustomer(id, customerDto.getUsername(), customerDto.getPassword()));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public CustomerDto deleteCustomer(@PathVariable Long id) {
|
||||
return new CustomerDto(customerService.deleteCustomer(id));
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
public void deleteAllCustomers(){
|
||||
customerService.deleteAllCustomers();
|
||||
}
|
||||
|
||||
@GetMapping("/find/{username}")
|
||||
public CustomerDto getCustomerByUsername(@PathVariable String username) {
|
||||
return new CustomerDto(customerService.findByUsername(username));
|
||||
}
|
||||
|
||||
@PostMapping(URL_LOGIN)
|
||||
public String login(@RequestBody @Valid CustomerDto customerDto) {
|
||||
return customerService.loginAndGetToken(customerDto);
|
||||
}
|
||||
|
||||
@GetMapping ("/me")
|
||||
CustomerDto getCurrentCustomer(@RequestHeader(HttpHeaders.AUTHORIZATION) String token) {
|
||||
return new CustomerDto(customerService.findByUsername(customerService.loadUserByToken(token.substring(7)).getUsername()));
|
||||
}
|
||||
|
||||
@GetMapping("role/{token}")
|
||||
public String getRoleByToken(@PathVariable String token) {
|
||||
var userDetails = customerService.loadUserByToken(token);
|
||||
Customer customer = customerService.findByUsername(userDetails.getUsername());
|
||||
|
||||
if (customer != null) {
|
||||
return customer.getRole().toString();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
@ -1,66 +0,0 @@
|
||||
package np.something.controllers;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import np.something.DTO.PostDto;
|
||||
import np.something.WebConfiguration;
|
||||
import np.something.services.CustomerService;
|
||||
import np.something.services.PostService;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(WebConfiguration.REST_API + "/post")
|
||||
public class PostController {
|
||||
private final PostService postService;
|
||||
private final CustomerService customerService;
|
||||
|
||||
public PostController(PostService postService, CustomerService customerService) {
|
||||
this.postService = postService;
|
||||
this.customerService = customerService;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public PostDto getPost(@PathVariable Long id) {
|
||||
return new PostDto(postService.findPost(id));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<PostDto> getPosts() {
|
||||
return postService.findAllPosts().stream()
|
||||
.map(PostDto::new)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public PostDto createPost(@RequestBody @Valid PostDto postDto)
|
||||
{
|
||||
return new PostDto(postService.addPost(customerService.findCustomer(postDto.getCustomerId()), postDto.getTitle(), postDto.getContent()));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public PostDto updatePost(@RequestBody @Valid PostDto postDto, @PathVariable Long id)
|
||||
{
|
||||
return new PostDto(postService.updatePost(id, postDto.title, postDto.content));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public PostDto deletePost (@PathVariable Long id) {
|
||||
return new PostDto(postService.deletePost(id));
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
public void deleteAllPosts() {
|
||||
postService.deleteAllPosts();
|
||||
}
|
||||
|
||||
@GetMapping("/search")
|
||||
public List<PostDto> searchPosts(@RequestParam(required = false) String query) {
|
||||
if (query == null || query.isBlank()) {
|
||||
return postService.findAllPosts().stream()
|
||||
.map(PostDto::new)
|
||||
.toList();
|
||||
} else {
|
||||
return postService.searchPosts(query);
|
||||
}
|
||||
}
|
||||
}
|
94
src/main/java/np/something/model/Album.java
Normal file
94
src/main/java/np/something/model/Album.java
Normal file
@ -0,0 +1,94 @@
|
||||
package np.something.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
import javax.validation.constraints.Size;
|
||||
import java.util.*;
|
||||
|
||||
@Entity
|
||||
public class Album {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column
|
||||
@Size(min=3, max=32, message="Album's name's size must be from 3 to 32 letters")
|
||||
private String name;
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "owner_fk")
|
||||
private Customer owner;
|
||||
|
||||
@ManyToMany(fetch = FetchType.EAGER)
|
||||
@JoinTable(name = "albums_customers",
|
||||
joinColumns = {
|
||||
@JoinColumn(name = "album_id", referencedColumnName = "id",
|
||||
nullable = false, updatable = false)},
|
||||
inverseJoinColumns = {
|
||||
@JoinColumn(name = "customer_id", referencedColumnName = "id",
|
||||
nullable = false, updatable = false)})
|
||||
private Set<Customer> customers;
|
||||
|
||||
@OneToMany(mappedBy = "album", fetch = FetchType.EAGER)
|
||||
private List<Photo> photos = new ArrayList<>();
|
||||
|
||||
public Album(String name, Customer owner) {
|
||||
this.name = name;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public Album() {
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Customer getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
public void setOwner(Customer owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public Set<Customer> getCustomers() {
|
||||
return customers;
|
||||
}
|
||||
|
||||
public void setCustomers(Set<Customer> customers) {
|
||||
this.customers = customers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Album album = (Album) o;
|
||||
return id.equals(album.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public List<Photo> getPhotos() {
|
||||
return photos;
|
||||
}
|
||||
|
||||
public void setPhotos(List<Photo> photos) {
|
||||
this.photos = photos;
|
||||
}
|
||||
}
|
@ -1,82 +0,0 @@
|
||||
package np.something.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
public class Comment {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column
|
||||
@NotBlank(message = "Content cannot be empty")
|
||||
private String content;
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER)
|
||||
@JoinColumn(name="customer_fk")
|
||||
private Customer customer;
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER)
|
||||
@JoinColumn(name="post_fk")
|
||||
private Post post;
|
||||
|
||||
@Column(columnDefinition = "timestamp default NOW()")
|
||||
private LocalDateTime createDate;
|
||||
|
||||
public Comment() {
|
||||
|
||||
}
|
||||
|
||||
public Comment(Customer customer, Post post, String content) {
|
||||
this.customer = customer;
|
||||
this.post = post;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Post getPost() {
|
||||
return post;
|
||||
}
|
||||
|
||||
public Customer getCustomer() {
|
||||
return customer;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
Comment comment = (Comment) o;
|
||||
|
||||
return Objects.equals(id, comment.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
public LocalDateTime getCreateDate() {
|
||||
return createDate;
|
||||
}
|
||||
|
||||
public void setCreateDate(LocalDateTime createDate) {
|
||||
this.createDate = createDate;
|
||||
}
|
||||
}
|
@ -4,6 +4,7 @@ import org.h2.engine.User;
|
||||
|
||||
import javax.persistence.*;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@ -13,15 +14,17 @@ public class Customer {
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@Column
|
||||
@NotBlank(message = "Username cannot be empty")
|
||||
@Size(min=3, max=32, message="Username string length must be from 3 to 32 letters")
|
||||
private String username;
|
||||
@Column
|
||||
@NotBlank(message = "Password cannot be empty")
|
||||
@Size(min=8, max=1024, message="Password string length must be from 8 to 1024 letters")
|
||||
private String password;
|
||||
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.ALL)
|
||||
private List<Comment> comments;
|
||||
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.ALL)
|
||||
private List<Post> posts;
|
||||
|
||||
@ManyToMany(mappedBy = "customers", fetch = FetchType.EAGER)
|
||||
private Set<Album> albums = new HashSet<>();
|
||||
|
||||
@OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)
|
||||
private List<Album> ownedAlbums = new ArrayList<>();
|
||||
|
||||
private UserRole role;
|
||||
|
||||
@ -33,16 +36,12 @@ public class Customer {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.role = UserRole.USER;
|
||||
this.comments = new ArrayList<>();
|
||||
this.posts = new ArrayList<>();
|
||||
}
|
||||
|
||||
public Customer(String username, String password, UserRole role) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.role = role;
|
||||
this.comments = new ArrayList<>();
|
||||
this.posts = new ArrayList<>();
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
@ -57,14 +56,6 @@ public class Customer {
|
||||
return password;
|
||||
}
|
||||
|
||||
public List<Comment> getComments() {
|
||||
return comments;
|
||||
}
|
||||
|
||||
public List<Post> getPosts() {
|
||||
return posts;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
@ -89,4 +80,20 @@ public class Customer {
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
public Set<Album> getAlbums() {
|
||||
return albums;
|
||||
}
|
||||
|
||||
public void setAlbums(Set<Album> albums) {
|
||||
this.albums = albums;
|
||||
}
|
||||
|
||||
public List<Album> getOwnedAlbums() {
|
||||
return ownedAlbums;
|
||||
}
|
||||
|
||||
public void setOwnedAlbums(List<Album> ownedAlbums) {
|
||||
this.ownedAlbums = ownedAlbums;
|
||||
}
|
||||
}
|
||||
|
70
src/main/java/np/something/model/Photo.java
Normal file
70
src/main/java/np/something/model/Photo.java
Normal file
@ -0,0 +1,70 @@
|
||||
package np.something.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
public class Photo {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "album_fk")
|
||||
private Album album;
|
||||
|
||||
@ManyToMany(fetch = FetchType.EAGER)
|
||||
@JoinTable(name = "photos_tags",
|
||||
joinColumns = {
|
||||
@JoinColumn(name = "photo_id", referencedColumnName = "id",
|
||||
nullable = false, updatable = false)},
|
||||
inverseJoinColumns = {
|
||||
@JoinColumn(name = "tag_id", referencedColumnName = "id",
|
||||
nullable = false, updatable = false)})
|
||||
private Set<Tag> tags;
|
||||
|
||||
public Photo(Album album) {
|
||||
this.album = album;
|
||||
}
|
||||
|
||||
public Photo() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Photo photo = (Photo) o;
|
||||
return id.equals(photo.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
public Album getAlbum() {
|
||||
return album;
|
||||
}
|
||||
|
||||
public void setAlbum(Album album) {
|
||||
this.album = album;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Set<Tag> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(Set<Tag> tags) {
|
||||
this.tags = tags;
|
||||
}
|
||||
}
|
@ -1,95 +0,0 @@
|
||||
package np.something.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class Post {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column
|
||||
@NotBlank(message = "Title cannot be empty")
|
||||
private String title;
|
||||
|
||||
@Column
|
||||
@NotBlank(message = "Content cannot be empty")
|
||||
private String content;
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "customer_fk")
|
||||
private Customer customer;
|
||||
|
||||
@OneToMany(fetch = FetchType.EAGER, mappedBy = "post", cascade = CascadeType.ALL)
|
||||
private List<Comment> comments;
|
||||
|
||||
@Column(columnDefinition = "timestamp default NOW()")
|
||||
private LocalDateTime createDate;
|
||||
|
||||
public Post() {
|
||||
|
||||
}
|
||||
|
||||
public Post(Customer customer, String title, String content) {
|
||||
this.customer = customer;
|
||||
this.title = title;
|
||||
this.content = content;
|
||||
this.comments = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
Post post = (Post) o;
|
||||
|
||||
return id.equals(post.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return id.hashCode();
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public List<Comment> getComments() {
|
||||
return comments;
|
||||
}
|
||||
|
||||
public Customer getCustomer() {
|
||||
return customer;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public LocalDateTime getCreateDate() {
|
||||
return createDate;
|
||||
}
|
||||
|
||||
public void setCreateDate(LocalDateTime createDate) {
|
||||
this.createDate = createDate;
|
||||
}
|
||||
}
|
64
src/main/java/np/something/model/Tag.java
Normal file
64
src/main/java/np/something/model/Tag.java
Normal file
@ -0,0 +1,64 @@
|
||||
package np.something.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
import javax.validation.constraints.Size;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
public class Tag {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column
|
||||
@Size(min=3, max=32, message="Tag's name must be from 3 to 32 letters")
|
||||
private String name;
|
||||
|
||||
@ManyToMany(mappedBy = "tags")
|
||||
List<Photo> photos;
|
||||
|
||||
public Tag() {
|
||||
}
|
||||
|
||||
public Tag(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Photo> getPhotos() {
|
||||
return photos;
|
||||
}
|
||||
|
||||
public void setPhotos(List<Photo> photos) {
|
||||
this.photos = photos;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Tag tag = (Tag) o;
|
||||
return id.equals(tag.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
@ -1,70 +0,0 @@
|
||||
package np.something.mvc;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import javax.validation.Valid;
|
||||
import np.something.DTO.CustomerDto;
|
||||
import np.something.model.UserRole;
|
||||
import np.something.services.CustomerService;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/admin")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public class Admin {
|
||||
private final CustomerService customerService;
|
||||
|
||||
public Admin(CustomerService customerService) {
|
||||
this.customerService = customerService;
|
||||
}
|
||||
|
||||
@GetMapping(value = { "/", "/{id}" })
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public String getCustomers(@PathVariable(required = false) Long id, HttpServletRequest request, Model model) {
|
||||
model.addAttribute("request", request);
|
||||
model.addAttribute("currentCustomerId", customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
).getId());
|
||||
if (id == null || id <= 0) {
|
||||
model.addAttribute("customers", customerService.findAllCustomers().stream().map(CustomerDto::new).toList());
|
||||
return "admin";
|
||||
} else {
|
||||
return "redirect:/customers/" + id;
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String deleteCustomer(@PathVariable Long id) {
|
||||
customerService.deleteCustomer(id);
|
||||
return "redirect:/admin/";
|
||||
}
|
||||
|
||||
@PostMapping(value = { "/", "/{id}"})
|
||||
public String manipulateCustomer(@PathVariable(required = false) Long id, @ModelAttribute @Valid CustomerDto customerDto,
|
||||
HttpServletRequest request,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
model.addAttribute("request", request);
|
||||
model.addAttribute("currentCustomerId", customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
).getId());
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "/admin";
|
||||
}
|
||||
|
||||
if (id == null || id <= 0) {
|
||||
customerService.addCustomer(customerDto.username, customerDto.password);
|
||||
} else {
|
||||
customerService.updateCustomer(id, customerDto.username, customerDto.password);
|
||||
}
|
||||
|
||||
return "redirect:/admin/";
|
||||
}
|
||||
}
|
132
src/main/java/np/something/mvc/AlbumMVC.java
Normal file
132
src/main/java/np/something/mvc/AlbumMVC.java
Normal file
@ -0,0 +1,132 @@
|
||||
package np.something.mvc;
|
||||
|
||||
import np.something.DTO.AlbumDto;
|
||||
import np.something.model.Album;
|
||||
import np.something.model.Customer;
|
||||
import np.something.services.AlbumService;
|
||||
import np.something.services.CustomerService;
|
||||
import np.something.services.PhotoService;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.Objects;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = {"/albums"})
|
||||
public class AlbumMVC {
|
||||
private final AlbumService albumService;
|
||||
private final CustomerService customerService;
|
||||
private final PhotoService photoService;
|
||||
|
||||
public AlbumMVC(AlbumService albumService, CustomerService customerService, PhotoService photoService) {
|
||||
this.albumService = albumService;
|
||||
this.customerService = customerService;
|
||||
this.photoService = photoService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String albums(Model model) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
model.addAttribute("currentCustomer", customer);
|
||||
model.addAttribute("albums", customer.getAlbums());
|
||||
model.addAttribute("ownerAlbums", customer.getOwnedAlbums());
|
||||
|
||||
return "/albums";
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public String album(Model model, @PathVariable Long id) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
Album album = albumService.find(id);
|
||||
model.addAttribute("currentCustomer", customer);
|
||||
model.addAttribute("customers", customerService.findAllCustomers().stream().filter(x -> !Objects.equals(x.getId(), album.getOwner().getId()) && !album.getCustomers().contains(x)).toList());
|
||||
model.addAttribute("album", album);
|
||||
model.addAttribute("photos", album.getPhotos());
|
||||
|
||||
return "/album";
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public String createAlbum(@ModelAttribute @Valid AlbumDto albumDto) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
albumService.add(albumDto.getName(), customer);
|
||||
|
||||
return "redirect:/albums";
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String editAlbum(@PathVariable Long id, @ModelAttribute @Valid AlbumDto albumDto) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
if (Objects.equals(albumService.find(id).getOwner().getId(), customer.getId())) {
|
||||
albumService.update(id, albumDto.getName());
|
||||
}
|
||||
|
||||
return "redirect:/albums/" + id;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String deleteAlbum(@PathVariable Long id) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
if (Objects.equals(albumService.find(id).getOwner().getId(), customer.getId())) {
|
||||
albumService.delete(id);
|
||||
}
|
||||
|
||||
return "redirect:/albums";
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/add/photo")
|
||||
public String addPhoto(@PathVariable Long id) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
if (Objects.equals(albumService.find(id).getOwner().getId(), customer.getId())) {
|
||||
albumService.addPhoto(id);
|
||||
}
|
||||
|
||||
return "redirect:/albums/" + id;
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/add/customer/{cid}")
|
||||
public String addCustomer(@PathVariable Long id, @PathVariable Long cid) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
if (Objects.equals(albumService.find(id).getOwner().getId(), customer.getId())) {
|
||||
albumService.addCustomer(id, cid);
|
||||
}
|
||||
|
||||
return "redirect:/albums/" + id;
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/remove/customer/{cid}")
|
||||
public String removeCustomer(@PathVariable Long id, @PathVariable Long cid) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
if (Objects.equals(albumService.find(id).getOwner().getId(), customer.getId())) {
|
||||
albumService.removeCustomer(id, cid);
|
||||
}
|
||||
|
||||
return "redirect:/albums/" + id;
|
||||
}
|
||||
}
|
@ -1,59 +0,0 @@
|
||||
package np.something.mvc;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import javax.validation.Valid;
|
||||
import np.something.DTO.CommentDto;
|
||||
import np.something.DTO.PostDto;
|
||||
import np.something.services.CommentService;
|
||||
import np.something.services.CustomerService;
|
||||
import np.something.services.PostService;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/comments")
|
||||
public class Comments {
|
||||
private final CustomerService customerService;
|
||||
private final CommentService commentService;
|
||||
private final PostService postService;
|
||||
|
||||
public Comments(CustomerService customerService, CommentService commentService, PostService postService) {
|
||||
this.customerService = customerService;
|
||||
this.commentService = commentService;
|
||||
this.postService = postService;
|
||||
}
|
||||
|
||||
@PostMapping(value = { "/", "/{id}"})
|
||||
public String manipulateComment(@PathVariable(required = false) Long id, @ModelAttribute @Valid CommentDto commentDto,
|
||||
HttpServletRequest request, BindingResult bindingResult, Model model) {
|
||||
model.addAttribute("request", request);
|
||||
model.addAttribute("currentCustomerId", customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
).getId());
|
||||
model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList());
|
||||
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "/feed";
|
||||
}
|
||||
|
||||
if (id == null || id <= 0) {
|
||||
commentService.addComment(customerService.findCustomer(commentDto.customerId), postService.findPost(commentDto.postId), commentDto.content);
|
||||
} else {
|
||||
commentService.updateComment(id, commentDto.content);
|
||||
}
|
||||
|
||||
return "redirect:/feed";
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String deleteComment(@PathVariable Long id) {
|
||||
commentService.deleteComment(id);
|
||||
return "redirect:/feed";
|
||||
}
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
package np.something.mvc;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import javax.validation.Valid;
|
||||
import np.something.DTO.CustomerDto;
|
||||
import np.something.services.CustomerService;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/customers")
|
||||
public class Customers {
|
||||
private final CustomerService customerService;
|
||||
|
||||
public Customers(CustomerService customerService) {
|
||||
this.customerService = customerService;
|
||||
}
|
||||
|
||||
@GetMapping(value = { "/", "/{id}" })
|
||||
public String getCustomers(@PathVariable(required = false) Long id, HttpServletRequest request, HttpSession session, Model model) {
|
||||
model.addAttribute("request", request);
|
||||
model.addAttribute("currentCustomerId", customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
).getId());
|
||||
if (id == null || id <= 0) {
|
||||
model.addAttribute("customers", customerService.findAllCustomers().stream().map(CustomerDto::new).toList());
|
||||
} else {
|
||||
model.addAttribute("customers", new CustomerDto[] { new CustomerDto(customerService.findCustomer(id)) });
|
||||
}
|
||||
|
||||
return "customers";
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String deleteCustomer(@PathVariable Long id, HttpSession session) {
|
||||
customerService.deleteCustomer(id);
|
||||
return "redirect:/customers/";
|
||||
}
|
||||
|
||||
@PostMapping(value = { "/", "/{id}"})
|
||||
public String manipulateCustomer(@PathVariable(required = false) Long id, @ModelAttribute @Valid CustomerDto customerDto,
|
||||
HttpServletRequest request, HttpSession session,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
model.addAttribute("request", request);
|
||||
model.addAttribute("currentCustomerId", customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
).getId());
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "/customers";
|
||||
}
|
||||
|
||||
if (id == null || id <= 0) {
|
||||
customerService.addCustomer(customerDto.username, customerDto.password);
|
||||
} else {
|
||||
customerService.updateCustomer(id, customerDto.username, customerDto.password);
|
||||
}
|
||||
|
||||
return "redirect:/customers/";
|
||||
}
|
||||
}
|
@ -1,54 +0,0 @@
|
||||
package np.something.mvc;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import np.something.DTO.CommentDto;
|
||||
import np.something.DTO.CustomerDto;
|
||||
import np.something.DTO.PostDto;
|
||||
import np.something.model.Post;
|
||||
import np.something.services.CommentService;
|
||||
import np.something.services.CustomerService;
|
||||
import np.something.services.PostService;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = { "", "/feed" })
|
||||
public class Feed {
|
||||
private final PostService postService;
|
||||
private final CustomerService customerService;
|
||||
|
||||
private final CommentService commentService;
|
||||
|
||||
public Feed(PostService postService, CustomerService customerService, CommentService commentService) {
|
||||
this.postService = postService;
|
||||
this.customerService = customerService;
|
||||
this.commentService = commentService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getPosts(@RequestParam(required = false) String search, HttpServletRequest request, HttpSession session, Model model) {
|
||||
model.addAttribute("request", request);
|
||||
model.addAttribute("currentCustomerId", customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
).getId());
|
||||
if (search == null) {
|
||||
model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList());
|
||||
} else {
|
||||
model.addAttribute("posts", postService.searchPosts(search));
|
||||
}
|
||||
model.addAttribute("customers", customerService.findAllCustomers().stream().map(CustomerDto::new).toList());
|
||||
|
||||
return "/feed";
|
||||
}
|
||||
}
|
94
src/main/java/np/something/mvc/PhotoMVC.java
Normal file
94
src/main/java/np/something/mvc/PhotoMVC.java
Normal file
@ -0,0 +1,94 @@
|
||||
package np.something.mvc;
|
||||
|
||||
import np.something.model.Album;
|
||||
import np.something.model.Customer;
|
||||
import np.something.model.Photo;
|
||||
import np.something.services.CustomerService;
|
||||
import np.something.services.PhotoService;
|
||||
import np.something.services.TagService;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.Objects;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/photos")
|
||||
public class PhotoMVC {
|
||||
private final PhotoService photoService;
|
||||
private final TagService tagService;
|
||||
|
||||
private final CustomerService customerService;
|
||||
|
||||
public PhotoMVC(PhotoService photoService, TagService tagService, CustomerService customerService) {
|
||||
this.photoService = photoService;
|
||||
this.tagService = tagService;
|
||||
this.customerService = customerService;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public String photo(Model model, @PathVariable Long id) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
Photo photo = photoService.getPhotoById(id);
|
||||
|
||||
model.addAttribute("currentCustomer", customer);
|
||||
model.addAttribute("photo", photo);
|
||||
model.addAttribute("tags", tagService.findAll().stream().filter(x -> !photo.getTags().contains(x)).toList());
|
||||
|
||||
return "/photo";
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String deletePhoto(@PathVariable Long id) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
Photo photo = photoService.getPhotoById(id);
|
||||
Album album = photo.getAlbum();
|
||||
|
||||
if (Objects.equals(album.getOwner().getId(), customer.getId())) {
|
||||
photoService.delete(id);
|
||||
}
|
||||
|
||||
return "redirect:/albums/" + album.getId();
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/add/tag/{tag_id}")
|
||||
public String addTag(@PathVariable Long id, @PathVariable Long tag_id) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
Photo photo = photoService.getPhotoById(id);
|
||||
Album album = photo.getAlbum();
|
||||
|
||||
if (Objects.equals(album.getOwner().getId(), customer.getId())) {
|
||||
photoService.addTag(id, tag_id);
|
||||
}
|
||||
|
||||
return "redirect:/photos/" + id;
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/remove/tag/{tag_id}")
|
||||
public String removeTag(@PathVariable Long id, @PathVariable Long tag_id) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
Photo photo = photoService.getPhotoById(id);
|
||||
Album album = photo.getAlbum();
|
||||
|
||||
if (Objects.equals(album.getOwner().getId(), customer.getId())) {
|
||||
photoService.removeTag(id, tag_id);
|
||||
}
|
||||
|
||||
return "redirect:/photos/" + id;
|
||||
}
|
||||
}
|
@ -1,60 +0,0 @@
|
||||
package np.something.mvc;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import np.something.services.CommentService;
|
||||
import np.something.services.CustomerService;
|
||||
import np.something.services.PostService;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import javax.validation.Valid;
|
||||
import np.something.DTO.PostDto;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/posts")
|
||||
public class Posts {
|
||||
private final CustomerService customerService;
|
||||
private final CommentService commentService;
|
||||
private final PostService postService;
|
||||
|
||||
public Posts(CustomerService customerService, CommentService commentService, PostService postService) {
|
||||
this.customerService = customerService;
|
||||
this.commentService = commentService;
|
||||
this.postService = postService;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String deletePost(@PathVariable Long id) {
|
||||
postService.deletePost(id);
|
||||
return "redirect:/feed";
|
||||
}
|
||||
|
||||
@PostMapping(value = { "/", "/{id}"})
|
||||
public String manipulatePost(@PathVariable(required = false) Long id, @ModelAttribute @Valid PostDto postDto,
|
||||
HttpServletRequest request, HttpSession session,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
model.addAttribute("request", request);
|
||||
model.addAttribute("currentCustomerId", customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
).getId());
|
||||
model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList());
|
||||
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "/feed";
|
||||
}
|
||||
|
||||
if (id == null || id <= 0) {
|
||||
postService.addPost(customerService.findCustomer(postDto.customerId), postDto.title, postDto.content);
|
||||
} else {
|
||||
postService.updatePost(id, postDto.title, postDto.content);
|
||||
}
|
||||
|
||||
return "redirect:/feed";
|
||||
}
|
||||
}
|
79
src/main/java/np/something/mvc/TagMVC.java
Normal file
79
src/main/java/np/something/mvc/TagMVC.java
Normal file
@ -0,0 +1,79 @@
|
||||
package np.something.mvc;
|
||||
|
||||
import np.something.DTO.TagDto;
|
||||
import np.something.model.Customer;
|
||||
import np.something.model.Tag;
|
||||
import np.something.model.UserRole;
|
||||
import np.something.services.CustomerService;
|
||||
import np.something.services.PhotoService;
|
||||
import np.something.services.TagService;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.*;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/tags")
|
||||
public class TagMVC {
|
||||
private final TagService tagService;
|
||||
private final CustomerService customerService;
|
||||
private final PhotoService photoService;
|
||||
|
||||
public TagMVC(TagService tagService, CustomerService customerService, PhotoService photoService) {
|
||||
this.tagService = tagService;
|
||||
this.customerService = customerService;
|
||||
this.photoService = photoService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String tags(Model model, @RequestParam(required = false) String search) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
model.addAttribute("currentCustomer", customer);
|
||||
if (search == null || search.isBlank()) {
|
||||
model.addAttribute("tags", tagService.findAll());
|
||||
} else {
|
||||
model.addAttribute("tags", tagService.tagsByTagPrefix(search));
|
||||
}
|
||||
|
||||
return "/tags";
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public String tag(Model model, @PathVariable Long id) {
|
||||
Customer customer = customerService.findByUsername(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
|
||||
);
|
||||
|
||||
Tag tag = tagService.find(id);
|
||||
|
||||
model.addAttribute("currentCustomer", customer);
|
||||
model.addAttribute("tag", tag);
|
||||
model.addAttribute("photos", tagService.customersPhotosByTag(customer, id));
|
||||
|
||||
return "/tag";
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public String createTag(@ModelAttribute @Valid TagDto tagDto) {
|
||||
tagService.add(tagDto.getName());
|
||||
|
||||
return "redirect:/tags";
|
||||
}
|
||||
|
||||
@PostMapping("/{id}")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public String editTag(@PathVariable Long id, @ModelAttribute @Valid TagDto tagDto) {
|
||||
tagService.update(id, tagDto.getName());
|
||||
|
||||
return "redirect:/tags";
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package np.something.repositories;
|
||||
|
||||
import np.something.model.Album;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface AlbumRepository extends JpaRepository<Album, Long> {
|
||||
}
|
@ -1,13 +0,0 @@
|
||||
package np.something.repositories;
|
||||
|
||||
import np.something.model.Comment;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface CommentRepository extends JpaRepository<Comment, Long> {
|
||||
@Query("SELECT DISTINCT c FROM Comment c WHERE c.content LIKE %:tag%")
|
||||
List<Comment> searchComments(@Param("tag") String tag);
|
||||
}
|
12
src/main/java/np/something/repositories/PhotoRepository.java
Normal file
12
src/main/java/np/something/repositories/PhotoRepository.java
Normal file
@ -0,0 +1,12 @@
|
||||
package np.something.repositories;
|
||||
|
||||
import np.something.model.Photo;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PhotoRepository extends JpaRepository<Photo, Long> {
|
||||
|
||||
}
|
@ -1,14 +0,0 @@
|
||||
package np.something.repositories;
|
||||
|
||||
import np.something.model.Comment;
|
||||
import np.something.model.Post;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PostRepository extends JpaRepository<Post, Long> {
|
||||
@Query("SELECT DISTINCT p FROM Post p WHERE p.title LIKE %:tag% OR p.content LIKE %:tag%")
|
||||
List<Post> searchPosts(@Param("tag") String tag);
|
||||
}
|
17
src/main/java/np/something/repositories/TagRepository.java
Normal file
17
src/main/java/np/something/repositories/TagRepository.java
Normal file
@ -0,0 +1,17 @@
|
||||
package np.something.repositories;
|
||||
|
||||
import np.something.model.Photo;
|
||||
import np.something.model.Tag;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface TagRepository extends JpaRepository<Tag, Long> {
|
||||
@Query("SELECT t FROM Tag t WHERE LOWER(t.name) LIKE LOWER(CONCAT(:tagPrefix, '%'))")
|
||||
List<Tag> findTagsByTagPrefix(@Param("tagPrefix") String tagPrefix);
|
||||
|
||||
@Query("SELECT p FROM Photo p JOIN p.tags t WHERE (:tagIds) IN t.id GROUP BY p HAVING COUNT(DISTINCT t) >= :tagCount")
|
||||
List<Photo> findPhotosByTags(@Param("tagIds") List<Long> tagIds, @Param("tagCount") long tagCount);
|
||||
}
|
@ -1,73 +0,0 @@
|
||||
package np.something.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import np.something.Exceptions.JwtException;
|
||||
import np.something.services.CustomerService;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.GenericFilterBean;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
public class JwtFilter extends GenericFilterBean {
|
||||
private static final String AUTHORIZATION = "Authorization";
|
||||
public static final String TOKEN_BEGIN_STR = "Bearer ";
|
||||
|
||||
private final CustomerService customerService;
|
||||
|
||||
public JwtFilter(CustomerService customerService) {
|
||||
this.customerService = customerService;
|
||||
}
|
||||
|
||||
private String getTokenFromRequest(HttpServletRequest request) {
|
||||
String bearer = request.getHeader(AUTHORIZATION);
|
||||
if (StringUtils.hasText(bearer) && bearer.startsWith(TOKEN_BEGIN_STR)) {
|
||||
return bearer.substring(TOKEN_BEGIN_STR.length());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void raiseException(ServletResponse response, int status, String message) throws IOException {
|
||||
if (response instanceof final HttpServletResponse httpResponse) {
|
||||
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
httpResponse.setStatus(status);
|
||||
final byte[] body = new ObjectMapper().writeValueAsBytes(message);
|
||||
response.getOutputStream().write(body);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request,
|
||||
ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
if (request instanceof final HttpServletRequest httpRequest) {
|
||||
final String token = getTokenFromRequest(httpRequest);
|
||||
if (StringUtils.hasText(token)) {
|
||||
try {
|
||||
final UserDetails user = customerService.loadUserByToken(token);
|
||||
final UsernamePasswordAuthenticationToken auth =
|
||||
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
} catch (JwtException e) {
|
||||
raiseException(response, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
raiseException(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
|
||||
String.format("Internal error: %s", e.getMessage()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
package np.something.security;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "jwt", ignoreInvalidFields = true)
|
||||
public class JwtProperties {
|
||||
private String devToken = "";
|
||||
private Boolean isDev = true;
|
||||
|
||||
public String getDevToken() {
|
||||
return devToken;
|
||||
}
|
||||
|
||||
public void setDevToken(String devToken) {
|
||||
this.devToken = devToken;
|
||||
}
|
||||
|
||||
public Boolean isDev() {
|
||||
return isDev;
|
||||
}
|
||||
|
||||
public void setDev(Boolean dev) {
|
||||
isDev = dev;
|
||||
}
|
||||
}
|
@ -1,108 +0,0 @@
|
||||
package np.something.security;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.exceptions.JWTVerificationException;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
import com.auth0.jwt.interfaces.JWTVerifier;
|
||||
import np.something.Exceptions.JwtException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class JwtProvider {
|
||||
private final static Logger LOG = LoggerFactory.getLogger(JwtProvider.class);
|
||||
|
||||
private final static byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
|
||||
private final static String ISSUER = "auth0";
|
||||
|
||||
private final Algorithm algorithm;
|
||||
private final JWTVerifier verifier;
|
||||
|
||||
public JwtProvider(JwtProperties jwtProperties) {
|
||||
if (!jwtProperties.isDev()) {
|
||||
LOG.info("Generate new JWT key for prod");
|
||||
try {
|
||||
final MessageDigest salt = MessageDigest.getInstance("SHA-256");
|
||||
salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
|
||||
LOG.info("Use generated JWT key for prod \n{}", bytesToHex(salt.digest()));
|
||||
algorithm = Algorithm.HMAC256(bytesToHex(salt.digest()));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new JwtException(e);
|
||||
}
|
||||
} else {
|
||||
LOG.info("Use default JWT key for dev \n{}", jwtProperties.getDevToken());
|
||||
algorithm = Algorithm.HMAC256(jwtProperties.getDevToken());
|
||||
}
|
||||
verifier = JWT.require(algorithm)
|
||||
.withIssuer(ISSUER)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static String bytesToHex(byte[] bytes) {
|
||||
byte[] hexChars = new byte[bytes.length * 2];
|
||||
for (int j = 0; j < bytes.length; j++) {
|
||||
int v = bytes[j] & 0xFF;
|
||||
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
|
||||
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
|
||||
}
|
||||
return new String(hexChars, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public String generateToken(String login) {
|
||||
final Date issueDate = Date.from(LocalDate.now()
|
||||
.atStartOfDay(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
final Date expireDate = Date.from(LocalDate.now()
|
||||
.plusDays(15)
|
||||
.atStartOfDay(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
return JWT.create()
|
||||
.withIssuer(ISSUER)
|
||||
.withIssuedAt(issueDate)
|
||||
.withExpiresAt(expireDate)
|
||||
.withSubject(login)
|
||||
.sign(algorithm);
|
||||
}
|
||||
|
||||
private DecodedJWT validateToken(String token) {
|
||||
try {
|
||||
return verifier.verify(token);
|
||||
} catch (JWTVerificationException e) {
|
||||
throw new JwtException(String.format("Token verification error: %s", e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token) {
|
||||
if (!StringUtils.hasText(token)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
validateToken(token);
|
||||
return true;
|
||||
} catch (JwtException e) {
|
||||
LOG.error(e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<String> getLoginFromToken(String token) {
|
||||
try {
|
||||
return Optional.ofNullable(validateToken(token).getSubject());
|
||||
} catch (JwtException e) {
|
||||
LOG.error(e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,7 +1,5 @@
|
||||
package np.something.security;
|
||||
|
||||
import np.something.WebConfiguration;
|
||||
import np.something.controllers.CustomerController;
|
||||
import np.something.model.UserRole;
|
||||
import np.something.mvc.UserSignUp;
|
||||
import np.something.services.CustomerService;
|
||||
@ -16,12 +14,10 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
|
||||
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
|
||||
@ -33,13 +29,10 @@ import java.util.LinkedHashMap;
|
||||
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||
private static final String LOGIN_URL = "/login";
|
||||
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
|
||||
private final CustomerService customerService;
|
||||
private final JwtFilter jwtFilter;
|
||||
|
||||
public SecurityConfiguration(CustomerService customerService) {
|
||||
this.customerService = customerService;
|
||||
this.jwtFilter = new JwtFilter(customerService);
|
||||
createAdminOnStartup();
|
||||
}
|
||||
|
||||
@ -47,7 +40,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
final String admin = "admin";
|
||||
if (customerService.findByUsername(admin) == null) {
|
||||
log.info("Admin user successfully created");
|
||||
customerService.addCustomer(admin, admin, UserRole.ADMIN);
|
||||
customerService.addCustomer(admin, admin + admin, UserRole.ADMIN);
|
||||
}
|
||||
}
|
||||
|
||||
@ -62,31 +55,12 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
.antMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.formLogin()
|
||||
.formLogin().defaultSuccessUrl("/albums", true)
|
||||
.loginPage(LOGIN_URL).permitAll()
|
||||
.and()
|
||||
.logout().permitAll();
|
||||
}
|
||||
|
||||
// @Override
|
||||
// protected void configure(HttpSecurity http) throws Exception {
|
||||
// log.info("Creating security configuration");
|
||||
// http.cors()
|
||||
// .and()
|
||||
// .csrf().disable()
|
||||
// .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
// .and()
|
||||
// .authorizeRequests()
|
||||
// .antMatchers("/", SPA_URL_MASK).permitAll()
|
||||
// .antMatchers(HttpMethod.POST, WebConfiguration.REST_API + "/customer" + CustomerController.URL_LOGIN).permitAll()
|
||||
// .antMatchers(HttpMethod.POST, WebConfiguration.REST_API + "/customer").permitAll()
|
||||
// .anyRequest()
|
||||
// .authenticated()
|
||||
// .and()
|
||||
// .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
// .anonymous();
|
||||
// }
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.userDetailsService(customerService);
|
||||
@ -106,11 +80,11 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
@Bean
|
||||
public AuthenticationEntryPoint delegatingEntryPoint() {
|
||||
final LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> map = new LinkedHashMap();
|
||||
map.put(new AntPathRequestMatcher("/"), new LoginUrlAuthenticationEntryPoint("/login"));
|
||||
map.put(new AntPathRequestMatcher("/"), new LoginUrlAuthenticationEntryPoint(LOGIN_URL));
|
||||
map.put(new AntPathRequestMatcher("/api/1.0/**"), new Http403ForbiddenEntryPoint());
|
||||
|
||||
final DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(map);
|
||||
entryPoint.setDefaultEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
|
||||
entryPoint.setDefaultEntryPoint(new LoginUrlAuthenticationEntryPoint(LOGIN_URL));
|
||||
|
||||
return entryPoint;
|
||||
}
|
||||
|
85
src/main/java/np/something/services/AlbumService.java
Normal file
85
src/main/java/np/something/services/AlbumService.java
Normal file
@ -0,0 +1,85 @@
|
||||
package np.something.services;
|
||||
|
||||
import np.something.model.Album;
|
||||
import np.something.model.Customer;
|
||||
import np.something.model.Photo;
|
||||
import np.something.repositories.AlbumRepository;
|
||||
import np.something.repositories.CustomerRepository;
|
||||
import np.something.repositories.PhotoRepository;
|
||||
import np.something.util.validation.ValidatorUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class AlbumService {
|
||||
private final AlbumRepository albumRepository;
|
||||
private final CustomerRepository customerRepository;
|
||||
private final PhotoRepository photoRepository;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public AlbumService(AlbumRepository albumRepository, CustomerRepository customerRepository, PhotoRepository photoRepository, ValidatorUtil validatorUtil) {
|
||||
this.albumRepository = albumRepository;
|
||||
this.customerRepository = customerRepository;
|
||||
this.photoRepository = photoRepository;
|
||||
this.validatorUtil = validatorUtil;
|
||||
}
|
||||
|
||||
public Album find(Long id) {
|
||||
return albumRepository.findById(id).get();
|
||||
}
|
||||
|
||||
public List<Album> findAll() {
|
||||
return albumRepository.findAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Album add(String name, Customer owner) {
|
||||
Album album = new Album(name, owner);
|
||||
validatorUtil.validate(album);
|
||||
return albumRepository.save(album);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Album update(Long id, String name) {
|
||||
Album album = albumRepository.findById(id).get();
|
||||
album.setName(name);
|
||||
validatorUtil.validate(album);
|
||||
albumRepository.save(album);
|
||||
return album;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void delete(Long id) {
|
||||
albumRepository.deleteById(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void addPhoto(Long id) {
|
||||
Album album = albumRepository.findById(id).get();
|
||||
album.getPhotos().add(photoRepository.save(new Photo(album)));
|
||||
albumRepository.save(album);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void removePhoto(Long photo_id) {
|
||||
photoRepository.deleteById(photo_id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void addCustomer(Long album_id, Long customer_id) {
|
||||
Album album = albumRepository.findById(album_id).get();
|
||||
Customer customer = customerRepository.findById(customer_id).get();
|
||||
album.getCustomers().add(customer);
|
||||
albumRepository.save(album);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void removeCustomer(Long album_id, Long customer_id) {
|
||||
Album album = albumRepository.findById(album_id).get();
|
||||
Customer customer = customerRepository.findById(customer_id).get();
|
||||
album.getCustomers().remove(customer);
|
||||
albumRepository.save(album);
|
||||
}
|
||||
}
|
@ -1,74 +0,0 @@
|
||||
package np.something.services;
|
||||
|
||||
import np.something.Exceptions.CommentNotFoundException;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import np.something.model.Comment;
|
||||
import np.something.model.Customer;
|
||||
import np.something.model.Post;
|
||||
import np.something.repositories.CommentRepository;
|
||||
import np.something.util.validation.ValidatorUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class CommentService {
|
||||
private final CommentRepository commentRepository;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public CommentService(CommentRepository commentRepository,
|
||||
ValidatorUtil validatorUtil) {
|
||||
this.commentRepository = commentRepository;
|
||||
this.validatorUtil = validatorUtil;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Comment findComment(Long id) {
|
||||
final Optional<Comment> comment = commentRepository.findById(id);
|
||||
return comment.orElseThrow(() -> new CommentNotFoundException(id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Comment> findAllComments() {
|
||||
return commentRepository.findAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Comment addComment(Customer customer, Post post, String content) {
|
||||
final Comment comment = new Comment(customer, post, content);
|
||||
comment.setCreateDate(LocalDateTime.now());
|
||||
validatorUtil.validate(comment);
|
||||
customer.getComments().add(comment);
|
||||
post.getComments().add(comment);
|
||||
return commentRepository.save(comment);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Comment updateComment(Long id, String content) {
|
||||
final Comment currentComment = findComment(id);
|
||||
currentComment.setContent(content);
|
||||
validatorUtil.validate(currentComment);
|
||||
return commentRepository.save(currentComment);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Comment deleteComment(Long id) {
|
||||
final Comment currentComment = findComment(id);
|
||||
commentRepository.delete(currentComment);
|
||||
currentComment.getPost().getComments().remove(currentComment);
|
||||
currentComment.getCustomer().getComments().remove(currentComment);
|
||||
return currentComment;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllComments() {
|
||||
commentRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<Comment> searchComments(String tag) {
|
||||
return commentRepository.searchComments(tag);
|
||||
}
|
||||
}
|
@ -4,11 +4,10 @@ import javax.transaction.Transactional;
|
||||
|
||||
import np.something.DTO.CustomerDto;
|
||||
import np.something.Exceptions.CustomerNotFoundException;
|
||||
import np.something.Exceptions.JwtException;
|
||||
import np.something.model.Album;
|
||||
import np.something.model.Customer;
|
||||
import np.something.model.UserRole;
|
||||
import np.something.repositories.CustomerRepository;
|
||||
import np.something.security.JwtProvider;
|
||||
import np.something.util.validation.ValidatorUtil;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
@ -24,14 +23,12 @@ public class CustomerService implements UserDetailsService {
|
||||
private final CustomerRepository customerRepository;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtProvider jwtProvider;
|
||||
|
||||
public CustomerService(CustomerRepository customerRepository,
|
||||
ValidatorUtil validatorUtil, PasswordEncoder passwordEncoder, JwtProvider jwtProvider) {
|
||||
ValidatorUtil validatorUtil, PasswordEncoder passwordEncoder) {
|
||||
this.customerRepository = customerRepository;
|
||||
this.validatorUtil = validatorUtil;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.jwtProvider = jwtProvider;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@ -48,6 +45,7 @@ public class CustomerService implements UserDetailsService {
|
||||
public Customer addCustomer(String username, String password) {
|
||||
Customer customer = new Customer(username, passwordEncoder.encode(password));
|
||||
validatorUtil.validate(customer);
|
||||
customer.getAlbums().add(new Album("Стандартный", customer));
|
||||
return customerRepository.save(customer);
|
||||
}
|
||||
|
||||
@ -92,29 +90,4 @@ public class CustomerService implements UserDetailsService {
|
||||
return new org.springframework.security.core.userdetails.User(
|
||||
customerEntity.getUsername(), customerEntity.getPassword(), Collections.singleton(customerEntity.getRole()));
|
||||
}
|
||||
|
||||
public String loginAndGetToken(CustomerDto customerDto) {
|
||||
try {
|
||||
final Customer customer = findByUsername(customerDto.getUsername());
|
||||
if (customer == null) {
|
||||
throw new Exception("Login not found" + customerDto.getUsername());
|
||||
}
|
||||
if (!passwordEncoder.matches(customerDto.getPassword(), customer.getPassword())) {
|
||||
throw new Exception("User not found" + customer.getUsername());
|
||||
}
|
||||
return jwtProvider.generateToken(customer.getUsername());
|
||||
}
|
||||
catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
|
||||
if (!jwtProvider.isTokenValid(token)) {
|
||||
throw new JwtException("Bad token");
|
||||
}
|
||||
final String userLogin = jwtProvider.getLoginFromToken(token)
|
||||
.orElseThrow(() -> new JwtException("Token is not contain Login"));
|
||||
return loadUserByUsername(userLogin);
|
||||
}
|
||||
}
|
||||
|
52
src/main/java/np/something/services/PhotoService.java
Normal file
52
src/main/java/np/something/services/PhotoService.java
Normal file
@ -0,0 +1,52 @@
|
||||
package np.something.services;
|
||||
|
||||
import np.something.model.Photo;
|
||||
import np.something.model.Tag;
|
||||
import np.something.repositories.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class PhotoService {
|
||||
|
||||
private final PhotoRepository photoRepository;
|
||||
private final TagRepository tagRepository;
|
||||
|
||||
@Autowired
|
||||
public PhotoService(PhotoRepository photoRepository, TagRepository tagRepository) {
|
||||
this.photoRepository = photoRepository;
|
||||
this.tagRepository = tagRepository;
|
||||
}
|
||||
|
||||
public List<Photo> getAllPhotos() {
|
||||
return photoRepository.findAll();
|
||||
}
|
||||
|
||||
public Photo getPhotoById(Long id) {
|
||||
return photoRepository.findById(id).get();
|
||||
}
|
||||
|
||||
public Photo add() {
|
||||
return photoRepository.save(new Photo());
|
||||
}
|
||||
|
||||
public void delete(Long id) {
|
||||
photoRepository.deleteById(id);
|
||||
}
|
||||
|
||||
public void addTag(Long photo_id, Long tag_id) {
|
||||
Photo photo = photoRepository.findById(photo_id).get();
|
||||
Tag tag = tagRepository.findById(tag_id).get();
|
||||
photo.getTags().add(tag);
|
||||
photoRepository.save(photo);
|
||||
}
|
||||
|
||||
public void removeTag(Long photo_id, Long tag_id) {
|
||||
Photo photo = photoRepository.findById(photo_id).get();
|
||||
Tag tag = tagRepository.findById(tag_id).get();
|
||||
photo.getTags().remove(tag);
|
||||
photoRepository.save(photo);
|
||||
}
|
||||
}
|
@ -1,98 +0,0 @@
|
||||
package np.something.services;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
|
||||
import np.something.DTO.PostDto;
|
||||
import np.something.Exceptions.PostNotFoundException;
|
||||
import np.something.model.Customer;
|
||||
import np.something.model.Post;
|
||||
import np.something.repositories.CommentRepository;
|
||||
import np.something.repositories.PostRepository;
|
||||
import np.something.util.validation.ValidatorUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
public class PostService {
|
||||
private final PostRepository postRepository;
|
||||
private final CommentRepository commentRepository;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public PostService(PostRepository postRepository,
|
||||
CommentRepository commentRepository, ValidatorUtil validatorUtil) {
|
||||
this.postRepository = postRepository;
|
||||
this.commentRepository = commentRepository;
|
||||
this.validatorUtil = validatorUtil;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Post findPost(Long id) {
|
||||
return postRepository.findById(id).orElseThrow(() -> new PostNotFoundException(id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<Post> findAllPosts() {
|
||||
return postRepository.findAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Post addPost(Customer customer, String title, String content) {
|
||||
Post post = new Post(customer, title, content);
|
||||
post.setCreateDate(LocalDateTime.now());
|
||||
validatorUtil.validate(post);
|
||||
customer.getPosts().add(post);
|
||||
return postRepository.save(post);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Post updatePost(Long id, String title, String content) {
|
||||
Post post = findPost(id);
|
||||
post.setTitle(title);
|
||||
post.setContent(content);
|
||||
validatorUtil.validate(post);
|
||||
return postRepository.save(post);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Post deletePost(Long id) {
|
||||
Post post = findPost(id);
|
||||
post.getCustomer().getPosts().remove(post);
|
||||
postRepository.delete(post);
|
||||
return post;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllPosts() {
|
||||
postRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<PostDto> searchPosts(String search) {
|
||||
var posts = new ArrayList<>(postRepository.searchPosts(search));
|
||||
var comments = commentRepository.searchComments(search);
|
||||
for (var post: posts) {
|
||||
post.getComments().clear();
|
||||
}
|
||||
for (var comment: comments) {
|
||||
boolean found = false;
|
||||
for (var post: posts) {
|
||||
if (Objects.equals(comment.getPost().getId(), post.getId())) {
|
||||
post.getComments().add(comment);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
var newPost = comment.getPost();
|
||||
newPost.getComments().clear();
|
||||
newPost.getComments().add(comment);
|
||||
posts.add(newPost);
|
||||
}
|
||||
}
|
||||
return posts.stream().map(PostDto::new).toList();
|
||||
}
|
||||
}
|
71
src/main/java/np/something/services/TagService.java
Normal file
71
src/main/java/np/something/services/TagService.java
Normal file
@ -0,0 +1,71 @@
|
||||
package np.something.services;
|
||||
|
||||
import np.something.model.Album;
|
||||
import np.something.model.Customer;
|
||||
import np.something.model.Photo;
|
||||
import np.something.model.Tag;
|
||||
import np.something.repositories.AlbumRepository;
|
||||
import np.something.repositories.CustomerRepository;
|
||||
import np.something.repositories.PhotoRepository;
|
||||
import np.something.repositories.TagRepository;
|
||||
import np.something.util.validation.ValidatorUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Service
|
||||
public class TagService {
|
||||
private final AlbumRepository albumRepository;
|
||||
private final CustomerRepository customerRepository;
|
||||
private final PhotoRepository photoRepository;
|
||||
private final TagRepository tagRepository;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public TagService(AlbumRepository albumRepository, CustomerRepository customerRepository, PhotoRepository photoRepository, TagRepository tagRepository, ValidatorUtil validatorUtil) {
|
||||
this.albumRepository = albumRepository;
|
||||
this.customerRepository = customerRepository;
|
||||
this.photoRepository = photoRepository;
|
||||
this.tagRepository = tagRepository;
|
||||
this.validatorUtil = validatorUtil;
|
||||
}
|
||||
|
||||
public Tag find(Long id) {
|
||||
return tagRepository.findById(id).get();
|
||||
}
|
||||
|
||||
public List<Tag> findAll() {
|
||||
return tagRepository.findAll();
|
||||
}
|
||||
|
||||
public Tag add(String name) {
|
||||
Tag tag = new Tag(name);
|
||||
validatorUtil.validate(tag);
|
||||
return tagRepository.save(tag);
|
||||
}
|
||||
|
||||
public Tag update(Long id, String name) {
|
||||
Tag tag = tagRepository.findById(id).get();
|
||||
tag.setName(name);
|
||||
validatorUtil.validate(tag);
|
||||
return tagRepository.save(tag);
|
||||
}
|
||||
|
||||
public void delete(Long id) {
|
||||
tagRepository.deleteById(id);
|
||||
}
|
||||
|
||||
public List<Tag> tagsByTagPrefix(String prefix) {
|
||||
return tagRepository.findTagsByTagPrefix(prefix);
|
||||
}
|
||||
|
||||
public List<Photo> photosByTags(List<Long> ids) {
|
||||
return tagRepository.findPhotosByTags(ids, ids.size());
|
||||
}
|
||||
|
||||
public List<Photo> customersPhotosByTag(Customer customer, Long tag_id) {
|
||||
var albums = Stream.concat(customer.getAlbums().stream(), customer.getOwnedAlbums().stream());
|
||||
List<Photo> photos = albums.flatMap(x -> x.getPhotos().stream()).toList();
|
||||
return photosByTags(List.of(tag_id)).stream().filter(photos::contains).toList();
|
||||
}
|
||||
}
|
@ -1,8 +1,6 @@
|
||||
package np.something.util.error;
|
||||
|
||||
import np.something.Exceptions.CommentNotFoundException;
|
||||
import np.something.Exceptions.CustomerNotFoundException;
|
||||
import np.something.Exceptions.PostNotFoundException;
|
||||
import np.something.util.validation.ValidationException;
|
||||
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||||
import org.springframework.http.HttpStatus;
|
||||
@ -17,9 +15,7 @@ import java.util.stream.Collectors;
|
||||
@ControllerAdvice(annotations = RestController.class)
|
||||
public class AdviceController {
|
||||
@ExceptionHandler({
|
||||
CommentNotFoundException.class,
|
||||
CustomerNotFoundException.class,
|
||||
PostNotFoundException.class,
|
||||
ValidationException.class
|
||||
})
|
||||
public ResponseEntity<Object> handleException(Throwable e) {
|
||||
|
@ -1,103 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<div class="row mb-5">
|
||||
<p class='is-center h2'>Профили</p>
|
||||
</div>
|
||||
<div class="row mb-5">
|
||||
<div class="col"></div>
|
||||
<div class="col-10 is-center">
|
||||
<button class="button primary" data-bs-toggle="modal" data-bs-target="#customerCreate">
|
||||
Добавить нового пользователя
|
||||
</button>
|
||||
</div>
|
||||
<div class="col"></div>
|
||||
</div>
|
||||
|
||||
<p class='h3 is-center row mb-5'>Список профилей</p>
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<div class="row card mb-3">
|
||||
<div class="row">
|
||||
<div class="col-3 is-left h3 fw-bold" th:text="ID"></div>
|
||||
<div class="col-3 is-center h3 fw-bold" th:text="Никнейм"></div>
|
||||
<div class="col-3 is-right h3 fw-bold" th:text="Пароль"></div>
|
||||
<div class="col-2"></div>
|
||||
<div class="col-1"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div th:each="customer: ${customers}" class="row card mb-3">
|
||||
<div class="row">
|
||||
<div class="col-3 is-left h3" th:text="${customer.id}"></div>
|
||||
<a th:href="${ '/customers/' + customer.id}" class="col-3 is-center h3" th:text="${customer.username}"></a>
|
||||
<div class="col-3 is-right h3"><span th:text="${customer.password}" style="text-overflow: ellipsis; overflow: hidden; max-width: 10ch; white-space: nowrap"></span></div>
|
||||
|
||||
<button style="max-width: 66px; max-height: 38px;" th:data-username="${customer.username}" th:data-password="${customer.password}" th:data-id="${customer.id}" th:onclick="|prepareEditModal(this)|" class="button primary outline is-right" data-bs-toggle="modal" data-bs-target="#customerEdit"><i class="fa fa-pencil" aria-hidden="true"></i></button>
|
||||
|
||||
<form th:action="@{/admin/delete/{id}(id=${customer.id})}" method="post" class="col-1 is-right">
|
||||
<button class="button dark outline is-right" style="max-width: 66px; max-height: 38px;" type="submit"><i class="fa fa-trash" aria-hidden="true"></i></button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Modal -->
|
||||
<div class="modal fade" id="customerCreate" tabindex="-1" role="dialog" aria-labelledby="customerCreateLabel" aria-hidden="true">
|
||||
<div class="modal-dialog" role="document">
|
||||
<form class="modal-content" th:action="@{/admin/}" method="post">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="customerCreateLabel">Создать профиль</h5>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<p>Логин</p>
|
||||
<textarea name="username" id="usernameTextC" cols="30" rows="1"></textarea>
|
||||
<p>Пароль</p>
|
||||
<textarea name="password" id="passwordTextC" cols="30" rows="1"></textarea>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button type="submit" class="btn btn-primary">Сохранить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal -->
|
||||
<div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true">
|
||||
<div class="modal-dialog" role="document">
|
||||
<form class="modal-content" id="edit-customer-form" method="post">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="customerEditLabel">Редактировать профиль</h5>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<p>Логин</p>
|
||||
<textarea name="username" id="usernameTextE" cols="30" rows="1"></textarea>
|
||||
<p>Пароль</p>
|
||||
<textarea name="password" id="passwordTextE" cols="30" rows="1"></textarea>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button type="submit" class="btn btn-primary">Изменить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
<script th:inline="javascript">
|
||||
function prepareEditModal(btn) {
|
||||
document.getElementById('usernameTextE').value = btn.getAttribute("data-username");
|
||||
document.getElementById('passwordTextE').value = btn.getAttribute("data-password");
|
||||
document.getElementById('edit-customer-form').setAttribute('action', '/admin/' + btn.getAttribute("data-id"));
|
||||
}
|
||||
</script>
|
||||
</th:block>
|
||||
</html>
|
58
src/main/resources/templates/album.html
Normal file
58
src/main/resources/templates/album.html
Normal file
@ -0,0 +1,58 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<div class="row">
|
||||
<div class="col"></div>
|
||||
<form class="col card mb-5" method="POST" th:action="@{/albums/edit/{id}(id=${album.getId()})}">
|
||||
<div class="row mb-3">
|
||||
<label>Название альбома: <input name="name" pattern=".+{3,32}" required></label>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<button type="submit" class="button primary">Изменить</button>
|
||||
</div>
|
||||
</form>
|
||||
<form id="customerform" class="col" th:action="@{/albums/{id}/add/customer/(id=${album.getId()})}" method="POST" th:onsubmit="|document.getElementById('customerform').action += document.getElementById('select').value|">
|
||||
<select class="row mb-3" id="select">
|
||||
<option th:each="c : ${customers}" th:value="${c.getId()}" th:text="${c.getUsername()}"></option>
|
||||
</select>
|
||||
<div class="row mb-3">
|
||||
<button type="submit" class="button primary">Добавить пользователя</button>
|
||||
</div>
|
||||
</form>
|
||||
<form id="customeform" class="col" th:action="@{/albums/{id}/remove/customer/(id=${album.getId()})}" method="POST" th:onsubmit="|document.getElementById('customeform').action += document.getElementById('selectt').value|">
|
||||
<select class="row mb-3" id="selectt">
|
||||
<option th:each="c : ${album.getCustomers()}" th:value="${c.getId()}" th:text="${c.getUsername()}"></option>
|
||||
</select>
|
||||
<div class="row mb-3">
|
||||
<button type="submit" class="button primary">Убрать пользователя</button>
|
||||
</div>
|
||||
</form>
|
||||
<form class="col card mb-5" method="POST" th:action="@{/albums/{id}/add/photo(id=${album.getId()})}">
|
||||
<div class="row mb-3">
|
||||
<button type="submit" class="button primary">Добавить фотографию</button>
|
||||
</div>
|
||||
</form>
|
||||
<div class="col"></div>
|
||||
</div>
|
||||
<div class="row card mb-5" th:each="photo : ${photos}">
|
||||
<div class="col">
|
||||
<div class="row is-center"><img style="max-height: 300px; max-width: 300px" src="https://cdn.theatlantic.com/thumbor/viW9N1IQLbCrJ0HMtPRvXPXShkU=/0x131:2555x1568/976x549/media/img/mt/2017/06/shutterstock_319985324/original.jpg"></div>
|
||||
<div class="row is-center mb-2 h1" th:text="${'Фотография №' + photo.getId()}"></div>
|
||||
<div class="row is-center">
|
||||
<div class="col"><a class="button primary" th:href="@{/photos/{id}(id=${photo.getId()})}">Открыть</a></div>
|
||||
<form class="col" th:action="@{/photos/delete/{id}(id=${photo.getId()})}" method="POST"><button type="submit" class="button primary">Удалить</button></form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
</th:block>
|
||||
</html>
|
44
src/main/resources/templates/albums.html
Normal file
44
src/main/resources/templates/albums.html
Normal file
@ -0,0 +1,44 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<div class="row">
|
||||
<div class="col"></div>
|
||||
<form class="col card mb-5" method="POST">
|
||||
<div class="row mb-3">
|
||||
<label>Название альбома: <input name="name" pattern=".+{3,32}" required></label>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<button type="submit" class="button primary">Создать новый альбом</button>
|
||||
</div>
|
||||
</form>
|
||||
<div class="col"></div>
|
||||
</div>
|
||||
<div class="row card mb-5" th:each="album : ${ownerAlbums}">
|
||||
<div class="col">
|
||||
<div class="row is-center mb-2 h1" th:text="${album.getName()}"></div>
|
||||
<div class="row is-center">
|
||||
<div class="col"><a class="button primary" th:href="@{/albums/{id}(id=${album.getId()})}">Открыть</a></div>
|
||||
<form class="col" th:action="@{/albums/delete/{id}(id=${album.getId()})}" method="POST"><button type="submit" class="button primary">Удалить</button></form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row card mb-5" th:each="album : ${albums}">
|
||||
<div class="col">
|
||||
<div class="row is-center mb-2 h1" th:text="${album.getName()}"></div>
|
||||
<div class="row is-center">
|
||||
<div class="col"><a class="button primary" th:href="@{/albums/{id}(id=${album.getId()})}">Открыть</a></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
</th:block>
|
||||
</html>
|
@ -1,83 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<div class="row mb-5">
|
||||
<p class='is-center h2'>Профили</p>
|
||||
</div>
|
||||
|
||||
<p class='h3 is-center row mb-5'>Список профилей</p>
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<div th:each="customer: ${customers}" class="row card mb-3">
|
||||
<div class="row">
|
||||
<div class="col is-left h3" th:text="'ID: ' + ${customer.id}"></div>
|
||||
<div class="col is-right h3" th:text="'Никнейм: ' + ${customer.username}"></div>
|
||||
</div>
|
||||
<p class="row">Комментарии:</p>
|
||||
<div class="row" th:unless="${#arrays.isEmpty(customer.comments)}">
|
||||
<div class="col">
|
||||
<div th:each="comment: ${customer.comments}" class="row is-left card mb-3">
|
||||
<div class="row is-left h4" th:text="${'"' + comment.content + '"' + ' - к посту ' + '"' + comment.postTitle + '"' + ' от пользователя ' + comment.postAuthor}"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p th:if="${#arrays.isEmpty(customer.comments)}" class="row">Нет комментариев</p>
|
||||
<p class="row">Посты: </p>
|
||||
<div class="row" th:unless="${#arrays.isEmpty(customer.comments)}">
|
||||
<div class="col">
|
||||
<div th:each="post: ${customer.posts}" class="row is-left card mb-3">
|
||||
<div class="row is-center h1" th:text="${post.title}"></div>
|
||||
<div class="row is-left h3" th:text="${post.content}"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p th:if="${#arrays.isEmpty(customer.comments)}" class="row">Нет постов</p>
|
||||
<div class="row" th:if="${currentCustomerId == customer.id}">
|
||||
<form th:action="@{/customers/delete/{id}(id=${customer.id})}" method="post" class="col">
|
||||
<button class="button dark outline is-full-width" type="submit">Удалить</button>
|
||||
</form>
|
||||
<button th:data-username="${customer.username}" th:data-password="${customer.password}" th:data-id="${customer.id}" th:onclick="|prepareEditModal(this)|" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#customerEdit">Редактировать</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal -->
|
||||
<div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true">
|
||||
<div class="modal-dialog" role="document">
|
||||
<form class="modal-content" id="edit-customer-form" method="post">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="customerEditLabel">Редактировать профиль</h5>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<p>Логин</p>
|
||||
<textarea name="username" id="usernameTextE" cols="30" rows="1"></textarea>
|
||||
<p>Пароль</p>
|
||||
<textarea name="password" id="passwordTextE" cols="30" rows="1"></textarea>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button type="submit" class="btn btn-primary">Изменить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
<script th:inline="javascript">
|
||||
function prepareEditModal(btn) {
|
||||
document.getElementById('usernameTextE').value = btn.getAttribute("data-username");
|
||||
document.getElementById('passwordTextE').value = btn.getAttribute("data-password");
|
||||
document.getElementById('edit-customer-form').setAttribute('action', '/customers/' + btn.getAttribute("data-id"));
|
||||
}
|
||||
</script>
|
||||
</th:block>
|
||||
</html>
|
@ -7,16 +7,15 @@
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
|
||||
<link rel="stylesheet" href="https://unpkg.com/chota@latest">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<title>Социальная сеть</title>
|
||||
<title>Фотографии</title>
|
||||
</head>
|
||||
<body class="container">
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
|
||||
<div>
|
||||
<div class="nav row" th:with="activeLink=${#request.requestURI}">
|
||||
<div class="nav-left col-10">
|
||||
<a href="/customers/" class="button primary" th:classappend="${#strings.startsWith(activeLink, '/customers')} ? 'clear' : ''">Профили</a>
|
||||
<a href="/feed" class="button primary" th:classappend="${#strings.startsWith(activeLink, '/feed')} ? 'clear' : ''">Посты</a>
|
||||
<a sec:authorize="hasRole('ROLE_ADMIN')" href="/admin/" class="button primary" th:classappend="${#strings.startsWith(activeLink, '/admin')} ? 'clear' : ''">Администрирование</a>
|
||||
<a href="/albums" class="button primary" th:classappend="${#strings.startsWith(activeLink, '/customers')} ? 'clear' : ''">Альбомы</a>
|
||||
<a href="/tags" class="button primary" th:classappend="${#strings.startsWith(activeLink, '/customers')} ? 'clear' : ''">Тэги</a>
|
||||
</div>
|
||||
<div class="nav-right col-2">
|
||||
<a sec:authorize="!isAuthenticated()" href="/login" class="button primary" th:classappend="${#strings.startsWith(activeLink, '/login')} ? 'clear' : ''">Войти</a>
|
||||
|
@ -7,7 +7,7 @@
|
||||
<div class="alert alert-danger">
|
||||
<span th:text="${error}"></span>
|
||||
</div>
|
||||
<a href="/" class="is-center">На главную</a>
|
||||
<a href="/albums" class="is-center">На главную</a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -1,155 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<div class="row mb-5">
|
||||
<p class='is-center h2'>Посты</p>
|
||||
</div>
|
||||
<form class="row mb-5" action="/feed">
|
||||
<input type="search" name="search" class="col-10">
|
||||
<button class="button primary col" type="submit">Найти</button>
|
||||
</form>
|
||||
<div class="row mb-5" th:if="${currentCustomerId > 0}">
|
||||
<div class="col"></div>
|
||||
<form class="col-10" th:action="@{/posts/}" method="post">
|
||||
<input name="customerId" type="text" style="display: none;" th:value="${currentCustomerId}">
|
||||
<div class="row mb-4 is-center">
|
||||
<p class="col-2 is-left mb-2">Заголовок:</p>
|
||||
<input name="title" type="text" class="col-6" id="createPostTitle" />
|
||||
</div>
|
||||
<div class="row mb-4 is-center">
|
||||
<p class="col-2 is-left mb-2">Текст:</p>
|
||||
<textarea name="content" type="textarea" class="col-6" id="createPostContent"></textarea>
|
||||
</div>
|
||||
<div class="row is-center">
|
||||
<button type='submit' class="button primary col-8">
|
||||
Опубликовать
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<div class="col"></div>
|
||||
</div>
|
||||
<div th:unless="${#arrays.isEmpty(posts)}" class="row">
|
||||
<div class="col">
|
||||
<div class="row mb-5 card" th:each="post: ${posts}">
|
||||
<div class="col">
|
||||
<div class="row h3">
|
||||
<div class="col is-left">
|
||||
<p>Автор: <a th:href="${'/customers/' + post.customerId}" class="text-primary" th:text="${post.customerName}"></a></p>
|
||||
</div>
|
||||
<div class="col is-right">
|
||||
<p>Дата: <span class="text-primary" th:text="${post.createDate}"></span></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row text-center">
|
||||
<span class="h1" th:text="${post.title}"></span>
|
||||
</div>
|
||||
<div class="row text-center mb-5">
|
||||
<span class="h3" th:text="${post.content}"></span>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<p class="row h2 is-center mb-3">Комментарии</p>
|
||||
<div th:unless="${#arrays.isEmpty(post.comments)}" class="row text-left mb-5 card" th:each="comment: ${post.comments}">
|
||||
<div class="row mb-1">
|
||||
<div class="col is-left">
|
||||
<span class="h2 text-primary" th:text="${comment.customerName}"></span>
|
||||
</div>
|
||||
<div class="col is-right">
|
||||
<span class="h2 text-primary" th:text="${comment.createDate}"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<span class="h3" th:text="${comment.content}"></span>
|
||||
</div>
|
||||
<div th:if="${currentCustomerId == comment.customerId}" class="row">
|
||||
<button th:data-content="${comment.content}" th:data-id="${comment.id}" th:onclick="|prepareCommentEditModal(this)|" class="button primary outline col" data-bs-toggle="modal" data-bs-target="#commentEdit">Изменить комментарий</button>
|
||||
<form th:action="@{/comments/delete/{id}(id=${comment.id})}" method="post" class="col">
|
||||
<button type="submit" class="button error is-full-width">Удалить комментарий</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<p th:if="${#arrays.isEmpty(post.comments)}" class="h3 row is-center mb-5">Пусто</p>
|
||||
<form class="row" th:if="${currentCustomerId != -1}" th:action="@{/comments/}" method="post">
|
||||
<input name="content" type="text" class="col-9"/>
|
||||
<input name="customerId" type="text" style="display: none;" th:value="${currentCustomerId}">
|
||||
<input name="postId" type="text" style="display: none;" th:value="${post.id}">
|
||||
<button type="submit" class="button col-3 secondary outline">Комментировать</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row" th:if="${currentCustomerId == post.customerId}">
|
||||
<form class="col" th:action="@{/posts/delete/{id}(id=${post.id})}" method="post">
|
||||
<button type="submit" class="is-full-width button dark outline">Удалить пост</button>
|
||||
</form>
|
||||
<button th:data-customer="${currentCustomerId}" th:data-id="${post.id}" th:data-title="${post.title}" th:data-content="${post.content}" type="button" th:onclick="|preparePostEditModal(this)|" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#postEdit">Изменить пост</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div th:if="${#arrays.isEmpty(posts)}" class="row text-center is-center">
|
||||
Нет постов
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal -->
|
||||
<div class="modal fade" id="commentEdit" tabindex="-1" role="dialog" aria-labelledby="commentEditLabel" aria-hidden="true">
|
||||
<div class="modal-dialog" role="document">
|
||||
<form method="post" class="modal-content" id="editComment">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="commentEditLabel">Изменить комментарий</h5>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<textarea name='content' id="editModalText" cols="30" rows="1"></textarea>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button type="submit" class="btn btn-primary">Изменить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal -->
|
||||
<div class="modal fade" id="postEdit" tabindex="-1" role="dialog" aria-labelledby="postEditLabel" aria-hidden="true">
|
||||
<div class="modal-dialog" role="document">
|
||||
<form class="modal-content" id="editPost">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="postEditLabel">Редактировать пост</h5>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<p>Заголовок</p>
|
||||
<textarea name="title" id="editModalTitle" cols="30" rows="1"></textarea>
|
||||
<p>Содержание</p>
|
||||
<textarea name="content" id="editModalPostContent" cols="30" rows="1"></textarea>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button type="submit" class="btn btn-primary">Изменить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
<script th:inline="javascript">
|
||||
function prepareCommentEditModal(btn) {
|
||||
document.getElementById('editModalText').value = btn.getAttribute("data-content");
|
||||
document.getElementById('editComment').setAttribute('action', '/comments/' + btn.getAttribute("data-id"));
|
||||
}
|
||||
|
||||
function preparePostEditModal(btn) {
|
||||
document.getElementById('editModalTitle').value = btn.getAttribute("data-title");
|
||||
document.getElementById('editModalPostContent').value = btn.getAttribute("data-content");
|
||||
document.getElementById('editPost').setAttribute('action', '/posts/' + btn.getAttribute("data-id"));
|
||||
}
|
||||
</script>
|
||||
</th:block>
|
||||
</html>
|
@ -8,10 +8,10 @@
|
||||
<div class="col"></div>
|
||||
<form class="col-6" action="/login" method="post">
|
||||
<div class="row">
|
||||
<label>Логин: <input type="text" name="username" required /></label>
|
||||
<label>Логин: <input type="text" name="username" pattern=".+{3, 32}" required /></label>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label>Пароль: <input type="password" name="password" id="password" required /></label>
|
||||
<label>Пароль: <input type="password" name="password" id="password" pattern=".+{8, 32}" required /></label>
|
||||
</div>
|
||||
<div class="row mt-3">
|
||||
<div class="col-4"></div>
|
||||
|
37
src/main/resources/templates/photo.html
Normal file
37
src/main/resources/templates/photo.html
Normal file
@ -0,0 +1,37 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<div class="row card">
|
||||
<form id="tagform" class="col" th:action="@{/photos/{id}/add/tag/(id=${photo.getId()})}" method="POST" th:onsubmit="|document.getElementById('tagform').action += document.getElementById('select').value|">
|
||||
<select name="name" class="row" id="select">
|
||||
<option th:each="tag : ${tags}" th:value="${tag.getId()}" th:text="${tag.getName()}"></option>
|
||||
</select>
|
||||
<button class="row" type="submit">Добавить</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="row card">
|
||||
<div class="col">
|
||||
<div class="row mb-2 is-center"><img style="max-height: 300px; max-width: 300px" src="https://cdn.theatlantic.com/thumbor/viW9N1IQLbCrJ0HMtPRvXPXShkU=/0x131:2555x1568/976x549/media/img/mt/2017/06/shutterstock_319985324/original.jpg"></div>
|
||||
<div class="row is-center mb-2 h1" th:text="${'Фотография №' + photo.getId()}"></div>
|
||||
<div class="row">
|
||||
<div class="col card" th:each="tag : ${photo.getTags()}">
|
||||
<span th:text="${tag.getName()}"></span>
|
||||
<form method="POST" th:action="@{/photos/{id}/remove/tag/{tag_id}(id=${photo.getId()}, tag_id=${tag.getId()})}">
|
||||
<button type="submit" class="button primary">Удалить тэг</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
</th:block>
|
||||
</html>
|
36
src/main/resources/templates/tag.html
Normal file
36
src/main/resources/templates/tag.html
Normal file
@ -0,0 +1,36 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<div class="row">
|
||||
<div class="col"></div>
|
||||
<form class="col card mb-5" method="POST" th:action="@{/tags/edit/{id}(id=${tag.getId()})}">
|
||||
<div class="row mb-3">
|
||||
<label>Название тэга: <input name="name" pattern=".+{3,32}" required></label>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<button type="submit" class="button primary">Изменить</button>
|
||||
</div>
|
||||
</form>
|
||||
<div class="col"></div>
|
||||
</div>
|
||||
<div class="row card mb-5" th:each="photo : ${photos}">
|
||||
<div class="col">
|
||||
<div class="row is-center"><img style="max-height: 300px; max-width: 300px" src="https://cdn.theatlantic.com/thumbor/viW9N1IQLbCrJ0HMtPRvXPXShkU=/0x131:2555x1568/976x549/media/img/mt/2017/06/shutterstock_319985324/original.jpg"></div>
|
||||
<div class="row is-center mb-2 h1" th:text="${'Фотография №' + photo.getId()}"></div>
|
||||
<div class="row is-center">
|
||||
<div class="col"><a class="button primary" th:href="@{/photos/{id}(id=${photo.getId()})}">Открыть</a></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
</th:block>
|
||||
</html>
|
42
src/main/resources/templates/tags.html
Normal file
42
src/main/resources/templates/tags.html
Normal file
@ -0,0 +1,42 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<div class="row">
|
||||
<form class="col card mb-5" method="POST">
|
||||
<div class="row mb-3">
|
||||
<label>Название тэга: <input name="name" pattern=".+{3,32}" required></label>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<button type="submit" class="button primary">Создать новый тэг</button>
|
||||
</div>
|
||||
</form>
|
||||
<form class="col card mb-5" method="GET">
|
||||
<div class="row mb-3">
|
||||
<label>Поиск по тэгам: <input name="search" pattern=".+{3,32}"></label>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<button type="submit" class="button primary">Искать</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="row card mb-5" th:each="tag : ${tags}">
|
||||
<div class="col">
|
||||
<div class="row is-center mb-2 h1" th:text="${tag.getName()}"></div>
|
||||
<div class="row is-center">
|
||||
<div class="col"><a class="button primary" th:href="@{/tags/{id}(id=${tag.getId()})}">Открыть</a></div>
|
||||
<form class="col" th:action="@{/tags/delete/{id}(id=${tag.getId()})}" method="POST"><button type="submit" class="button primary">Удалить</button></form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
</th:block>
|
||||
</html>
|
@ -1,123 +0,0 @@
|
||||
package np.something;
|
||||
|
||||
import np.something.model.*;
|
||||
import np.something.services.CommentService;
|
||||
import np.something.services.CustomerService;
|
||||
import np.something.services.PostService;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
public class SocialNetworkTest {
|
||||
@Autowired
|
||||
CustomerService customerService;
|
||||
|
||||
@Autowired
|
||||
CommentService commentService;
|
||||
|
||||
@Autowired
|
||||
PostService postService;
|
||||
|
||||
@Test
|
||||
void testCustomers() {
|
||||
commentService.deleteAllComments();
|
||||
postService.deleteAllPosts();
|
||||
customerService.deleteAllCustomers();
|
||||
|
||||
Customer c1 = customerService.addCustomer("first", "1");
|
||||
Customer c2 = customerService.addCustomer("second", "2");
|
||||
Customer c3 = customerService.addCustomer("third", "3");
|
||||
|
||||
Assertions.assertEquals("first", c1.getUsername());
|
||||
Assertions.assertEquals("second", c2.getUsername());
|
||||
Assertions.assertEquals("third", c3.getUsername());
|
||||
|
||||
Assertions.assertEquals(c1, customerService.findCustomer(c1.getId()));
|
||||
|
||||
customerService.deleteCustomer(c2.getId());
|
||||
|
||||
Assertions.assertEquals(2, customerService.findAllCustomers().size());
|
||||
|
||||
Customer c4 = customerService.updateCustomer(c3.getId(), "fourth", "4");
|
||||
|
||||
Assertions.assertNotEquals(c3.getUsername(), c4.getUsername());
|
||||
Assertions.assertNotEquals(c3.getPassword(), c4.getPassword());
|
||||
|
||||
commentService.deleteAllComments();
|
||||
postService.deleteAllPosts();
|
||||
customerService.deleteAllCustomers();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPost() {
|
||||
commentService.deleteAllComments();
|
||||
postService.deleteAllPosts();
|
||||
customerService.deleteAllCustomers();
|
||||
|
||||
Customer c1 = customerService.addCustomer("first", "1");
|
||||
Customer c2 = customerService.addCustomer("second", "2");
|
||||
|
||||
Post p1 = postService.addPost(c1, "first title", "nonsense");
|
||||
Post p2 = postService.addPost(c2, "second title", "ordinal");
|
||||
|
||||
Assertions.assertEquals(2, postService.findAllPosts().size());
|
||||
|
||||
Assertions.assertEquals(p1.getCustomer(), c1);
|
||||
Assertions.assertEquals(p2.getCustomer(), c2);
|
||||
|
||||
Assertions.assertEquals(c1.getPosts().get(0), p1);
|
||||
Assertions.assertEquals(c2.getPosts().get(0), p2);
|
||||
|
||||
Assertions.assertEquals(p1, postService.findPost(p1.getId()));
|
||||
Assertions.assertEquals(p2, postService.findPost(p2.getId()));
|
||||
|
||||
Post p3 = postService.addPost(c1, "asdf", "asd");
|
||||
postService.deletePost(p1.getId());
|
||||
Assertions.assertEquals(1, customerService.findCustomer(c1.getId()).getPosts().size());
|
||||
|
||||
Post p4 = postService.updatePost(p2.getId(), "third title", "wow");
|
||||
|
||||
Assertions.assertNotEquals(p2.getTitle(), p4.getTitle());
|
||||
Assertions.assertNotEquals(p2.getContent(), p4.getContent());
|
||||
|
||||
commentService.deleteAllComments();
|
||||
postService.deleteAllPosts();
|
||||
customerService.deleteAllCustomers();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testComment() {
|
||||
commentService.deleteAllComments();
|
||||
postService.deleteAllPosts();
|
||||
customerService.deleteAllCustomers();
|
||||
|
||||
Customer c1 = customerService.addCustomer("first", "1");
|
||||
Customer c2 = customerService.addCustomer("second", "2");
|
||||
|
||||
Post p1 = postService.addPost(c1, "first title", "nonsense");
|
||||
Post p2 = postService.addPost(c2, "second title", "ordinal");
|
||||
|
||||
Assertions.assertEquals(2, postService.findAllPosts().size());
|
||||
|
||||
Comment com1 = commentService.addComment(c1, p2, "What");
|
||||
Comment com2 = commentService.addComment(c2, p1, "How");
|
||||
|
||||
Assertions.assertEquals(c1, p2.getComments().get(0).getCustomer());
|
||||
Assertions.assertEquals(c2, p1.getComments().get(0).getCustomer());
|
||||
|
||||
Comment com3 = commentService.addComment(c1, p1, "Really");
|
||||
|
||||
Assertions.assertEquals(com2, commentService.findComment(p1.getComments().get(0).getId()));
|
||||
|
||||
Comment com4 = commentService.updateComment(com3.getId(), "Not really");
|
||||
|
||||
Assertions.assertNotEquals(com3.getContent(), com4.getContent());
|
||||
Assertions.assertEquals(com3.getCustomer().getId(), com4.getCustomer().getId());
|
||||
|
||||
commentService.deleteAllComments();
|
||||
postService.deleteAllPosts();
|
||||
customerService.deleteAllCustomers();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user