Skip to content
Merged

Test #38

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ configurations {
extendsFrom annotationProcessor
}
}
configurations.configureEach {
resolutionStrategy {
force 'com.google.protobuf:protobuf-java:4.34.0'
force 'com.google.protobuf:protobuf-java-util:4.34.0'
eachDependency { details ->
if (details.requested.group == 'com.google.protobuf' && (details.requested.name == 'protobuf-java' || details.requested.name == 'protobuf-java-util')) {
details.useVersion '4.34.0'
details.because 'Keep protobuf runtime aligned with generated proto-common classes'
}
}
}
}

repositories {
mavenCentral()
Expand All @@ -35,6 +47,14 @@ repositories {
password = System.getenv("GITHUB_TOKEN") ?: ""
}
}
maven {
name = "GitHubPackagesObservability"
url = uri("https://maven.pkg.github.com/Management-System-for-Rental-SEP490/ISUMS_Observability-Common")
credentials {
username = System.getenv("GITHUB_ACTOR") ?: ""
password = System.getenv("GITHUB_TOKEN") ?: ""
}
}
}

dependencyManagement {
Expand All @@ -45,6 +65,10 @@ dependencyManagement {
}

dependencies {
implementation 'net.logstash.logback:logstash-logback-encoder:8.1'
implementation 'io.opentelemetry:opentelemetry-exporter-otlp'
implementation 'io.micrometer:micrometer-tracing-bridge-otel'
implementation 'com.isums:isums-observability-common:1.0-SNAPSHOT'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
Expand All @@ -59,7 +83,7 @@ dependencies {
// implementation 'net.devh:grpc-server-spring-boot-starter:3.1.0.RELEASE'
// implementation 'net.devh:grpc-client-spring-boot-starter:3.1.0.RELEASE'
// implementation 'javax.annotation:javax.annotation-api:1.3.2'
implementation 'com.google.protobuf:protobuf-java:4.34.0-RC2'
implementation 'com.google.protobuf:protobuf-java:4.34.0'
implementation "org.springframework.grpc:spring-grpc-client-spring-boot-starter"
// implementation "io.grpc:grpc-netty-shaded"
implementation "org.mapstruct:mapstruct:1.6.3"
Expand Down Expand Up @@ -100,3 +124,5 @@ dependencies {
tasks.named('test') {
useJUnitPlatform()
}

tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8' }
Original file line number Diff line number Diff line change
@@ -1,52 +1,118 @@
package com.isums.userservice.configurations;

import io.grpc.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
public class GrpcJwtServerInterceptor implements ServerInterceptor {

private static final Metadata.Key<String> AUTHORIZATION =
Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);

private final JwtDecoder jwtDecoder;

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call,
Metadata headers,
ServerCallHandler<ReqT, RespT> next) {

String auth = headers.get(AUTHORIZATION);
if (auth == null || !auth.startsWith("Bearer ")) {
log.info("No token in gRPC call — passing through");
return next.startCall(call, headers);
}

String tokenValue = auth.substring("Bearer ".length()).trim();

try {
Jwt jwt = jwtDecoder.decode(tokenValue);

AbstractAuthenticationToken authentication = new JwtAuthenticationToken(jwt);
SecurityContextHolder.getContext().setAuthentication(authentication);

return next.startCall(call, headers);

} catch (Exception ex) {
call.close(Status.UNAUTHENTICATED.withDescription("Invalid token"), new Metadata());
return new ServerCall.Listener<>() {};
} finally {
SecurityContextHolder.clearContext();
}
}
}
package com.isums.userservice.configurations;

import io.grpc.ForwardingServerCallListener;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
public class GrpcJwtServerInterceptor implements ServerInterceptor {

private static final Metadata.Key<String> AUTHORIZATION =
Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
private static final Metadata.Key<String> REQUEST_ID =
Metadata.Key.of("x-request-id", Metadata.ASCII_STRING_MARSHALLER);
private static final Metadata.Key<String> CORRELATION_ID =
Metadata.Key.of("x-correlation-id", Metadata.ASCII_STRING_MARSHALLER);
private static final Metadata.Key<String> ACTOR_USER_ID =
Metadata.Key.of("actor-user-id", Metadata.ASCII_STRING_MARSHALLER);
private static final Metadata.Key<String> ACTOR_ROLE =
Metadata.Key.of("actor-role", Metadata.ASCII_STRING_MARSHALLER);
private static final Metadata.Key<String> TRACEPARENT =
Metadata.Key.of("traceparent", Metadata.ASCII_STRING_MARSHALLER);

private final JwtDecoder jwtDecoder;

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call,
Metadata headers,
ServerCallHandler<ReqT, RespT> next) {

setupMdc(headers, call.getMethodDescriptor().getFullMethodName());

String auth = headers.get(AUTHORIZATION);
if (auth == null || !auth.startsWith("Bearer ")) {
log.info("No token in gRPC call - passing through");
return clearContextOnClose(next.startCall(call, headers));
}

String tokenValue = auth.substring("Bearer ".length()).trim();

try {
Jwt jwt = jwtDecoder.decode(tokenValue);

AbstractAuthenticationToken authentication = new JwtAuthenticationToken(jwt);
SecurityContextHolder.getContext().setAuthentication(authentication);

return clearContextOnClose(next.startCall(call, headers));

} catch (Exception ex) {
call.close(Status.UNAUTHENTICATED.withDescription("Invalid token"), new Metadata());
clear();
return new ServerCall.Listener<>() {};
}
}

private <ReqT> ServerCall.Listener<ReqT> clearContextOnClose(ServerCall.Listener<ReqT> delegate) {
return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>(delegate) {
@Override
public void onComplete() {
try {
super.onComplete();
} finally {
clear();
}
}

@Override
public void onCancel() {
try {
super.onCancel();
} finally {
clear();
}
}
};
}

private void setupMdc(Metadata headers, String grpcMethod) {
putIfPresent("requestId", headers.get(REQUEST_ID));
putIfPresent("correlationId", headers.get(CORRELATION_ID));
putIfPresent("userId", headers.get(ACTOR_USER_ID));
putIfPresent("role", headers.get(ACTOR_ROLE));
putIfPresent("grpcMethod", grpcMethod);
String traceparent = headers.get(TRACEPARENT);
if (traceparent != null) {
String[] parts = traceparent.split("-");
if (parts.length >= 4) {
putIfPresent("traceId", parts[1]);
putIfPresent("spanId", parts[2]);
}
}
}

private void putIfPresent(String key, String value) {
if (value != null && !value.isBlank()) {
MDC.put(key, value);
}
}

private void clear() {
SecurityContextHolder.clearContext();
MDC.clear();
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
package com.isums.userservice.configurations;

import io.grpc.ServerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class GrpcServerConfig {
import io.grpc.ServerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.grpc.server.security.AuthenticationProcessInterceptor;
import org.springframework.grpc.server.security.GrpcSecurity;

import java.util.List;

@Configuration
public class GrpcServerConfig {

@Bean
public List<ServerInterceptor> globalInterceptors(GrpcJwtServerInterceptor jwt) {
return List.of(jwt);
}
}
public List<ServerInterceptor> globalInterceptors(GrpcJwtServerInterceptor jwt) {
return List.of(jwt);
}

@Bean
public AuthenticationProcessInterceptor grpcAuthenticationProcessInterceptor(GrpcSecurity grpc) throws Exception {
return grpc
.authorizeRequests(auth -> auth.allRequests().permitAll())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
package com.isums.userservice.configurations;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {

private static final String BEARER_SCHEME = "bearerAuth";

@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.info(new Info()
.title("EContract Service API")
.version("v1")
.description("Có nhiều thứ rất là khó nói vậy nên là lá đò"))
.addSecurityItem(new SecurityRequirement().addList(BEARER_SCHEME))
.components(new Components().addSecuritySchemes(
BEARER_SCHEME,
new SecurityScheme().name(BEARER_SCHEME).type(SecurityScheme.Type.HTTP)
.scheme("bearer").bearerFormat("JWT")
));
}
}
package com.isums.userservice.configurations;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {

private static final String BEARER_SCHEME = "bearerAuth";

@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.info(new Info()
.title("EContract Service API")
.version("v1")
.description("ISUMS service API documentation"))
.addSecurityItem(new SecurityRequirement().addList(BEARER_SCHEME))
.components(new Components().addSecuritySchemes(
BEARER_SCHEME,
new SecurityScheme().name(BEARER_SCHEME).type(SecurityScheme.Type.HTTP)
.scheme("bearer").bearerFormat("JWT")
));
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import com.isums.userservice.infrastructures.abstracts.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
Expand Down Expand Up @@ -74,6 +73,19 @@ public ApiResponse<Void> updateMainHouse(@RequestBody UpdateMainHouseRequest req
return ApiResponses.ok(null, "success to update main house");
}

@PutMapping("/language")
public ApiResponse<Void> updateLanguage(@RequestBody UpdateLanguageRequest req, @AuthenticationPrincipal Jwt jwt) {
userService.updateLanguage(jwt.getSubject(), req.language());
return ApiResponses.ok(null, "success to update language");
}

@PutMapping("/me/phone")
public ApiResponse<Void> updateMyPhone(@RequestBody @Valid UpdatePhoneRequest req,
@AuthenticationPrincipal Jwt jwt) {
userService.updatePhone(jwt.getSubject(), req.phoneNumber());
return ApiResponses.ok(null, "Phone updated");
}

@PostMapping("/technical-staff")
@PreAuthorize("hasRole('LANDLORD')")
public ApiResponse<UserDto> createTechnicalStaff(@RequestBody @Valid CreateTechnicalStaffRequest req) {
Expand All @@ -87,9 +99,29 @@ public ApiResponse<List<StaffDto>> getAllStaffs() {
return ApiResponses.ok(res, "Get staffs successfully");
}

@PostMapping("/manager")
@PreAuthorize("hasRole('LANDLORD')")
public ApiResponse<UserDto> createManager(@RequestBody @Valid CreateManagerRequest req) {
UserDto res = userService.createManger(req);
return ApiResponses.created(res, "Manager created successfully");
}

@GetMapping("/managers")
public ApiResponse<List<StaffDto>> getAllManagers() {
List<StaffDto> res = userService.getAllManagers();
return ApiResponses.ok(res, "Get managers successfully");
}

@GetMapping("/byId/{userId}")
public ApiResponse<UserProfileDto> getUserById(@PathVariable UUID userId) {
UserProfileDto res = userService.getUserById(userId);
return ApiResponses.ok(res, "Get user successfully");
}

@PostMapping("/{userId}/admin-reset-password")
@PreAuthorize("hasRole('LANDLORD')")
public ApiResponse<String> adminResetPassword(@PathVariable UUID userId) {
String tempPassword = userService.adminResetPassword(userId);
return ApiResponses.ok(tempPassword, "Password reset successfully");
}
}
Loading