Skip to content

Commit 0f2496a

Browse files
author
Omari Sopromadze
committed
Sonar fix
1 parent d592da0 commit 0f2496a

47 files changed

Lines changed: 1612 additions & 1153 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
.settings
1010
.springBeans
1111
.sts4-cache
12+
/bin/
1213

1314
### IntelliJ IDEA ###
1415
.idea

pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@
4141
<groupId>org.springframework.boot</groupId>
4242
<artifactId>spring-boot-starter-web</artifactId>
4343
</dependency>
44+
45+
<dependency>
46+
<groupId>org.springframework.boot</groupId>
47+
<artifactId>spring-boot-starter-aop</artifactId>
48+
</dependency>
4449

4550
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
4651
<dependency>

src/main/java/com/sopromadze/blogapi/config/SecutiryConfig.java

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
package com.sopromadze.blogapi.config;
22

3-
import com.sopromadze.blogapi.repository.UserRepository;
4-
import com.sopromadze.blogapi.security.JwtAuthenticationEntryPoint;
5-
import com.sopromadze.blogapi.security.JwtAuthenticationFilter;
6-
import com.sopromadze.blogapi.service.CustomUserDetailsService;
73
import org.springframework.beans.factory.annotation.Autowired;
84
import org.springframework.context.annotation.Bean;
95
import org.springframework.context.annotation.Configuration;
@@ -20,27 +16,32 @@
2016
import org.springframework.security.crypto.password.PasswordEncoder;
2117
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
2218

