Skip to content

Commit

Permalink
feat: refactor code and update role_based authorize
Browse files Browse the repository at this point in the history
  • Loading branch information
loingtan committed May 23, 2024
1 parent 68bfcbc commit dbc9973
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -69,30 +69,32 @@ protected void doFilterInternal(@NonNull HttpServletRequest request,
try {
String authHeader = request.getHeader("Authorization");
if (StringUtils.isEmpty(authHeader) || !StringUtils.startsWith(authHeader, "Bearer ")) {
filterChain.doFilter(request, response);
return;
}

String jwt = authHeader.substring(7);
String userEmail = jwtService.extractUsername(jwt);

if (StringUtils.isNotEmpty(userEmail) && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userService.loadUserByUsername(userEmail);

if (jwtService.isTokenValid(jwt, userDetails)) {
setAuthenticationContext(userDetails, request);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Unauthorized");
} else {
String jwt = authHeader.substring(7);
String userEmail = jwtService.extractUsername(jwt);

if (StringUtils.isNotEmpty(userEmail) && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userService.loadUserByUsername(userEmail);

if (jwtService.isTokenValid(jwt, userDetails)) {
setAuthenticationContext(userDetails, request);
filterChain.doFilter(request, response);
} else {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Unauthorized");
}
} else {
filterChain.doFilter(request, response);
}
}
} catch (Exception e) {
logger.error("Failed to process JWT authentication", e);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Unauthorized");
return;
}

filterChain.doFilter(request, response);
}

private void setupCorsHeaders(HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin", allowedOrigins);
response.addHeader("Access-Control-Allow-Methods", allowedMethods);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,15 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http, Authentication
.sessionManagement(session -> session.sessionCreationPolicy(STATELESS))
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.logout(logout -> logout.logoutUrl("/api/v1/auth/logout")).build();
.build();
}

//Dùng Bean để tạo ra một PasswordEncoder để mã hóa mật khẩu bằng BCryptPasswordEncoder
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

//Dùng Bean để tạo ra một Customizer<CorsConfigurer<HttpSecurity>> để cấu hình CORS
@Bean
public Customizer<CorsConfigurer<HttpSecurity>> corsConfigurationSource() {
return cors -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;

@RestController
@RequestMapping(Endpoint.Auth.BASE)
Expand All @@ -22,7 +25,12 @@ public AuthController(AuthService service) {
@PostMapping(Endpoint.Auth.REGISTER)
public ResponseEntity<String> register(
@Validated @RequestBody AuthRegisterDto request) {
return ResponseEntity.ok(service.register(request));
String newUser = service.register(request);
URI location = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/user/{id}")
.buildAndExpand(newUser)
.toUri();
return ResponseEntity.created(location).body(newUser);
}

@PostMapping(Endpoint.Auth.LOGIN)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package com.github.nhatoriginal.spring.controller;

import java.net.URI;
import java.util.List;
import java.util.UUID;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.github.nhatoriginal.spring.constant.Endpoint;
import com.github.nhatoriginal.spring.dto.menuItem.MenuItemDetailDto;
import com.github.nhatoriginal.spring.dto.menuItem.MenuItemDto;
import com.github.nhatoriginal.spring.service.MenuItemService;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@RestController
@RequestMapping(Endpoint.MenuItem.BASE)
Expand All @@ -18,30 +21,38 @@ public MenuItemController(MenuItemService menuItemService) {
this.menuItemService = menuItemService;
}
@GetMapping(Endpoint.MenuItem.GET_ALL)
public List<MenuItemDto> findAll(@RequestParam(name = "name", required = false) String name) {
return menuItemService.findAll(name);
public ResponseEntity<List<MenuItemDto>> findAll(@RequestParam(name = "name", required = false) String name) {
return ResponseEntity.ok(menuItemService.findAll(name));
}
@PreAuthorize("hasAuthority('ROLE_OWNER')")
@PostMapping(Endpoint.MenuItem.CREATE)
public MenuItemDetailDto create(@RequestBody MenuItemDetailDto menuItemDto) {

return menuItemService.create(menuItemDto);
}
@GetMapping(Endpoint.MenuItem.GET_ALL_BY_MENU_ID)
public List<MenuItemDetailDto> findAllByMenuId(@PathVariable UUID menuId) {
return menuItemService.findAllByMenuId(menuId);
}
@PatchMapping(Endpoint.MenuItem.UPDATE)
public MenuItemDetailDto update(@PathVariable UUID id, @RequestBody MenuItemDetailDto menuItemDto) {
return menuItemService.update(id, menuItemDto);
}
@DeleteMapping(Endpoint.MenuItem.DELETE)
public ResponseEntity<String> delete(@PathVariable UUID id) {
return ResponseEntity.ok(menuItemService.delete(id));
}
// @GetMapping(Endpoint.MenuItem.GET_ONE)
// public MenuItemDetailDto findById(@PathVariable UUID id) {
// return menuItemService.findById(id);
// }
public ResponseEntity<MenuItemDetailDto> create(@RequestBody MenuItemDetailDto menuItemDto) {
MenuItemDetailDto createdMenuItem = menuItemService.create(menuItemDto);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(createdMenuItem.getId())
.toUri();
return ResponseEntity.created(location).body(createdMenuItem);
}
@PreAuthorize("hasAuthority('ROLE_OWNER')")
@GetMapping(Endpoint.MenuItem.GET_ALL_BY_MENU_ID)
public ResponseEntity<List<MenuItemDetailDto>> findAllByMenuId(@PathVariable UUID menuId) {
return ResponseEntity.ok(menuItemService.findAllByMenuId(menuId));
}
@PreAuthorize("hasAuthority('ROLE_OWNER')")
@PatchMapping(Endpoint.MenuItem.UPDATE)
public MenuItemDetailDto update(@PathVariable UUID id, @RequestBody MenuItemDetailDto menuItemDto) {
return menuItemService.update(id, menuItemDto);
}
@PreAuthorize("hasAuthority('ROLE_OWNER')")
@DeleteMapping(Endpoint.MenuItem.DELETE)
public ResponseEntity<String> delete(@PathVariable UUID id) {
return ResponseEntity.ok(menuItemService.delete(id));
}
@GetMapping(Endpoint.MenuItem.GET_ONE)
public MenuItemDetailDto findById(@PathVariable UUID id) {
return menuItemService.findById(id);
}
// @GetMapping("")
// public List<MenuItemDto> findAllByOwner() {
// return menuItemService.findAll(null);
Expand Down

0 comments on commit dbc9973

Please sign in to comment.