Skip to content

Commit

Permalink
[Rahul] | BAH-3374 | Add. Session Cookies To REST Post Calls (#96)
Browse files Browse the repository at this point in the history
  • Loading branch information
rahu1ramesh authored Dec 22, 2023
1 parent 6d7bae6 commit 5a8a7a1
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,11 @@
import org.bahmni.openerp.web.client.strategy.OpenERPClientStrategy;
import org.bahmni.openerp.web.http.client.RestClient;
import org.bahmni.openerp.web.request.OpenERPRequest;
import org.bahmni.openerp.web.request.builder.Parameter;
import org.bahmni.openerp.web.request.builder.RequestBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
@Lazy
public class OdooRESTClient implements OpenERPClientStrategy {
Expand All @@ -22,10 +18,11 @@ public class OdooRESTClient implements OpenERPClientStrategy {
public OdooRESTClient(OpenERPProperties openERPProperties) {
final String host = openERPProperties.getHost();
final int port = openERPProperties.getPort();
final String database = openERPProperties.getDatabase();
final String user = openERPProperties.getUser();
final String password = openERPProperties.getPassword();
final int connectionTimeoutInMilliseconds = openERPProperties.getConnectionTimeoutInMilliseconds();
restClient = new RestClient("http://" + host + ":" + port, user, password, connectionTimeoutInMilliseconds);
restClient = new RestClient("http://" + host + ":" + port, user, password, connectionTimeoutInMilliseconds, database);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,56 +1,56 @@
package org.bahmni.openerp.web.http.client;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bahmni.openerp.web.OpenERPException;
import org.bahmni.openerp.web.request.OpenERPRequest;
import org.bahmni.openerp.web.request.builder.Parameter;
import org.bahmni.openerp.web.request.builder.RequestBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.Duration;
import java.util.Arrays;
import java.util.UUID;
import java.util.HashMap;
import java.util.function.Consumer;

public class RestClient {
private static final Logger logger = LogManager.getLogger(RestClient.class);
private WebClient webClient;
private String accessToken;
private final String baseURL;
private final String database;
private final String username;
private final String password;
private final int connectionTimeout;
private String sessionId;

public RestClient(String baseURL, String username, String password, int connectionTimeout) {
public RestClient(String baseURL, String username, String password, int connectionTimeout, String database) {
this.database = database;
this.baseURL = baseURL;
this.username = username;
this.password = password;
this.connectionTimeout = connectionTimeout;
}

private void login() {
if (accessToken == null) {
OpenERPRequest openERPRequest = new OpenERPRequest("res.users", "login", Arrays.asList(new Parameter("username", username), new Parameter("password", password)));
String requestBody = RequestBuilder.buildNewRestRequest(openERPRequest);
if (sessionId == null) {
String requestBody = buildLoginRequest();
WebClient client = getWebClient(baseURL);
HttpHeaders headers = getHttpHeaders();
Consumer<HttpHeaders> consumer = httpHeaders -> httpHeaders.addAll(headers);
try{
String response = client.post().uri("api/odoo-login").headers(consumer).bodyValue(requestBody).retrieve().bodyToMono(String.class).timeout(Duration.ofMillis(connectionTimeout)).block();
logger.debug("\n-----------------------------------------------------Login Initiated-----------------------------------------------------\n* Request : {}\n* Response : {}\n-----------------------------------------------------End of Login-----------------------------------------------------", requestBody, response);
if (response == null) {
throw new OpenERPException("Login failed");
Consumer < HttpHeaders > consumer = httpHeaders -> httpHeaders.addAll(headers);
try {
client.post().uri("web/session/authenticate").headers(consumer).bodyValue(requestBody).exchangeToMono(loginResponse -> {
if(loginResponse.statusCode().is2xxSuccessful()) {
try {
sessionId = loginResponse.cookies().get("session_id").get(0).getValue();
logger.debug("Login session_id: {}", sessionId);
} catch (Exception e) {
logger.warn("Failed to login for user {}", username);
throw new OpenERPException(String.format("Failed to login. The login user is : %s", username));
}
}
ObjectMapper objectMapper = new ObjectMapper();
JsonNode responseNode = objectMapper.readTree(response);
accessToken = responseNode.get("result").get("data").get("access_token").asText();
}
catch (Exception e){
return loginResponse.bodyToMono(String.class);
}).timeout(Duration.ofMillis(connectionTimeout)).block();
logger.debug("\n-----------------------------------------------------Login Initiated-----------------------------------------------------\n* Request : {}\n* Session Id : {}\n-----------------------------------------------------End of Login-----------------------------------------------------", requestBody, sessionId);
} catch (Exception e) {
logger.warn("Failed to login for user {}", username);
throw new OpenERPException(String.format("Failed to login. The login user is : %s", username));
}
Expand All @@ -63,10 +63,9 @@ public String post(String URL, String requestBody) {
logger.debug("Post Data: {}", requestBody);
WebClient client = getWebClient(baseURL);
HttpHeaders headers = getHttpHeaders();
headers.set(HttpHeaders.AUTHORIZATION, accessToken);
Consumer<HttpHeaders> consumer = httpHeaders -> httpHeaders.addAll(headers);
String response = client.post().uri(URL).headers(consumer).bodyValue(requestBody).retrieve().bodyToMono(String.class).timeout(Duration.ofMillis(connectionTimeout)).block();
logger.debug("\n-----------------------------------------------------{} Initiated-----------------------------------------------------\n* Request : {}\n* Response : {}\n-----------------------------------------------------End of {}-----------------------------------------------------", URL, requestBody, response, URL);
Consumer < HttpHeaders > consumer = httpHeaders -> httpHeaders.addAll(headers);
String response = client.post().uri(URL).headers(consumer).cookie("session_id", sessionId).bodyValue(requestBody).retrieve().bodyToMono(String.class).timeout(Duration.ofMillis(connectionTimeout)).block();
logger.debug("\n-----------------------------------------------------{} Initiated-----------------------------------------------------\n* Cookies : {}\n* Request : {}\n* Response : {}\n-----------------------------------------------------End of {}-----------------------------------------------------", URL, sessionId, requestBody, response, URL);
if (response == null) {
throw new OpenERPException(String.format("Could not post to %s", URL));
}
Expand All @@ -81,8 +80,8 @@ public String post(String URL, String requestBody) {
}

private WebClient getWebClient(String baseURL) {
if(webClient == null){
webClient = WebClient.builder()
if (webClient == null) {
webClient = WebClient.builder()
.baseUrl(baseURL)
.build();
}
Expand All @@ -96,4 +95,19 @@ private HttpHeaders getHttpHeaders() {
return httpHeaders;
}

private String buildLoginRequest() {
try {
HashMap < String, Object > params = new HashMap < > ();
params.put("db", database);
params.put("login", username);
params.put("password", password);
HashMap < String, Object > requestBody = new HashMap < > ();
requestBody.put("params", params);
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(requestBody);
} catch (Exception e) {
throw new OpenERPException(e);
}
}

}

0 comments on commit 5a8a7a1

Please sign in to comment.