perubahan struktur response
This commit is contained in:
parent
2b8de7a320
commit
c8fe5bb235
@ -1,6 +1,7 @@
|
|||||||
package id.co.anaheim.gateway.span.config;
|
package id.co.anaheim.gateway.span.config;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
|
import id.co.anaheim.gateway.span.models.BasicResponse;
|
||||||
import id.co.anaheim.gateway.span.models.JwtUsername;
|
import id.co.anaheim.gateway.span.models.JwtUsername;
|
||||||
import id.co.anaheim.gateway.span.models.JwtValidationResult;
|
import id.co.anaheim.gateway.span.models.JwtValidationResult;
|
||||||
import id.co.anaheim.gateway.span.services.JwtService;
|
import id.co.anaheim.gateway.span.services.JwtService;
|
||||||
@ -19,7 +20,6 @@ import org.springframework.stereotype.Component;
|
|||||||
import org.springframework.web.filter.OncePerRequestFilter;
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.HashMap;
|
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
@ -48,6 +48,10 @@ public class JwtAuthFilter extends OncePerRequestFilter {
|
|||||||
if (isWhitelisted) {
|
if (isWhitelisted) {
|
||||||
filterChain.doFilter(request, response);
|
filterChain.doFilter(request, response);
|
||||||
} else {
|
} else {
|
||||||
|
BasicResponse basicResponse = new BasicResponse();
|
||||||
|
basicResponse.setFileName("");
|
||||||
|
basicResponse.setResultCode("403");
|
||||||
|
Gson gson = new Gson();
|
||||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||||
String token = authHeader.substring(7);
|
String token = authHeader.substring(7);
|
||||||
JwtUsername userName = jwtService.extractUsername(token);
|
JwtUsername userName = jwtService.extractUsername(token);
|
||||||
@ -64,31 +68,31 @@ public class JwtAuthFilter extends OncePerRequestFilter {
|
|||||||
log.info("Security Context: {}", SecurityContextHolder.getContext().getAuthentication());
|
log.info("Security Context: {}", SecurityContextHolder.getContext().getAuthentication());
|
||||||
filterChain.doFilter(request, response);
|
filterChain.doFilter(request, response);
|
||||||
} else {
|
} else {
|
||||||
HashMap<String, String> map = new HashMap<>();
|
basicResponse.setResultStatus(validationResult.getStatus());
|
||||||
map.put("message", validationResult.getMessage());
|
basicResponse.setResultDescription(validationResult.getDescription() );
|
||||||
Gson gson = new Gson();
|
|
||||||
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
||||||
response.setContentType("application/json");
|
response.setContentType("application/json");
|
||||||
response.getWriter().write(gson.toJson(map));
|
response.getWriter().write(gson.toJson(basicResponse));
|
||||||
response.getWriter().flush();
|
response.getWriter().flush();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
HashMap<String, String> map = new HashMap<>();
|
basicResponse.setResultStatus(userName.getStatus());
|
||||||
map.put("message", userName.getMessage());
|
basicResponse.setResultDescription(userName.getDescription() );
|
||||||
Gson gson = new Gson();
|
|
||||||
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
||||||
response.setContentType("application/json");
|
response.setContentType("application/json");
|
||||||
response.getWriter().write(gson.toJson(map));
|
response.getWriter().write(gson.toJson(basicResponse));
|
||||||
response.getWriter().flush();
|
response.getWriter().flush();
|
||||||
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
HashMap<String, String> map = new HashMap<>();
|
basicResponse.setResultStatus("Tidak Memiliki Otorisasi");
|
||||||
map.put("message", "Tidak ada authorization header");
|
basicResponse.setResultDescription("Tidak ada authorization header");
|
||||||
Gson gson = new Gson();
|
|
||||||
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
||||||
response.setContentType("application/json");
|
response.setContentType("application/json");
|
||||||
response.getWriter().write(gson.toJson(map));
|
response.getWriter().write(gson.toJson(basicResponse));
|
||||||
response.getWriter().flush();
|
response.getWriter().flush();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,10 +1,7 @@
|
|||||||
package id.co.anaheim.gateway.span.controllers;
|
package id.co.anaheim.gateway.span.controllers;
|
||||||
|
|
||||||
import at.favre.lib.crypto.bcrypt.BCrypt;
|
import at.favre.lib.crypto.bcrypt.BCrypt;
|
||||||
import id.co.anaheim.gateway.span.models.AuthDto;
|
import id.co.anaheim.gateway.span.models.*;
|
||||||
import id.co.anaheim.gateway.span.models.AuthResponse;
|
|
||||||
import id.co.anaheim.gateway.span.models.JwtExpiration;
|
|
||||||
import id.co.anaheim.gateway.span.models.User;
|
|
||||||
import id.co.anaheim.gateway.span.repositories.UserRepository;
|
import id.co.anaheim.gateway.span.repositories.UserRepository;
|
||||||
import id.co.anaheim.gateway.span.repositories.jdbc.JdbcUserRepository;
|
import id.co.anaheim.gateway.span.repositories.jdbc.JdbcUserRepository;
|
||||||
import id.co.anaheim.gateway.span.services.JwtService;
|
import id.co.anaheim.gateway.span.services.JwtService;
|
||||||
@ -31,30 +28,40 @@ public class AuthController {
|
|||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
ResponseEntity<AuthResponse> login(@RequestBody AuthDto authDto) {
|
ResponseEntity<AuthResponse> login(@RequestBody AuthDto authDto) {
|
||||||
AuthResponse response = new AuthResponse();
|
AuthResponse response = new AuthResponse();
|
||||||
|
AuthResponseDescription description = new AuthResponseDescription();
|
||||||
|
|
||||||
User user = repository.findByUsername(authDto.getUsername());
|
User user = repository.findByUsername(authDto.getUsername());
|
||||||
if (user == null) {
|
if (user == null) {
|
||||||
response.setMessage("Pengguna tidak ditemukan");
|
response.setResultCode("403");
|
||||||
|
response.setResultStatus("Tidak Memiliki Otorisasi");
|
||||||
|
description.setMessage("Username/Password tidak sesuai");
|
||||||
} else {
|
} else {
|
||||||
BCrypt.Result result = BCrypt.verifyer().verify(authDto.getPassword().toCharArray(), user.getPassword());
|
BCrypt.Result result = BCrypt.verifyer().verify(authDto.getPassword().toCharArray(), user.getPassword());
|
||||||
if (result.verified) {
|
if (result.verified) {
|
||||||
response.setMessage("Berhasil masuk");
|
response.setResultCode("401");
|
||||||
response.setId(user.getId());
|
response.setResultStatus("Berhasil Login");
|
||||||
|
description.setMessage("Berhasil Masuk");
|
||||||
|
description.setId(user.getId());
|
||||||
String token = jwtService.generateToken(user);
|
String token = jwtService.generateToken(user);
|
||||||
response.setToken(token);
|
description.setToken(token);
|
||||||
JwtExpiration jwtExpiration = jwtService.extractExpiration(token);
|
JwtExpiration jwtExpiration = jwtService.extractExpiration(token);
|
||||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||||
response.setTokenExpiration(dateFormat.format(jwtExpiration.getValue()));
|
description.setTokenExpiration(dateFormat.format(jwtExpiration.getValue()));
|
||||||
} else {
|
} else {
|
||||||
response.setMessage("Password tidak sesuai");
|
response.setResultCode("403");
|
||||||
|
response.setResultStatus("Tidak Memiliki Otorisasi");
|
||||||
|
description.setMessage("Username/Password tidak sesuai");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
response.setResultDescription(description);
|
||||||
return ResponseEntity.ok(response);
|
return ResponseEntity.ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/register")
|
@PostMapping("/register")
|
||||||
ResponseEntity<AuthResponse> createDefault() {
|
ResponseEntity<AuthResponse> createDefault() {
|
||||||
AuthResponse response = new AuthResponse();
|
AuthResponse response = new AuthResponse();
|
||||||
|
AuthResponseDescription description = new AuthResponseDescription();
|
||||||
|
|
||||||
User user = repository.findByUsername("admin");
|
User user = repository.findByUsername("admin");
|
||||||
if (user == null) {
|
if (user == null) {
|
||||||
user = new User();
|
user = new User();
|
||||||
@ -66,12 +73,16 @@ public class AuthController {
|
|||||||
user.setRole("ADMIN");
|
user.setRole("ADMIN");
|
||||||
repository.create(user);
|
repository.create(user);
|
||||||
|
|
||||||
response.setMessage("Pendaftaran berhasil");
|
response.setResultCode("Pendaftaran berhasil");
|
||||||
response.setId(user.getId());
|
description.setMessage("Pendaftaran berhasil");
|
||||||
|
description.setId(user.getId());
|
||||||
|
response.setResultDescription(description);
|
||||||
return ResponseEntity.ok(response);
|
return ResponseEntity.ok(response);
|
||||||
}
|
}
|
||||||
response.setMessage("Pengguna dengan username admin sudah ada");
|
response.setResultCode("400");
|
||||||
response.setId(user.getId());
|
description.setMessage("Pengguna dengan username admin sudah ada");
|
||||||
|
description.setId(user.getId());
|
||||||
|
response.setResultDescription(description);
|
||||||
return ResponseEntity.ok(response);
|
return ResponseEntity.ok(response);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,8 +4,8 @@ import lombok.Data;
|
|||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class AuthResponse {
|
public class AuthResponse {
|
||||||
private String id;
|
private String fileName;
|
||||||
private String token;
|
private String resultCode;
|
||||||
private String message;
|
private String resultStatus;
|
||||||
private String tokenExpiration;
|
private AuthResponseDescription resultDescription;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,11 @@
|
|||||||
|
package id.co.anaheim.gateway.span.models;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class AuthResponseDescription {
|
||||||
|
private String id;
|
||||||
|
private String token;
|
||||||
|
private String message;
|
||||||
|
private String tokenExpiration;
|
||||||
|
}
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
package id.co.anaheim.gateway.span.models;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class BasicResponse {
|
||||||
|
private String fileName;
|
||||||
|
private String resultCode;
|
||||||
|
private String resultStatus;
|
||||||
|
private String resultDescription;
|
||||||
|
}
|
||||||
@ -10,5 +10,6 @@ import java.util.Date;
|
|||||||
public class JwtExpiration {
|
public class JwtExpiration {
|
||||||
private boolean valid;
|
private boolean valid;
|
||||||
private Date value;
|
private Date value;
|
||||||
private String message;
|
private String status;
|
||||||
|
private String description;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,5 +8,6 @@ import lombok.Data;
|
|||||||
public class JwtUsername {
|
public class JwtUsername {
|
||||||
private boolean valid;
|
private boolean valid;
|
||||||
private String value;
|
private String value;
|
||||||
private String message;
|
private String status;
|
||||||
|
private String description;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -9,5 +9,6 @@ import lombok.Data;
|
|||||||
public class JwtValidationResult {
|
public class JwtValidationResult {
|
||||||
private Claims claims;
|
private Claims claims;
|
||||||
private boolean valid;
|
private boolean valid;
|
||||||
private String message;
|
private String status;
|
||||||
|
private String description;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -63,11 +63,11 @@ public class JwtService {
|
|||||||
public JwtValidationResult validateToken(String token, UserDetails userDetails) {
|
public JwtValidationResult validateToken(String token, UserDetails userDetails) {
|
||||||
JwtExpiration expirationDate = extractExpiration(token);
|
JwtExpiration expirationDate = extractExpiration(token);
|
||||||
if (!expirationDate.isValid() || (expirationDate.getValue() != null && expirationDate.getValue().before(new Date()))) {
|
if (!expirationDate.isValid() || (expirationDate.getValue() != null && expirationDate.getValue().before(new Date()))) {
|
||||||
return JwtValidationResult.builder().message("JWT token is expired").valid(false).build();
|
return JwtValidationResult.builder().status("Tidak Memiliki Otorisasi").description("Token yang Digunakan Expired").valid(false).build();
|
||||||
}
|
}
|
||||||
JwtUsername username = extractUsername(token);
|
JwtUsername username = extractUsername(token);
|
||||||
if (!username.isValid()) {
|
if (!username.isValid()) {
|
||||||
return JwtValidationResult.builder().message(username.getMessage()).valid(false).build();
|
return JwtValidationResult.builder().status(username.getStatus()).description(username.getDescription()).valid(false).build();
|
||||||
}
|
}
|
||||||
boolean valid = userDetails.getUsername().equals(username.getValue()) && !expirationDate.getValue().before(new Date());
|
boolean valid = userDetails.getUsername().equals(username.getValue()) && !expirationDate.getValue().before(new Date());
|
||||||
return JwtValidationResult.builder().valid(valid).build();
|
return JwtValidationResult.builder().valid(valid).build();
|
||||||
@ -79,7 +79,7 @@ public class JwtService {
|
|||||||
Date value = result.getClaims().getExpiration();
|
Date value = result.getClaims().getExpiration();
|
||||||
return JwtExpiration.builder().value(value).valid(true).build();
|
return JwtExpiration.builder().value(value).valid(true).build();
|
||||||
}
|
}
|
||||||
return JwtExpiration.builder().message(result.getMessage()).valid(false).build();
|
return JwtExpiration.builder().description(result.getDescription()).status(result.getStatus()).valid(false).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
public JwtUsername extractUsername(String token) {
|
public JwtUsername extractUsername(String token) {
|
||||||
@ -88,7 +88,7 @@ public class JwtService {
|
|||||||
String value = result.getClaims().getSubject();
|
String value = result.getClaims().getSubject();
|
||||||
return JwtUsername.builder().value(value).valid(true).build();
|
return JwtUsername.builder().value(value).valid(true).build();
|
||||||
}
|
}
|
||||||
return JwtUsername.builder().message(result.getMessage()).valid(false).build();
|
return JwtUsername.builder().description(result.getDescription()).valid(false).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
public String extractStaticToken(String token) {
|
public String extractStaticToken(String token) {
|
||||||
@ -100,27 +100,33 @@ public class JwtService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public JwtValidationResult getAllClaimsFromToken(String token) {
|
public JwtValidationResult getAllClaimsFromToken(String token) {
|
||||||
String message = "";
|
String description = "";
|
||||||
|
String status = "";
|
||||||
try {
|
try {
|
||||||
Claims claims = Jwts.parserBuilder().setSigningKey(getSignKey()).build().parseClaimsJws(token).getBody();
|
Claims claims = Jwts.parserBuilder().setSigningKey(getSignKey()).build().parseClaimsJws(token).getBody();
|
||||||
return JwtValidationResult.builder().valid(true).claims(claims).message(message).build();
|
return JwtValidationResult.builder().valid(true).claims(claims).description(description).status(status).build();
|
||||||
} catch (MalformedJwtException e) {
|
} catch (MalformedJwtException e) {
|
||||||
log.error("Invalid JWT token: {}", e.getMessage());
|
log.error("Invalid JWT token: {}", e.getMessage());
|
||||||
message = "JWT token tidak sesuai";
|
status = "Tidak Memiliki Otorisasi";
|
||||||
|
description = "Token yang Digunakan Salah";
|
||||||
} catch (ExpiredJwtException e) {
|
} catch (ExpiredJwtException e) {
|
||||||
log.error("JWT token is expired: {}", e.getMessage());
|
log.error("JWT token is expired: {}", e.getMessage());
|
||||||
message = "JWT token telah kadaluarsa";
|
status = "Tidak Memiliki Otorisasi";
|
||||||
|
description = "Token yang Digunakan Expired";
|
||||||
} catch (UnsupportedJwtException e) {
|
} catch (UnsupportedJwtException e) {
|
||||||
log.error("JWT token is unsupported: {}", e.getMessage());
|
log.error("JWT token is unsupported: {}", e.getMessage());
|
||||||
message = "JWT token tidak didukung";
|
status = "Tidak Memiliki Otorisasi";
|
||||||
|
description = "Token yang Digunakan Salah";
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.error("JWT claims string is empty: {}", e.getMessage());
|
log.error("JWT claims string is empty: {}", e.getMessage());
|
||||||
message = "String JWT claims kosong";
|
status = "Tidak Memiliki Otorisasi";
|
||||||
|
description = "Token yang Digunakan Salah";
|
||||||
} catch (Exception e){
|
} catch (Exception e){
|
||||||
log.error("Invalid JWT token");
|
log.error("Invalid JWT token");
|
||||||
message = "JWT token tidak sesuai";
|
status = "Tidak Memiliki Otorisasi";
|
||||||
|
description = "Token yang Digunakan Salah";
|
||||||
}
|
}
|
||||||
return JwtValidationResult.builder().valid(false).message(message).build();
|
return JwtValidationResult.builder().valid(false).description(description).status(status).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
private String createToken(Map<String, Object> claims, String username) {
|
private String createToken(Map<String, Object> claims, String username) {
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user