WIP: Permissions
This commit is contained in:
+1
@@ -30,6 +30,7 @@ public class ApplicationStartupRunner implements CommandLineRunner {
|
||||
permissions.setUser(admin);
|
||||
permissions.setPermissionUpload(true);
|
||||
permissions.setPermissionDownload(true);
|
||||
permissions.setPermissionManipulateLibrary(true);
|
||||
permissions.setPermissionEditMetadata(true);
|
||||
permissions.setPermissionAdmin(true);
|
||||
|
||||
|
||||
+6
@@ -68,6 +68,12 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
if (permissions.isPermissionEditMetadata()) {
|
||||
authorities.add(new SimpleGrantedAuthority("ROLE_EDIT_METADATA"));
|
||||
}
|
||||
if (permissions.isPermissionManipulateLibrary()) {
|
||||
authorities.add(new SimpleGrantedAuthority("ROLE_MANIPULATE_LIBRARY"));
|
||||
}
|
||||
if (permissions.isPermissionAdmin()) {
|
||||
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
|
||||
}
|
||||
return authorities;
|
||||
}
|
||||
}
|
||||
+26
-20
@@ -1,25 +1,32 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import io.jsonwebtoken.*;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class JwtUtils {
|
||||
private final String secretKey = "G6u4m3g7M/b93k7m9a1h1Kw4l3D+5WqXldpl4nTjl4s=";
|
||||
|
||||
private SecretKey getSigningKey() {
|
||||
return Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public String generateToken(BookLoreUserEntity user) {
|
||||
SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
||||
SecretKey key = getSigningKey();
|
||||
Date now = new Date();
|
||||
Date expirationDate = new Date(now.getTime() + 1000 * 60 * 60 * 10);
|
||||
|
||||
return Jwts.builder()
|
||||
.claim("sub", user.getUsername())
|
||||
.subject(user.getUsername())
|
||||
.claim("userId", user.getId())
|
||||
.issuedAt(now)
|
||||
.expiration(expirationDate)
|
||||
.signWith(key, Jwts.SIG.HS256)
|
||||
@@ -27,27 +34,26 @@ public class JwtUtils {
|
||||
}
|
||||
|
||||
public boolean validateToken(String token) {
|
||||
return !isTokenExpired(token);
|
||||
try {
|
||||
return !isTokenExpired(token);
|
||||
} catch (JwtException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Claims extractClaims(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(getSigningKey())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
}
|
||||
|
||||
public String extractUsername(String token) {
|
||||
SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
||||
return Jwts.parser()
|
||||
.verifyWith(key)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload()
|
||||
.getSubject();
|
||||
return extractClaims(token).getSubject();
|
||||
}
|
||||
|
||||
private boolean isTokenExpired(String token) {
|
||||
SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
||||
return Jwts.parser()
|
||||
.verifyWith(key)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload()
|
||||
.getExpiration()
|
||||
.before(new Date());
|
||||
return extractClaims(token).getExpiration().before(new Date());
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.config.security;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
@@ -17,6 +18,7 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import java.util.List;
|
||||
|
||||
@AllArgsConstructor
|
||||
@EnableMethodSecurity
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
|
||||
@@ -22,12 +22,19 @@ public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<BookLoreUser> getUser(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(userService.getBookLoreUser(id));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<List<BookLoreUser>> getAllUsers() {
|
||||
return ResponseEntity.ok(userService.getBookLoreUsers());
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<BookLoreUser> updateUser(@PathVariable Long id, @Valid @RequestBody UserUpdateRequest updateRequest) {
|
||||
BookLoreUser updatedUser = userService.updateUser(id, updateRequest);
|
||||
return ResponseEntity.ok(updatedUser);
|
||||
|
||||
+7
@@ -5,6 +5,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
@@ -51,6 +52,12 @@ public class GlobalExceptionHandler {
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public ResponseEntity<ErrorResponse> handleAccessDeniedException(AccessDeniedException ex) {
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.FORBIDDEN.value(), "Access Denied: " + ex.getMessage());
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An unexpected error occurred.");
|
||||
|
||||
@@ -17,8 +17,11 @@ public interface BookLoreUserMapper {
|
||||
return null;
|
||||
}
|
||||
BookLoreUser.UserPermissions dto = new BookLoreUser.UserPermissions();
|
||||
dto.setAdmin(permissions.isPermissionAdmin());
|
||||
dto.setCanUpload(permissions.isPermissionUpload());
|
||||
dto.setCanDownload(permissions.isPermissionDownload());
|
||||
dto.setCanManipulateLibrary(permissions.isPermissionManipulateLibrary());
|
||||
dto.setCanEditMetadata(permissions.isPermissionEditMetadata());
|
||||
dto.setCanEditMetadata(permissions.isPermissionEditMetadata());
|
||||
return dto;
|
||||
}
|
||||
|
||||
@@ -12,8 +12,10 @@ public class BookLoreUser {
|
||||
|
||||
@Data
|
||||
public static class UserPermissions {
|
||||
private boolean isAdmin;
|
||||
private boolean canUpload;
|
||||
private boolean canDownload;
|
||||
private boolean canEditMetadata;
|
||||
private boolean canManipulateLibrary;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,4 +12,5 @@ public class UserCreateRequest {
|
||||
private boolean permissionUpload;
|
||||
private boolean permissionDownload;
|
||||
private boolean permissionEditMetadata;
|
||||
private boolean permissionManipulateLibrary;
|
||||
}
|
||||
+3
@@ -29,6 +29,9 @@ public class UserPermissionsEntity {
|
||||
@Column(name = "permission_edit_metadata", nullable = false)
|
||||
private boolean permissionEditMetadata = false;
|
||||
|
||||
@Column(name = "permission_manipulate_library", nullable = false)
|
||||
private boolean permissionManipulateLibrary = false;
|
||||
|
||||
@Column(name = "permission_admin", nullable = false)
|
||||
private boolean permissionAdmin;
|
||||
}
|
||||
@@ -50,6 +50,7 @@ public class UserService {
|
||||
permissions.setPermissionUpload(request.isPermissionUpload());
|
||||
permissions.setPermissionDownload(request.isPermissionDownload());
|
||||
permissions.setPermissionEditMetadata(request.isPermissionEditMetadata());
|
||||
permissions.setPermissionEditMetadata(request.isPermissionManipulateLibrary());
|
||||
|
||||
bookLoreUserEntity.setPermissions(permissions);
|
||||
|
||||
@@ -64,8 +65,7 @@ public class UserService {
|
||||
}
|
||||
|
||||
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
|
||||
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername())
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
|
||||
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
|
||||
|
||||
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
|
||||
throw ApiError.INVALID_CREDENTIALS.createException();
|
||||
@@ -111,4 +111,8 @@ public class UserService {
|
||||
}
|
||||
|
||||
|
||||
public BookLoreUser getBookLoreUser(Long id) {
|
||||
BookLoreUserEntity user = userRepository.findById(id).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(id));
|
||||
return bookLoreUserMapper.toDto(user);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,12 +181,13 @@ CREATE TABLE IF NOT EXISTS users
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_permissions
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
permission_upload BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
permission_download BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
permission_edit_metadata BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
permission_admin BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
permission_upload BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
permission_download BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
permission_edit_metadata BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
permission_manipulate_library BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
permission_admin BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
CONSTRAINT fk_user_permissions_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user