19+
import com.sopromadze.blogapi.repository.UserRepository;
20+
import com.sopromadze.blogapi.security.JwtAuthenticationEntryPoint;
21+
import com.sopromadze.blogapi.security.JwtAuthenticationFilter;
22+
import com.sopromadze.blogapi.service.impl.CustomUserDetailsServiceImpl;
23+
2324
@Configuration
2425
@EnableWebSecurity
2526
@EnableGlobalMethodSecurity(
2627
securedEnabled = true,
2728
jsr250Enabled = true,
2829
prePostEnabled = true)
2930
public class SecutiryConfig extends WebSecurityConfigurerAdapter {
30-
private final CustomUserDetailsService customUserDetailsService;
31+
private final CustomUserDetailsServiceImpl customUserDetailsService;
3132
private final JwtAuthenticationEntryPoint unauthorizedHandler;
3233
private final JwtAuthenticationFilter jwtAuthenticationFilter;
3334

3435
@Autowired
35-
public SecutiryConfig(UserRepository userRepository, CustomUserDetailsService customUserDetailsService, JwtAuthenticationEntryPoint unauthorizedHandler, JwtAuthenticationFilter jwtAuthenticationFilter) {
36+
public SecutiryConfig(UserRepository userRepository, CustomUserDetailsServiceImpl customUserDetailsService, JwtAuthenticationEntryPoint unauthorizedHandler, JwtAuthenticationFilter jwtAuthenticationFilter) {
3637
this.customUserDetailsService = customUserDetailsService;
3738
this.unauthorizedHandler = unauthorizedHandler;
3839
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
39-
;
4040
}
4141

4242
@Override
4343
protected void configure(HttpSecurity http) throws Exception {
44+
4445
http.cors().and().csrf().disable()
4546
.exceptionHandling()
4647
.authenticationEntryPoint(unauthorizedHandler)
@@ -50,7 +51,7 @@ protected void configure(HttpSecurity http) throws Exception {
5051
.and()
5152
.authorizeRequests()
5253
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
53-
.antMatchers("/api/auth/**").permitAll()
54+
.antMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
5455
.antMatchers(HttpMethod.GET, "/api/users/checkUsernameAvailability", "/api/users/checkEmailAvailability").permitAll()
5556
.anyRequest().authenticated();
5657

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,23 @@
11
package com.sopromadze.blogapi.config;
22

3+
import org.springframework.beans.factory.annotation.Value;
34
import org.springframework.context.annotation.Configuration;
45
import org.springframework.web.servlet.config.annotation.CorsRegistry;
56
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
67

78
@Configuration
89
public class WebMvcConfig implements WebMvcConfigurer {
9-
private final long MAX_AGE_SECS = 3600;
10+
11+
@Value("cors.allowedOrings")
12+
private String allowedOrigins;
1013

1114
public void addCorsMappings(CorsRegistry registry){
15+
final long MAX_AGE_SECS = 3600;
16+
1217
registry.addMapping("/**")
13-
.allowedOrigins("*")
18+
.allowedOrigins(allowedOrigins)
1419
.allowedMethods("GET", "POST", "PUT", "DELETE")
20+
.allowedHeaders("*")
1521
.maxAge(MAX_AGE_SECS);
1622
}
1723
}

src/main/java/com/sopromadze/blogapi/controller/AlbumController.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,14 @@
2121
import com.sopromadze.blogapi.payload.AlbumResponse;
2222
import com.sopromadze.blogapi.payload.ApiResponse;
2323
import com.sopromadze.blogapi.payload.PagedResponse;
24+
import com.sopromadze.blogapi.payload.PhotoResponse;
2425
import com.sopromadze.blogapi.payload.request.AlbumRequest;
2526
import com.sopromadze.blogapi.security.CurrentUser;
2627
import com.sopromadze.blogapi.security.UserPrincipal;
2728
import com.sopromadze.blogapi.service.AlbumService;
2829
import com.sopromadze.blogapi.service.PhotoService;
2930
import com.sopromadze.blogapi.utils.AppConstants;
31+
import com.sopromadze.blogapi.utils.AppUtils;
3032

3133
@RestController
3234
@RequestMapping("/api/albums")
@@ -46,6 +48,7 @@ public ResponseEntity<ApiResponse> handleExceptions(ResponseEntityErrorException
4648
public PagedResponse<AlbumResponse> getAllAlbums(
4749
@RequestParam(name = "page", required = false, defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) Integer page,
4850
@RequestParam(name = "size", required = false, defaultValue = AppConstants.DEFAULT_PAGE_SIZE) Integer size) {
51+
AppUtils.validatePageNumberAndSize(page, size);
4952

5053
return albumService.getAllAlbums(page, size);
5154
}
@@ -57,7 +60,7 @@ public ResponseEntity<Album> addAlbum(@Valid @RequestBody AlbumRequest albumRequ
5760
}
5861

5962
@GetMapping("/{id}")
60-
public ResponseEntity<?> getAlbum(@PathVariable(name = "id") Long id) {
63+
public ResponseEntity<Album> getAlbum(@PathVariable(name = "id") Long id) {
6164
return albumService.getAlbum(id);
6265
}
6366

@@ -70,12 +73,12 @@ public ResponseEntity<AlbumResponse> updateAlbum(@PathVariable(name = "id") Long
7073

7174
@DeleteMapping("/{id}")
7275
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
73-
public ResponseEntity<?> deleteAlbum(@PathVariable(name = "id") Long id, @CurrentUser UserPrincipal currentUser) {
76+
public ResponseEntity<ApiResponse> deleteAlbum(@PathVariable(name = "id") Long id, @CurrentUser UserPrincipal currentUser) {
7477
return albumService.deleteAlbum(id, currentUser);
7578
}
7679

7780
@GetMapping("/{id}/photos")
78-
public PagedResponse<?> getAllPhotosByAlbum(@PathVariable(name = "id") Long id,
81+
public PagedResponse<PhotoResponse> getAllPhotosByAlbum(@PathVariable(name = "id") Long id,
7982
@RequestParam(name = "page", required = false, defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) Integer page,
8083
@RequestParam(name = "size", required = false, defaultValue = AppConstants.DEFAULT_PAGE_SIZE) Integer size) {
8184
return photoService.getAllPhotosByAlbum(id, page, size);
Lines changed: 35 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,11 @@
11
package com.sopromadze.blogapi.controller;
22

3-
import com.sopromadze.blogapi.exception.AppException;
4-
import com.sopromadze.blogapi.model.role.Role;
5-
import com.sopromadze.blogapi.model.role.RoleName;
6-
import com.sopromadze.blogapi.model.user.User;
7-
import com.sopromadze.blogapi.payload.ApiResponse;
8-
import com.sopromadze.blogapi.payload.JwtAuthenticationResponse;
9-
import com.sopromadze.blogapi.payload.LoginRequest;
10-
import com.sopromadze.blogapi.payload.SignUpRequest;
11-
import com.sopromadze.blogapi.repository.RoleRepository;
12-
import com.sopromadze.blogapi.repository.UserRepository;
13-
import com.sopromadze.blogapi.security.JwtTokenProvider;
3+
import java.net.URI;
4+
import java.util.ArrayList;
5+
import java.util.List;
6+
7+
import javax.validation.Valid;
8+
149
import org.springframework.beans.factory.annotation.Autowired;
1510
import org.springframework.http.HttpStatus;
1611
import org.springframework.http.ResponseEntity;
@@ -25,14 +20,24 @@
2520
import org.springframework.web.bind.annotation.RestController;
2621
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
2722

28-
import javax.validation.Valid;
29-
import java.net.URI;
30-
import java.util.ArrayList;
31-
import java.util.List;
23+
import com.sopromadze.blogapi.exception.AppException;
24+
import com.sopromadze.blogapi.exception.BlogapiException;
25+
import com.sopromadze.blogapi.model.role.Role;
26+
import com.sopromadze.blogapi.model.role.RoleName;
27+
import com.sopromadze.blogapi.model.user.User;
28+
import com.sopromadze.blogapi.payload.ApiResponse;
29+
import com.sopromadze.blogapi.payload.JwtAuthenticationResponse;
30+
import com.sopromadze.blogapi.payload.LoginRequest;
31+
import com.sopromadze.blogapi.payload.SignUpRequest;
32+
import com.sopromadze.blogapi.repository.RoleRepository;
33+
import com.sopromadze.blogapi.repository.UserRepository;
34+
import com.sopromadze.blogapi.security.JwtTokenProvider;
3235

3336
@RestController
3437
@RequestMapping("/api/auth")
3538
public class AuthController {
39+
private static final String USER_ROLE_NOT_SET = "User role not set";
40+
3641
@Autowired
3742
private AuthenticationManager authenticationManager;
3843

@@ -49,7 +54,7 @@ public class AuthController {
4954
private JwtTokenProvider jwtTokenProvider;
5055

5156
@PostMapping("/signin")
52-
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
57+
public ResponseEntity<JwtAuthenticationResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
5358
Authentication authentication = authenticationManager.authenticate(
5459
new UsernamePasswordAuthenticationToken(loginRequest.getUsernameOrEmail(), loginRequest.getPassword()));
5560

@@ -60,37 +65,37 @@ public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest login
6065
}
6166

6267
@PostMapping("/signup")
63-
public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpRequest signUpRequest) {
68+
public ResponseEntity<ApiResponse> registerUser(@Valid @RequestBody SignUpRequest signUpRequest) {
6469
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
65-
return new ResponseEntity<>(new ApiResponse(false, "Username is already taken"), HttpStatus.BAD_REQUEST);
70+
throw new BlogapiException(HttpStatus.BAD_REQUEST, "Username is already taken");
6671
}
6772

6873
if (userRepository.existsByEmail(signUpRequest.getEmail())) {
69-
return new ResponseEntity<>(new ApiResponse(false, "Email is already taken"), HttpStatus.BAD_REQUEST);
74+
throw new BlogapiException(HttpStatus.BAD_REQUEST, "Email is already taken");
7075
}
71-
String firstName = signUpRequest.getFirstName().substring(0, 1).toUpperCase()
72-
+ signUpRequest.getFirstName().substring(1).toLowerCase();
76+
77+
String firstName = signUpRequest.getFirstName().toLowerCase();
7378

74-
String lastName = signUpRequest.getLastName().substring(0, 1).toUpperCase()
75-
+ signUpRequest.getLastName().substring(1).toLowerCase();
79+
String lastName = signUpRequest.getLastName().toLowerCase();
7680

7781
String username = signUpRequest.getUsername().toLowerCase();
7882

7983
String email = signUpRequest.getEmail().toLowerCase();
84+
85+
String password = passwordEncoder.encode(signUpRequest.getPassword());
8086

81-
User user = new User(firstName, lastName, username, email, signUpRequest.getPassword());
82-
83-
user.setPassword(passwordEncoder.encode(user.getPassword()));
87+
User user = new User(firstName, lastName, username, email, password);
8488

8589
List<Role> roles = new ArrayList<>();
90+
8691
if (userRepository.count() == 0) {
8792
roles.add(roleRepository.findByName(RoleName.ROLE_USER)
88-
.orElseThrow(() -> new AppException("User role not set")));
93+
.orElseThrow(() -> new AppException(USER_ROLE_NOT_SET)));
8994
roles.add(roleRepository.findByName(RoleName.ROLE_ADMIN)
90-
.orElseThrow(() -> new AppException("User role not set")));
95+
.orElseThrow(() -> new AppException(USER_ROLE_NOT_SET)));
9196
} else {
9297
roles.add(roleRepository.findByName(RoleName.ROLE_USER)
93-
.orElseThrow(() -> new AppException("User role not set")));
98+
.orElseThrow(() -> new AppException(USER_ROLE_NOT_SET)));
9499
}
95100

96101
user.setRoles(roles);
@@ -100,6 +105,6 @@ public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpRequest signUpRe
100105
URI location = ServletUriComponentsBuilder.fromCurrentContextPath().path("/api/users/{userId}")
101106
.buildAndExpand(result.getId()).toUri();
102107

103-
return ResponseEntity.created(location).body(new ApiResponse(true, "User registered successfully"));
108+
return ResponseEntity.created(location).body(new ApiResponse(Boolean.TRUE, "User registered successfully"));
104109
}
105110
}

src/main/java/com/sopromadze/blogapi/controller/CategoryController.java

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515
import org.springframework.web.bind.annotation.RequestParam;
1616
import org.springframework.web.bind.annotation.RestController;
1717

18+
import com.sopromadze.blogapi.exception.UnathorizedException;
1819
import com.sopromadze.blogapi.model.category.Category;
20+
import com.sopromadze.blogapi.payload.ApiResponse;
1921
import com.sopromadze.blogapi.payload.PagedResponse;
2022
import com.sopromadze.blogapi.security.CurrentUser;
2123
import com.sopromadze.blogapi.security.UserPrincipal;
@@ -29,32 +31,32 @@ public class CategoryController {
2931
private CategoryService categoryService;
3032

3133
@GetMapping
32-
public PagedResponse<?> getAllCategories(
34+
public PagedResponse<Category> getAllCategories(
3335
@RequestParam(name = "page", required = false, defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) Integer page,
3436
@RequestParam(name = "size", required = false, defaultValue = AppConstants.DEFAULT_PAGE_SIZE) Integer size){
3537
return categoryService.getAllCategories(page, size);
3638
}
3739

3840
@PostMapping
3941
@PreAuthorize("hasRole('USER')")
40-
public ResponseEntity<?> addCategory(@Valid @RequestBody Category category, @CurrentUser UserPrincipal currentUser){
42+
public ResponseEntity<Category> addCategory(@Valid @RequestBody Category category, @CurrentUser UserPrincipal currentUser){
4143
return categoryService.addCategory(category, currentUser);
4244
}
4345

4446
@GetMapping("/{id}")
45-
public ResponseEntity<?> getCategory(@PathVariable(name = "id") Long id){
47+
public ResponseEntity<Category> getCategory(@PathVariable(name = "id") Long id){
4648
return categoryService.getCategory(id);
4749
}
4850

4951
@PutMapping("/{id}")
5052
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
51-
public ResponseEntity<?> updateCategory(@PathVariable(name = "id") Long id, @Valid @RequestBody Category category, @CurrentUser UserPrincipal currentUser){
53+
public ResponseEntity<Category> updateCategory(@PathVariable(name = "id") Long id, @Valid @RequestBody Category category, @CurrentUser UserPrincipal currentUser) throws UnathorizedException{
5254
return categoryService.updateCategory(id, category, currentUser);
5355
}
5456

5557
@DeleteMapping("/{id}")
5658
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
57-
public ResponseEntity<?> deleteCategory(@PathVariable(name = "id") Long id, @CurrentUser UserPrincipal currentUser){
59+
public ResponseEntity<ApiResponse> deleteCategory(@PathVariable(name = "id") Long id, @CurrentUser UserPrincipal currentUser) throws UnathorizedException{
5860
return categoryService.deleteCategory(id, currentUser);
5961
}
6062

src/main/java/com/sopromadze/blogapi/controller/CommentController.java

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import javax.validation.Valid;
44

55
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.http.HttpStatus;
67
import org.springframework.http.ResponseEntity;
78
import org.springframework.security.access.prepost.PreAuthorize;
89
import org.springframework.web.bind.annotation.DeleteMapping;
@@ -15,6 +16,8 @@
1516
import org.springframework.web.bind.annotation.RequestParam;
1617
import org.springframework.web.bind.annotation.RestController;
1718

19+
import com.sopromadze.blogapi.model.comment.Comment;
20+
import com.sopromadze.blogapi.payload.ApiResponse;
1821
import com.sopromadze.blogapi.payload.CommentRequest;
1922
import com.sopromadze.blogapi.payload.PagedResponse;
2023
import com.sopromadze.blogapi.security.CurrentUser;
@@ -29,38 +32,53 @@ public class CommentController {
2932
private CommentService commentService;
3033

3134
@GetMapping
32-
public PagedResponse<?> getAllComments(@PathVariable(name = "postId") Long postId,
35+
public ResponseEntity<PagedResponse<Comment>> getAllComments(@PathVariable(name = "postId") Long postId,
3336
@RequestParam(name = "page", required = false, defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) Integer page,
3437
@RequestParam(name = "size", required = false, defaultValue = AppConstants.DEFAULT_PAGE_SIZE) Integer size) {
35-
return commentService.getAllComments(postId, page, size);
38+
39+
PagedResponse<Comment> allComments = commentService.getAllComments(postId, page, size);
40+
41+
return new ResponseEntity<PagedResponse<Comment>>(allComments, HttpStatus.OK);
3642
}
3743

3844
@PostMapping
3945
@PreAuthorize("hasRole('USER')")
40-
public ResponseEntity<?> addComment(@Valid @RequestBody CommentRequest commentRequest,
46+
public ResponseEntity<Comment> addComment(@Valid @RequestBody CommentRequest commentRequest,
4147
@PathVariable(name = "postId") Long postId, @CurrentUser UserPrincipal currentUser) {
42-
return commentService.addComment(commentRequest, postId, currentUser);
48+
Comment newComment = commentService.addComment(commentRequest, postId, currentUser);
49+
50+
return new ResponseEntity<Comment>(newComment, HttpStatus.CREATED);
4351
}
4452

4553
@GetMapping("/{id}")
46-
public ResponseEntity<?> getComment(@PathVariable(name = "postId") Long postId,
54+
public ResponseEntity<Comment> getComment(@PathVariable(name = "postId") Long postId,
4755
@PathVariable(name = "id") Long id) {
48-
return commentService.getComment(postId, id);
56+
Comment comment = commentService.getComment(postId, id);
57+
58+
return new ResponseEntity<Comment>(comment, HttpStatus.OK);
4959
}
5060

5161
@PutMapping("/{id}")
5262
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
53-
public ResponseEntity<?> updateComment(@PathVariable(name = "postId") Long postId,
63+
public ResponseEntity<Comment> updateComment(@PathVariable(name = "postId") Long postId,
5464
@PathVariable(name = "id") Long id, @Valid @RequestBody CommentRequest commentRequest,
5565
@CurrentUser UserPrincipal currentUser) {
56-
return commentService.updateComment(postId, id, commentRequest, currentUser);
66+
67+
Comment updatedComment = commentService.updateComment(postId, id, commentRequest, currentUser);
68+
69+
return new ResponseEntity<Comment>(updatedComment, HttpStatus.OK);
5770
}
5871

5972
@DeleteMapping("/{id}")
6073
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
61-
public ResponseEntity<?> deleteComment(@PathVariable(name = "postId") Long postId,
74+
public ResponseEntity<ApiResponse> deleteComment(@PathVariable(name = "postId") Long postId,
6275
@PathVariable(name = "id") Long id, @CurrentUser UserPrincipal currentUser) {
63-
return commentService.deleteComment(postId, id, currentUser);
76+
77+
ApiResponse response = commentService.deleteComment(postId, id, currentUser);
78+
79+
HttpStatus status = response.getSuccess() ? HttpStatus.OK : HttpStatus.BAD_REQUEST;
80+
81+
return new ResponseEntity<ApiResponse>(response, status);
6482
}
6583

6684
}

0 commit comments

Comments
 (0)