Skip to content

Commit

Permalink
Merge pull request #42 from CodeURJC-DAW-2022-23/fix/rest-urls
Browse files Browse the repository at this point in the history
Fix: api rest urls and methods
  • Loading branch information
franchescoURJC authored Apr 4, 2023
2 parents 42f3468 + b26f856 commit 36252d4
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
import net.daw.alist.models.User;
import net.daw.alist.services.PostService;

import java.util.Optional;

@RestController
@RequestMapping("/api/ajax")
@RequestMapping("/api/posts")
public class AjaxRestController {

@Autowired
Expand All @@ -31,26 +33,19 @@ public class AjaxRestController {
@Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = Post.class)))}),
@ApiResponse(responseCode = "404", description = "No new posts found", content = @Content)
})
@GetMapping("/posts")
public Page<Post> getNewPosts(@RequestParam int page) {
if (page <= (int) Math.ceil(postService.count() / 2))
@GetMapping("")
public Page<Post> getNewPosts(Authentication authentication, @RequestParam int page, @RequestParam Optional<Boolean> filter) {
boolean validPage = page <= (int) Math.ceil(postService.count()/2);
boolean filterPosts = false;
if(filter.isPresent()){
filterPosts = filter.get();
}
if((authentication != null) && filterPosts && validPage){
User currentUser = (User) authentication.getPrincipal();
return postService.getStarredPosts(page, currentUser.getId().intValue());
} else if (validPage)
return postService.getPosts(page);
return null;
}

@Operation(summary = "Load more posts from followed-users")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "New posts loaded", content = {
@Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = Post.class)))}),
@ApiResponse(responseCode = "404", description = "No new posts found", content = @Content)
})
@GetMapping("/followed-users/posts")
public Page<Post> getFollowedUsersPosts(Authentication authentication, @RequestParam int page) {
User currentUser = (User) authentication.getPrincipal();

if (page <= (int) Math.ceil(postService.count()/2))
return postService.getStarredPosts(page, currentUser.getId().intValue());

return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public ResponseEntity<Comment> createComment(@RequestBody Data content, @PathVar
@Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = Comment.class)))}),
@ApiResponse(responseCode = "404", description = "Post not found", content = @Content)
})
@GetMapping("/post/{postId}")
@GetMapping("/posts/{postId}")
public ResponseEntity<List<Comment>> getPostComments(@PathVariable long postId) {
Optional<Post> optionalPost = postService.findByID(postId);
if (optionalPost.isPresent()) {
Expand Down Expand Up @@ -121,7 +121,7 @@ public ResponseEntity<Post> deleteComment(@PathVariable long postId, @PathVariab
@Getter
@Setter
@EqualsAndHashCode
public static class Data {
private static class Data {
private final String content;
private final String imagePath;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,22 @@
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import net.daw.alist.models.Post;
import net.daw.alist.models.PostItem;
import net.daw.alist.models.Topic;
import net.daw.alist.models.User;
import net.daw.alist.services.PostService;
import net.daw.alist.services.UserService;
import net.daw.alist.services.VotesService;
import net.daw.alist.services.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

Expand All @@ -27,27 +32,43 @@ public class PostRestController {
@Autowired
private PostService postService;

@Autowired
private PostItemService postItemService;

@Autowired
private TopicService topicService;

@Autowired
private UserService userService;

@Autowired
private VotesService votesService;


@Operation(summary = "Create new post")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Post created", content = {
@Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = Post.class)))
}),
@ApiResponse(responseCode = "403", description = "Can't create post if not registered", content = @Content)
@ApiResponse(responseCode = "403", description = "Can't create post if not registered", content = @Content),
@ApiResponse(responseCode = "400", description = "Bad formatting", content = @Content)
})
@PostMapping("/")
@ResponseStatus(HttpStatus.CREATED)
public Post createPost(Authentication auth, Post post) {
if (auth != null) {
postService.save(post);
return post;
public ResponseEntity<Post> createPost(Authentication auth, @RequestBody Data content) {
if (content.getTitle() == null || content.getTopicStrings() == null || content.getItems() == null)
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

User author = (User) auth.getPrincipal();
author = userService.findByID(author.getId()).orElseThrow();
List<PostItem> items = content.getItems();
for (PostItem item: items) {
postItemService.save(item);
}
return null;
List<Topic> topicList = topicService.getTopics(content.getTopicStrings());
Post post = new Post(author, content.getTitle(), topicList, items);
postService.save(post);
return new ResponseEntity<>(post, HttpStatus.CREATED);

}

@Operation(summary = "Get specific post")
Expand Down Expand Up @@ -135,4 +156,13 @@ public ResponseEntity<Post> downvotePost(Authentication authentication, @PathVar
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

@AllArgsConstructor
@Getter
@Setter
@EqualsAndHashCode
private static class Data {
private final String title;
private final List<String> topicStrings;
private final List<PostItem> items;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import net.daw.alist.models.Topic;
import net.daw.alist.services.TopicService;
import net.daw.alist.utils.Utils;
Expand Down Expand Up @@ -52,10 +56,13 @@ public ResponseEntity<Topic> getTopic(@PathVariable long topicId) {
@ApiResponse(responseCode = "403", description = "Create topic only for admin", content = @Content)
})
@PostMapping("/")
public ResponseEntity<Topic> createTopic(Authentication auth, Topic topic) {
if (auth == null) return new ResponseEntity<>(HttpStatus.FORBIDDEN);
public ResponseEntity<Topic> createTopic(Authentication auth, @RequestBody Data content) {
if (auth == null)
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
boolean isAdmin = utils.getCurrentUserRole(auth).equals("ADMIN");
if (!isAdmin) return new ResponseEntity<>(HttpStatus.FORBIDDEN);
if (!isAdmin)
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
Topic topic = new Topic(content.getName(), content.getDescription());
topicService.save(topic);
return new ResponseEntity<>(topic, HttpStatus.CREATED);
}
Expand All @@ -82,4 +89,13 @@ public ResponseEntity<Topic> deleteTopic(Authentication auth, @PathVariable long
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

@AllArgsConstructor
@Getter
@Setter
@EqualsAndHashCode
private static class Data {
private final String name;
private final String description;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -72,31 +72,38 @@ public ResponseEntity<User> getUser(@PathVariable String username) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

@Operation(summary = "(Admin) Ban/unban user by its id")
@Operation(summary = "Edit user by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User found and banned/unbanned state changed", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = User.class))}),
@ApiResponse(responseCode = "403", description = "Admin access required", content = @Content),
@ApiResponse(responseCode = "404", description = "User not found", content = @Content)
@ApiResponse(responseCode = "404", description = "User not found", content = @Content),
@ApiResponse(responseCode = "400", description = "Operation doesn't exist", content = @Content)
})
@PutMapping ("/{id}")
public ResponseEntity<User> banUser(Authentication authentication, @PathVariable Long id) {
String userRole = utils.getCurrentUserRole(authentication);
if (!userRole.equals("ADMIN"))
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
public ResponseEntity<User> userOperation(Authentication authentication, @PathVariable Long id, @RequestParam String operation) {
Optional<User> optionalUser = userService.findByID(id);
if (optionalUser.isPresent()) {
User user = optionalUser.get();
if (user.isLocked()) {
userService.unbanUser(user.getUsername());
user.setLocked(false);
} else {
userService.banUser(user.getUsername());
user.setLocked(true);
}
return new ResponseEntity<>(user, HttpStatus.OK);
if (optionalUser.isEmpty())
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
String userRole = utils.getCurrentUserRole(authentication);

User user = optionalUser.get();
switch (operation){
case("ban"):
if (!userRole.equals("ADMIN"))
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
if (user.isLocked()) {
userService.unbanUser(user.getUsername());
user.setLocked(false);
} else {
userService.banUser(user.getUsername());
user.setLocked(true);
}
return new ResponseEntity<>(user, HttpStatus.OK);
//case("profile"):...
//Add more operations here
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}

@Operation(summary = "Current user follows another user by its name")
Expand All @@ -106,7 +113,7 @@ public ResponseEntity<User> banUser(Authentication authentication, @PathVariable
@ApiResponse(responseCode = "403", description = "Current user not logged in", content = @Content),
@ApiResponse(responseCode = "404", description = "User not found", content = @Content)
})
@PutMapping("/{username}/follows")
@PutMapping("/followers/{username}")
public ResponseEntity<User> follow(Authentication authentication, @PathVariable String username){
Optional<User> optionalUser = userService.findByUsername(username);
User userSession = (User) authentication.getPrincipal();
Expand Down
3 changes: 3 additions & 0 deletions back/src/main/java/net/daw/alist/models/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.EqualsAndHashCode;
import org.springframework.security.core.GrantedAuthority;
Expand Down Expand Up @@ -95,6 +96,7 @@ public void setUsername(String username) {
this.username = username;
}

@JsonProperty
public void setPassword(String password) {
this.password = password;
}
Expand Down Expand Up @@ -144,6 +146,7 @@ public String getUsername() {
return username;
}

@JsonIgnore
@Override
public String getPassword() {
return password;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ protected void configure(HttpSecurity http) throws Exception {
// URLs that need authentication to access to it
http
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/ajax/followed-users/posts").hasAnyRole("ADMIN", "USER")
.antMatchers(HttpMethod.POST, "/api/comments/**").hasAnyRole("ADMIN", "USER")
.antMatchers(HttpMethod.DELETE, "/api/comments/**").hasAnyRole("ADMIN", "USER")
.antMatchers(HttpMethod.POST, "/api/posts/**").hasAnyRole("ADMIN", "USER")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,8 @@ public Optional<PostItem> findById(Long id) {
return this.postItemRepository.findById(id);
}

public void save(PostItem item){
postItemRepository.save(item);
}

}

0 comments on commit 36252d4

Please sign in to comment.