Skip to content

Commit 94ec4f2

Browse files
Exceptions updated etc
1 parent 45a3bde commit 94ec4f2

File tree

11 files changed

+82
-94
lines changed

11 files changed

+82
-94
lines changed

Readme.md

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
Spring Boot REST API Practices
22
========================================
33

4-
####Features:
4+
### Features:
55

66
* JWT (Signin, Signup, Roles)
77
* REST API best practices
@@ -11,6 +11,10 @@ Spring Boot REST API Practices
1111
![task](Task.PNG)
1212
*
1313

14+
### To-do Items
15+
* Spring HATEOAS
16+
* Spring Auto REST Docs
17+
1418
## Requirements
1519

1620
For building and running the application you need:

api-requests.http

+20-15
Original file line numberDiff line numberDiff line change
@@ -6,36 +6,41 @@
66
# * 'mptr' and 'fptr' create a POST request to submit a form with a text or file field (multipart/form-data);
77

88

9-
GET http://localhost:8080/hello
10-
Accepts: application/json
11-
12-
###
13-
14-
GET http://localhost:8080/hello
15-
Accepts: application/json
16-
Authorization: Bearer <--token here-->
17-
9+
### Sign up
10+
POST http://localhost:8080/api/auth/signup
11+
Content-Type: application/json
1812

19-
###
13+
{
14+
"email": "[email protected]",
15+
"password": "admin001",
16+
"role": [
17+
"string"
18+
],
19+
"username": "admin001"
20+
}
2021

22+
### Sign in
2123

22-
POST http://localhost:8080/authenticate
24+
POST http://localhost:8080/api/auth/signin
2325
Content-Type: application/json
24-
Accepts: application/json
2526

2627
{
27-
"username" :learning,
28-
"password" :"password"
28+
"password": "admin001",
29+
"username": "admin001"
2930
}
3031

3132
###
3233

34+
GET http://localhost:8080/api/v1/notes
35+
Accepts: application/json
36+
Authorization: Bearer <--token here-->
37+
###
38+
3339
GET http://localhost:8080/api/v1/name/Bangla
3440
Accepts: application/json
3541
Authorization: Bearer <--token here-->
3642

3743
###
38-
3944
GET http://localhost:8080/api/v1/name/bangladesh
4045
Accepts: application/json
4146

src/main/java/com/learning/config/WebSecurityConfig.java

+3-5
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,10 @@ protected void configure(HttpSecurity httpSecurity) throws Exception {
6363
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
6464
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
6565
// dont authenticate this particular request
66-
.authorizeRequests().antMatchers("/authenticate").permitAll()
67-
.antMatchers("/users/signin").permitAll()//
68-
.antMatchers("/users/signup").permitAll()//
69-
.antMatchers("/h2-console/**/**").permitAll().
66+
.authorizeRequests()
67+
.antMatchers("/api/auth/**","/h2-console/**/**").permitAll()
7068
// all other requests need to be authenticated
71-
anyRequest().authenticated();
69+
.anyRequest().authenticated();
7270

7371

7472
// If a user try to access a resource without having enough permissions

src/main/java/com/learning/controller/api/v1/NoteController.java

+1-4
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,7 @@ public class NoteController {
2525
@ApiResponse(code = 500, message = "Internal Server Error")})
2626
public ResponseEntity<?> getAllNotes() {
2727
List<Note> note = noteService.getNotes();
28-
29-
ImmutableMap<String, Object> dataMap = ImmutableMap.of("status", 200,
30-
"message", "success", "data", note);
31-
return ResponseEntity.ok().body(dataMap);
28+
return ResponseEntity.ok().body(note);
3229
}
3330

3431
@PostMapping("/v1/notes")

