Skip to content

Commit

Permalink
Update api
Browse files Browse the repository at this point in the history
  • Loading branch information
ajaynegi45 committed Nov 15, 2024
1 parent 72bba58 commit 2aac646
Show file tree
Hide file tree
Showing 8 changed files with 58 additions and 47 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,11 @@
<version>3.3.4</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

</dependencies>

<build>
Expand Down
14 changes: 7 additions & 7 deletions src/main/java/com/libraryman_api/book/BookController.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
* updating an existing book, and deleting a book.
*/
@RestController
@RequestMapping("/api/books")
@RequestMapping("/api")
public class BookController {

@Autowired
Expand All @@ -34,7 +34,7 @@ public class BookController {
* @return a {@link Page} of {@link BookDto} objects representing the books in the library.
* The results are sorted by title by default and limited to 5 books per page.
*/
@GetMapping
@GetMapping("/get-all-books")
public Page<BookDto> getAllBooks(@PageableDefault(page = 0, size = 5, sort = "title") Pageable pageable,
@RequestParam(required = false) String sortBy,
@RequestParam(required = false) String sortDir) {
Expand All @@ -59,7 +59,7 @@ public Page<BookDto> getAllBooks(@PageableDefault(page = 0, size = 5, sort = "ti
* @return a {@link ResponseEntity} containing the {@link Book} object, if found.
* @throws ResourceNotFoundException if the book with the specified ID is not found.
*/
@GetMapping("/{id}")
@GetMapping("get-book-by-id/{id}")
public ResponseEntity<BookDto> getBookById(@PathVariable int id) {
return bookService.getBookById(id)
.map(ResponseEntity::ok)
Expand All @@ -72,7 +72,7 @@ public ResponseEntity<BookDto> getBookById(@PathVariable int id) {
* @param bookDto the {@link Book} object representing the new book to add.
* @return the added {@link Book} object.
*/
@PostMapping
@PostMapping("/add-book")
@PreAuthorize("hasRole('LIBRARIAN') or hasRole('ADMIN')")
public BookDto addBook(@Valid @RequestBody BookDto bookDto) {
return bookService.addBook(bookDto);
Expand All @@ -85,7 +85,7 @@ public BookDto addBook(@Valid @RequestBody BookDto bookDto) {
* @param bookDtoDetails the {@link Book} object containing the updated book details.
* @return the updated {@link Book} object.
*/
@PutMapping("/{id}")
@PutMapping("update-book/{id}")
@PreAuthorize("hasRole('LIBRARIAN') or hasRole('ADMIN')")
public BookDto updateBook(@PathVariable int id, @Valid @RequestBody BookDto bookDtoDetails) {
return bookService.updateBook(id, bookDtoDetails);
Expand All @@ -96,7 +96,7 @@ public BookDto updateBook(@PathVariable int id, @Valid @RequestBody BookDto book
*
* @param id the ID of the book to delete.
*/
@DeleteMapping("/{id}")
@DeleteMapping("delete-book/{id}")
@PreAuthorize("hasRole('LIBRARIAN') or hasRole('ADMIN')")
public void deleteBook(@PathVariable int id) {
bookService.deleteBook(id);
Expand All @@ -112,7 +112,7 @@ public void deleteBook(@PathVariable int id) {
* @param pageable
* @return
*/
@GetMapping("/search")
@GetMapping("book/search")
public ResponseEntity<Page<Book>> searchBook(@RequestParam String keyword, @PageableDefault(page = 0, size = 5, sort = "title") Pageable pageable) {
Page<Book> books = bookService.searchBook(keyword, pageable);
if (!books.isEmpty())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* paying fines, and retrieving borrowing records.
*/
@RestController
@RequestMapping("/api/borrowings")
@RequestMapping("/api")
public class BorrowingController {

private final BorrowingService borrowingService;
Expand All @@ -39,7 +39,7 @@ public BorrowingController(BorrowingService borrowingService) {
* @return a {@link Page} of {@link Borrowings} representing all borrowings.
* The results are sorted by borrow date by default and limited to 5 members per page.
*/
@GetMapping
@GetMapping("/get-all-borrowings")
@PreAuthorize("hasRole('LIBRARIAN') or hasRole('ADMIN')")
public Page<BorrowingsDto> getAllBorrowings(@PageableDefault(page = 0, size = 5, sort = "borrowDate") Pageable pageable,
@RequestParam(required = false) String sortBy,
Expand All @@ -65,7 +65,7 @@ public Page<BorrowingsDto> getAllBorrowings(@PageableDefault(page = 0, size = 5,
* @param borrowingsDto the {@link Borrowings} object containing borrowing details.
* @return the saved {@link Borrowings} object representing the borrowing record.
*/
@PostMapping
@PostMapping("/borrow-book")
@PreAuthorize("hasRole('LIBRARIAN') or hasRole('ADMIN') or (hasRole('USER') and #borrowingsDto.member.memberId == authentication.principal.memberId)")
public BorrowingsDto borrowBook(@Valid @RequestBody BorrowingsDto borrowingsDto) {
return borrowingService.borrowBook(borrowingsDto);
Expand All @@ -76,7 +76,7 @@ public BorrowingsDto borrowBook(@Valid @RequestBody BorrowingsDto borrowingsDto)
*
* @param id the ID of the borrowing record to update.
*/
@PutMapping("/{id}/return")
@PutMapping("/{id}/return-borrow-book")
public BorrowingsDto returnBook(@PathVariable int id) {
return borrowingService.returnBook(id);
}
Expand All @@ -87,7 +87,7 @@ public BorrowingsDto returnBook(@PathVariable int id) {
* @param id the ID of the borrowing record for which the fine is being paid.
* @return a message indicating the payment status.
*/
@PutMapping("/{id}/pay")
@PutMapping("/borrowing/{id}/pay-fine")
public String payFine(@PathVariable int id) {
System.out.println("Pay Fine Id: " + id);
return borrowingService.payFine(id);
Expand All @@ -103,7 +103,7 @@ public String payFine(@PathVariable int id) {
* @return a {@link Page} of {@link Borrowings} representing all borrowings for a specific member.
* The results are sorted by borrow date by default and limited to 5 members per page.
*/
@GetMapping("member/{memberId}")
@GetMapping("/get-all-borrowings-of-a-member/{memberId}")
@PreAuthorize("hasRole('LIBRARIAN') or hasRole('ADMIN') or (hasRole('USER') and #memberId == authentication.principal.memberId)")
public Page<BorrowingsDto> getAllBorrowingsOfAMember(@PathVariable int memberId,
@PageableDefault(page = 0, size = 5, sort = "borrowDate") Pageable pageable,
Expand Down Expand Up @@ -131,7 +131,7 @@ public Page<BorrowingsDto> getAllBorrowingsOfAMember(@PathVariable int memberId,
* @return the {@link Borrowings} object representing the borrowing record.
* @throws ResourceNotFoundException if the borrowing record with the specified ID is not found.
*/
@GetMapping("{borrowingId}")
@GetMapping("/get-borrowing-by-id/{borrowingId}")
@PreAuthorize("hasRole('LIBRARIAN') or hasRole('ADMIN')")
public BorrowingsDto getBorrowingById(@PathVariable int borrowingId) {
return borrowingService.getBorrowingById(borrowingId)
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/libraryman_api/fine/Fine.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class Fine {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "fine_id_generator")
@SequenceGenerator(name = "fine_id_generator", sequenceName = "fine_id_sequence", allocationSize = 1)
@Column(name = "fine_id", updatable = false, nullable = false)
@Column(updatable = false, nullable = false)
private int fineId;

/**
Expand Down
12 changes: 6 additions & 6 deletions src/main/java/com/libraryman_api/member/MemberController.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
* This controller provides endpoints for performing CRUD operations on members.
*/
@RestController
@RequestMapping("/api/members")
@RequestMapping("/api")
public class MemberController {

private final MemberService memberService;
Expand All @@ -42,7 +42,7 @@ public MemberController(MemberService memberService) {
* @return a {@link Page} of {@link Members} representing all members in the library.
* The results are sorted by name by default and limited to 5 members per page.
*/
@GetMapping
@GetMapping("/get-all-members")
@PreAuthorize("hasRole('LIBRARIAN') or hasRole('ADMIN')")
public Page<MembersDto> getAllMembers(@PageableDefault(page = 0, size = 5, sort = "name") Pageable pageable,
@RequestParam(required = false) String sortBy,
Expand All @@ -69,7 +69,7 @@ public Page<MembersDto> getAllMembers(@PageableDefault(page = 0, size = 5, sort
* @param id the ID of the member to retrieve
* @return a {@link ResponseEntity} containing the found {@link Members} object
*/
@GetMapping("/{id}")
@GetMapping("/get-member-by-id/{id}")
@PreAuthorize("hasRole('LIBRARIAN') or hasRole('ADMIN')")
public ResponseEntity<MembersDto> getMemberById(@PathVariable int id) {
return memberService.getMemberById(id)
Expand All @@ -85,7 +85,7 @@ public ResponseEntity<MembersDto> getMemberById(@PathVariable int id) {
* @param membersDtoDetails the {@link Members} object containing the updated details
* @return the updated {@link Members} object
*/
@PutMapping("/{id}")
@PutMapping("/update-member-by-id/{id}")
@PreAuthorize("hasRole('LIBRARIAN') or hasRole('ADMIN') or (hasRole('USER') and #id == authentication.principal.memberId)")
public MembersDto updateMember(@PathVariable int id, @Valid @RequestBody UpdateMembersDto membersDtoDetails) {
return memberService.updateMember(id, membersDtoDetails);
Expand All @@ -97,7 +97,7 @@ public MembersDto updateMember(@PathVariable int id, @Valid @RequestBody UpdateM
*
* @param id the ID of the member to delete
*/
@DeleteMapping("/{id}")
@DeleteMapping("/delete-member-by-id/{id}")
@PreAuthorize("hasRole('LIBRARIAN') or hasRole('ADMIN')")
public void deleteMember(@PathVariable int id) {
memberService.deleteMember(id);
Expand All @@ -111,7 +111,7 @@ public void deleteMember(@PathVariable int id) {
* @param updatePasswordDto the {@link UpdatePasswordDto} object containing the password details
* @return a {@link ResponseEntity} containing a success message indicating the password was updated successfully
*/
@PutMapping("/{id}/password")
@PutMapping("/update-password-by-id/{id}")
@PreAuthorize("#id == authentication.principal.memberId")
public ResponseEntity<?> updatePassword(@PathVariable int id,
@Valid @RequestBody UpdatePasswordDto updatePasswordDto) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,21 @@ public ResponseEntity<String> subscribe(@RequestParam String email) {
try {
String result = newsletterService.subscribe(email);

switch (result) {
case "Invalid email format.":
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); // 400 Bad Request
return switch (result) {
case "Invalid email format." ->
ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); // 400 Bad Request

case "Email is already subscribed.":
return ResponseEntity.status(HttpStatus.CONFLICT).body(result); // 409 Conflict
case "Email is already subscribed." ->
ResponseEntity.status(HttpStatus.CONFLICT).body(result); // 409 Conflict

case "You have successfully subscribed!":
return ResponseEntity.status(HttpStatus.CREATED).body(result); // 201 Created
case "You have successfully subscribed!" ->
ResponseEntity.status(HttpStatus.CREATED).body(result); // 201 Created

case "You have successfully re-subscribed!":
return ResponseEntity.status(HttpStatus.OK).body(result); // 200 OK
case "You have successfully re-subscribed!" ->
ResponseEntity.status(HttpStatus.OK).body(result); // 200 OK

default:
return ResponseEntity.status(HttpStatus.OK).body(result); // Default 200 OK
}
default -> ResponseEntity.status(HttpStatus.OK).body(result); // Default 200 OK
};
} catch (Exception e) {
// Handle unexpected errors
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
Expand All @@ -49,19 +48,18 @@ public ResponseEntity<String> unsubscribe(@RequestParam String token) {
try {
String result = newsletterService.unsubscribe(token);

switch (result) {
case "Invalid or expired token.":
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result); // 404 Not Found
return switch (result) {
case "Invalid or expired token." ->
ResponseEntity.status(HttpStatus.NOT_FOUND).body(result); // 404 Not Found

case "You are already unsubscribed.":
return ResponseEntity.status(HttpStatus.CONFLICT).body(result); // 409 Conflict
case "You are already unsubscribed." ->
ResponseEntity.status(HttpStatus.CONFLICT).body(result); // 409 Conflict

case "You have successfully unsubscribed!":
return ResponseEntity.status(HttpStatus.OK).body(result); // 200 OK
case "You have successfully unsubscribed!" ->
ResponseEntity.status(HttpStatus.OK).body(result); // 200 OK

default:
return ResponseEntity.status(HttpStatus.OK).body(result); // Default 200 OK
}
default -> ResponseEntity.status(HttpStatus.OK).body(result); // Default 200 OK
};
} catch (Exception e) {
// Handle unexpected errors
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,11 @@ public SecurityFilterChain web(HttpSecurity http) throws Exception {
.requestMatchers("/api/signup").permitAll()
.requestMatchers("/api/login").permitAll()
.requestMatchers("/api/logout").permitAll()
.requestMatchers("/api/books").permitAll()
.requestMatchers("/api/get-all-books/**").permitAll()
.requestMatchers("/api/book/search**").permitAll()
.requestMatchers("/api/analytics/**").hasAnyRole("ADMIN", "LIBRARIAN") // New line for analytics
.anyRequest().authenticated()

)
.logout(logout -> logout
.deleteCookies("LibraryManCookie"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,18 @@ public void signup(Members members) {
}
String encoded_password = passwordEncoder.bCryptPasswordEncoder().encode(members.getPassword());
Members new_members = new Members();
new_members.setEmail(members.getEmail());

// TODO: check for proper username format
new_members.setUsername(members.getUsername());

new_members.setName(members.getName());
new_members.setPassword(encoded_password);

// TODO: check for proper email format
new_members.setEmail(members.getEmail());

new_members.setRole(Role.USER);
new_members.setMembershipDate(new Date());
new_members.setUsername(members.getUsername());
new_members.setPassword(encoded_password);
memberRepository.save(new_members);
}

Expand Down

0 comments on commit 2aac646

Please sign in to comment.