src/main/java/com/learning/controller/auth/AuthController.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,14 @@
1515
@CrossOrigin(origins = "*", maxAge = 3600)
1616
@RestController
1717
@RequestMapping("/api/auth")
18-
@Api(tags = "users")
18+
@Api(tags = "Auth Controller")
1919
public class AuthController {
2020

2121
@Autowired
2222
UserDetailsServiceImpl userDetailsService;
2323

2424
@PostMapping("/signin")
25-
@ApiOperation(value = "${AuthController.signin}")
25+
@ApiOperation(value = "${AuthController.authenticateUser}")
2626
@ApiResponses(value = {
2727
@ApiResponse(code = 400, message = "Something went wrong"),
2828
@ApiResponse(code = 422, message = "Invalid username/password supplied")})
@@ -31,7 +31,7 @@ public ResponseEntity<?> authenticateUser(@ApiParam("Signin User") @Valid @Reque
3131
}
3232

3333
@PostMapping("/signup")
34-
@ApiOperation(value = "${AuthController.signup}")
34+
@ApiOperation(value = "${AuthController.registerUser}")
3535
@ApiResponses(value = {
3636
@ApiResponse(code = 400, message = "Something went wrong"),
3737
@ApiResponse(code = 403, message = "Access denied"),

src/main/java/com/learning/exception/GlobalExceptionHandler.java

+39-3
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,34 @@
11
package com.learning.exception;
22

3+
import com.learning.payload.response.ErrorResponse;
4+
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
5+
import org.springframework.boot.web.servlet.error.ErrorAttributes;
6+
import org.springframework.context.annotation.Bean;
37
import org.springframework.http.HttpStatus;
48
import org.springframework.http.ResponseEntity;
5-
import org.springframework.web.bind.annotation.ControllerAdvice;
9+
import org.springframework.security.access.AccessDeniedException;
610
import org.springframework.web.bind.annotation.ExceptionHandler;
11+
import org.springframework.web.bind.annotation.RestControllerAdvice;
712
import org.springframework.web.context.request.WebRequest;
813

9-
@ControllerAdvice
14+
import javax.servlet.http.HttpServletResponse;
15+
import java.io.IOException;
16+
import java.util.Map;
17+
18+
@RestControllerAdvice
1019
public class GlobalExceptionHandler {
1120

21+
@Bean
22+
public ErrorAttributes errorAttributes() {
23+
return new DefaultErrorAttributes() {
24+
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
25+
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);
26+
errorAttributes.remove("exception");
27+
return errorAttributes;
28+
}
29+
};
30+
}
31+
1232
/**
1333
* Resource not found exception response entity.
1434
*
@@ -31,10 +51,26 @@ public ResponseEntity<?> resourceNotFoundException(
3151
* @param request the request
3252
* @return the response entity
3353
*/
34-
@ExceptionHandler(Exception.class)
54+
/*@ExceptionHandler(Exception.class)
3555
public ResponseEntity<?> globleExcpetionHandler(Exception ex, WebRequest request) {
3656
ErrorResponse errorDetails =
3757
new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.toString() ,ex.getMessage(), request.getDescription(false));
3858
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
59+
}*/
60+
61+
@ExceptionHandler(CustomException.class)
62+
public void handleCustomException(HttpServletResponse res, CustomException ex) throws IOException {
63+
res.sendError(ex.getHttpStatus().value(), ex.getMessage());
3964
}
65+
66+
@ExceptionHandler(AccessDeniedException.class)
67+
public void handleAccessDeniedException(HttpServletResponse res) throws IOException {
68+
res.sendError(HttpStatus.FORBIDDEN.value(), "Access denied");
69+
}
70+
71+
@ExceptionHandler(Exception.class)
72+
public void handleException(HttpServletResponse res) throws IOException {
73+
res.sendError(HttpStatus.BAD_REQUEST.value(), "Something went wrong");
74+
}
75+
4076
}

src/main/java/com/learning/exception/GlobalExceptionHandlerController.java

-45
This file was deleted.

src/main/java/com/learning/exception/ErrorResponse.java renamed to src/main/java/com/learning/payload/response/ErrorResponse.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.learning.exception;
1+
package com.learning.payload.response;
22

33
import io.swagger.annotations.ApiModelProperty;
44

src/main/java/com/learning/repository/UserRepository.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,5 @@
1111
public interface UserRepository extends JpaRepository<User, Long> {
1212
Optional<User> findByUsername(String username);
1313
void deleteByUsername(String username);
14-
14+
Optional<User> findByEmail(String email);
1515
}

src/main/java/com/learning/service/UserDetailsServiceImpl.java

+7-13
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import com.learning.payload.request.LoginRequest;
1010
import com.learning.payload.request.SignupRequest;
1111
import com.learning.payload.response.JwtResponse;
12+
import com.learning.payload.response.MessageResponse;
1213
import com.learning.repository.RoleRepository;
1314
import com.learning.repository.UserRepository;
1415
import org.springframework.beans.factory.annotation.Autowired;
@@ -91,7 +92,7 @@ public JwtResponse signin(@Valid LoginRequest loginRequest) {
9192
}
9293
}
9394

94-
public JwtResponse signup(@Valid SignupRequest signUpRequest) {
95+
public MessageResponse signup(@Valid SignupRequest signUpRequest) {
9596

9697
// Create new user's account
9798
User user = new User(signUpRequest.getUsername(),
@@ -130,16 +131,7 @@ public JwtResponse signup(@Valid SignupRequest signUpRequest) {
130131
user.setRoles(roles);
131132
userRepository.save(user);
132133

133-
UserDetailsImpl userDetails = UserDetailsImpl.build(user);
134-
final String token = jwtTokenUtil.generateToken(userDetails);
135-
136-
return new JwtResponse(token,
137-
userDetails.getId(),
138-
userDetails.getUsername(),
139-
userDetails.getEmail(),
140-
userDetails.getAuthorities().stream()
141-
.map(item -> item.getAuthority())
142-
.collect(Collectors.toList()));
134+
return new MessageResponse("User registration successful");
143135
}
144136

145137
public void delete(String username) {
@@ -164,10 +156,12 @@ public String refresh(String username) {
164156
}
165157

166158
public boolean existsByUsername(String username) {
167-
return false;
159+
Optional<User> user = userRepository.findByUsername(username);
160+
return user.isPresent();
168161
}
169162

170163
public boolean existsByEmail(String email) {
171-
return false;
164+
Optional<User> user = userRepository.findByEmail(email);
165+
return user.isPresent();
172166
}
173167
}

src/main/resources/application.properties

+2-3
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@
99
spring.datasource.url=jdbc:h2:mem:testdb
1010
spring.datasource.driverClassName=org.h2.Driver
1111
spring.datasource.username=sa
12-
spring.datasource.password=password
12+
spring.datasource.password=
1313
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
14+
spring.h2.console.enabled=true
1415

1516
spring.jpa.defer-datasource-initialization=true
1617

@@ -21,5 +22,3 @@ my.app.jwtExpirationMs= 6000000
2122

2223
#logging.level.root=debug
2324

24-
25-
#jwt.get.token.uri=/authenticate

0 commit comments

Comments
 (0)