Skip to content

Commit

Permalink
updates for ARRAffinity
Browse files Browse the repository at this point in the history
  • Loading branch information
chtrembl committed Feb 7, 2024
1 parent 18cc79c commit 49bbca3
Show file tree
Hide file tree
Showing 10 changed files with 67 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ function ButtonWithImage({ data, className }) {
const url = window.parent.location.toString();
console.log(`${url} ${productId}`);
const session = url.split('sid=')[1].split('&')[0];
const csrf = url.split('csrf=')[1];
const csrf = url.split('csrf=')[1].split('&')[0];
const arr = url.split('arr=')[1];

const azureURL = `https://azurepetstore.com/api/updatecart?csrf=${csrf}&productId=${productId}`;
console.log(azureURL);

fetch(azureURL, {
headers: {
Cookie: `JSESSIONID=${session}`,
Cookie: `JSESSIONID=${session}; ARRAffinity=${arr};`,
'Content-Type': 'text/html',
},
type: 'GET',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public String updatecart(Model model, @RequestParam Map<String, String> params,
logger.info("session: " + this.sessionUser.getSessionId());
logger.info("jsession: " + this.sessionUser.getJSessionId());
logger.info("csrf: " + this.sessionUser.getCsrfToken());
logger.info("incoming arrAffinity: " + params.get("arrAffinity"));

if(params.get("csrf") == null || !params.get("csrf").equals(this.sessionUser.getCsrfToken()))
{
Expand Down Expand Up @@ -90,11 +91,17 @@ public String updatecart(Model model, @RequestParam Map<String, String> params,

// helper api call for soul machines dp demo... POST URL Encoding intermittent missing headers with POST/FORM Encoding hence the GET hack with UUID
@GetMapping(value = "/api/viewcart", produces = MediaType.TEXT_HTML_VALUE)
public String viewcart() {
public String viewcart(Model model, @RequestParam Map<String, String> params, HttpServletRequest request) {
logger.info("session: " + this.sessionUser.getSessionId());
logger.info("jsession: " + this.sessionUser.getJSessionId());
logger.info("csrf: " + this.sessionUser.getCsrfToken());
logger.info("incoming arrAffinity: " + params.get("arrAffinity"));

if(params.get("csrf") == null || !params.get("csrf").equals(this.sessionUser.getCsrfToken()))
{
return "Invalid CSRF token";
}

this.sessionUser.getTelemetryClient().trackEvent(
String.format("PetStoreApp user %s requesting view cart", this.sessionUser.getName()),
this.sessionUser.getCustomEventProperties(), null);
Expand All @@ -106,11 +113,11 @@ public String viewcart() {

if (order != null && order.getProducts() != null && !order.isComplete()) {
sb = new StringBuilder();
sb.append("Your order contains a ");
sb.append("Your order contains ");
for (int i = 0; i < order.getProducts().size(); i++) {
sb.append(order.getProducts().get(i).getName()).append(" (").append(order.getProducts().get(i).getQuantity()).append(")");
sb.append("(").append(order.getProducts().get(i).getQuantity()).append(") ").append(order.getProducts().get(i).getName());
if (i < order.getProducts().size() - 1) {
sb.append(", a ");
sb.append(", ");
}
}
}
Expand All @@ -124,6 +131,7 @@ public String completecart(Model model, @RequestParam Map<String, String> params
logger.info("session: " + this.sessionUser.getSessionId());
logger.info("jsession: " + this.sessionUser.getJSessionId());
logger.info("csrf: " + this.sessionUser.getCsrfToken());
logger.info("incoming arrAffinity: " + params.get("arrAffinity"));

if(params.get("csrf") == null || !params.get("csrf").equals(this.sessionUser.getCsrfToken()))
{
Expand Down Expand Up @@ -157,7 +165,7 @@ public String cartcount() {
logger.info("session: " + this.sessionUser.getSessionId());
logger.info("jsession: " + this.sessionUser.getJSessionId());
logger.info("csrf: " + this.sessionUser.getCsrfToken());

this.sessionUser.getTelemetryClient().trackEvent(
String.format("PetStoreApp user %s requesting cart count", this.sessionUser.getName()),
this.sessionUser.getCustomEventProperties(), null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ public String hybridConnection(Model model) throws URISyntaxException {
}

@GetMapping(value = "/soulmachines")
public String soulmachines(Model model, HttpServletRequest request, @RequestParam("sid") Optional<String> sid, @RequestParam("csrf") Optional<String> csrf) throws URISyntaxException {
public String soulmachines(Model model, HttpServletRequest request, @RequestParam("sid") Optional<String> sid, @RequestParam("csrf") Optional<String> csrf, @RequestParam("arr") Optional<String> arr) throws URISyntaxException {
logger.info(String.format("PetStoreApp /soulmachines requested for %s, routing to soulmachines view...",
this.sessionUser.getName()));

Expand All @@ -281,10 +281,24 @@ public String soulmachines(Model model, HttpServletRequest request, @RequestPara
this.sessionUser.setCsrfToken(new HttpSessionCsrfTokenRepository().loadToken(request).getToken().toString());
}

String arrAffinity = "";
if(request.getCookies() != null)
{
for(int i = 0; i < request.getCookies().length; i++)
{
if(request.getCookies()[i].getName().equals("ARRAffinity"))
{
arrAffinity = request.getCookies()[i].getValue();
}
}
}

model.addAttribute("arrAffinity", arrAffinity);

String url = request.getRequestURL().toString() + "?" + request.getQueryString();
if(!url.contains("sid") || !url.contains("csrf"))
{
return "redirect:soulmachines?sid="+this.sessionUser.getJSessionId()+"&csrf="+this.sessionUser.getCsrfToken();
return "redirect:soulmachines?sid="+this.sessionUser.getJSessionId()+"&csrf="+this.sessionUser.getCsrfToken()+"&arr="+arrAffinity;
}

return "soulmachines";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<script>
var sid = "[[${sid}]]";
var csrf = "[[${_csrf.token}]]";
var arr = "[[${arrAffinity}]]";
</script>

<div
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<style>
</style>

<iframe id="soulmachines" th:src="@{'https://azurepetstore.com/static/index.html?sid=' + ${sid} + '&csrf=' + ${_csrf.token}}" style="overflow: hidden; top:0; left:0; bottom:0; right:0; width:100%; height:522px; border:none; margin:0; padding:0;" scrolling="no">
<iframe id="soulmachines" th:src="@{'https://azurepetstore.com/static/index.html?sid=' + ${sid} + '&csrf=' + ${_csrf.token}} + '&arr=' + ${arrAffinity}}" style="overflow: hidden; top:0; left:0; bottom:0; right:0; width:100%; height:522px; border:none; margin:0; padding:0;" scrolling="no">
Your browser doesn't support iframes
</iframe>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import com.microsoft.bot.builder.MessageFactory;
import com.microsoft.bot.builder.TurnContext;
import com.microsoft.bot.builder.UserState;
import com.microsoft.bot.schema.Activity;
import com.microsoft.bot.schema.Attachment;
import com.microsoft.bot.schema.ChannelAccount;

Expand Down Expand Up @@ -88,7 +87,7 @@ public CompletableFuture<Void> onTurn(TurnContext turnContext) {
AzurePetStoreSessionInfo azurePetStoreSessionInfo = configureSession(turnContext, text);

if (azurePetStoreSessionInfo != null && azurePetStoreSessionInfo.getNewText() != null) {
// get the text without the session id and csrf token
// get the text without the session id, csrf token and arr affinity
text = azurePetStoreSessionInfo.getNewText();
}

Expand Down Expand Up @@ -120,7 +119,7 @@ protected CompletableFuture<Void> onMessageActivity(TurnContext turnContext) {
AzurePetStoreSessionInfo azurePetStoreSessionInfo = configureSession(turnContext, text);

if (azurePetStoreSessionInfo != null && azurePetStoreSessionInfo.getNewText() != null) {
// get the text without the session id and csrf token
// get the text without the session id, csrf token and arr affinity
text = azurePetStoreSessionInfo.getNewText();
}

Expand Down Expand Up @@ -254,7 +253,7 @@ protected CompletableFuture<Void> onMembersAdded(
AzurePetStoreSessionInfo azurePetStoreSessionInfo = configureSession(turnContext, text);

if (azurePetStoreSessionInfo != null && azurePetStoreSessionInfo.getNewText() != null) {
// get the text without the session id and csrf token
// get the text without the session id, csrf token and arr affinity
text = azurePetStoreSessionInfo.getNewText();
}

Expand Down Expand Up @@ -302,7 +301,7 @@ private AzurePetStoreSessionInfo configureSession(TurnContext turnContext, Strin
existingPrompts = azurePetStoreSessionInfo.getPrompts();
}

// strip out session id and csrf token if one was passed in
// strip out session id, csrf token and arr affinity if one was passed in
AzurePetStoreSessionInfo incomingAzurePetStoreSessionInfo = PetStoreAssistantUtilities
.getAzurePetStoreSessionInfo(text);
if (incomingAzurePetStoreSessionInfo != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@
public class AzurePetStoreSessionInfo implements Serializable{
private String sessionID = null;
private String csrfToken = null;
private String arrAffinity = null;
@JsonIgnore
private String newText = null;
private String id = null;

private List<Prompt> prompts = null;

public AzurePetStoreSessionInfo(String sessionID, String csrfToken, String newText) {
public AzurePetStoreSessionInfo(String sessionID, String csrfToken, String arrAffinity, String newText) {
super();
this.sessionID = sessionID.trim().toUpperCase(); //JSESSION needs to be UPPER CASE
this.csrfToken = csrfToken.trim(); //CSRF needs to be exact case
this.arrAffinity = arrAffinity.trim(); //ARRAffinity for App Service Session Stickiness
this.newText = newText.trim();
}
public String getSessionID() {
Expand All @@ -26,6 +28,9 @@ public String getSessionID() {
public String getCsrfToken() {
return csrfToken;
}
public String getArrAffinity() {
return arrAffinity;
}
public String getNewText() {
return newText;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,15 @@ public DPResponse updateCart(AzurePetStoreSessionInfo azurePetStoreSessionInfo,
.url(this.UPDATE_CART_URL + "?csrf=" + azurePetStoreSessionInfo.getCsrfToken()
+ "&productId=" + productId)
.method("GET", null)
.addHeader("Cookie", "JSESSIONID=" + azurePetStoreSessionInfo.getSessionID())
.addHeader("Cookie", "JSESSIONID=" + azurePetStoreSessionInfo.getSessionID()+"; ARRAffinity="+azurePetStoreSessionInfo.getArrAffinity())
.addHeader("Content-Type", "text/html")
.build();

this.client.newCall(request).execute();

LOGGER.info("Updated cart with product id: " + productId + " for session id: "
+ azurePetStoreSessionInfo.getSessionID() + " csrf: "
+ azurePetStoreSessionInfo.getCsrfToken());
+ azurePetStoreSessionInfo.getSessionID() + " csrf token: "
+ azurePetStoreSessionInfo.getCsrfToken() + " arr affinity: " + azurePetStoreSessionInfo.getArrAffinity());

dpResponse.setDpResponseText("I just added the "
+ this.cosmosDB.getProducts().get(productId).getName()
Expand All @@ -57,8 +57,8 @@ public DPResponse updateCart(AzurePetStoreSessionInfo azurePetStoreSessionInfo,
+ azurePetStoreSessionInfo.getSessionID() + " " + e.getMessage());
dpResponse.setDpResponseText("I'm sorry, I wasn't able to add the "
+ this.cosmosDB.getProducts().get(productId).getName()
+ " to your cart. " + azurePetStoreSessionInfo.getSessionID() + "|"
+ azurePetStoreSessionInfo.getCsrfToken());
+ " to your cart. session id: " + azurePetStoreSessionInfo.getSessionID() + " csrf token: "
+ azurePetStoreSessionInfo.getCsrfToken() + " arr affinity: " + azurePetStoreSessionInfo.getArrAffinity());
}

dpResponse.setClassification(Classification.UPDATE_SHOPPING_CART);
Expand All @@ -81,18 +81,18 @@ public DPResponse viewCart(AzurePetStoreSessionInfo azurePetStoreSessionInfo) {
response = this.client.newCall(request).execute();

LOGGER.info("Retrieved cart items for session id: "
+ azurePetStoreSessionInfo.getSessionID() + " csrf: "
+ azurePetStoreSessionInfo.getCsrfToken());
+ azurePetStoreSessionInfo.getSessionID() + " csrf token: "
+ azurePetStoreSessionInfo.getCsrfToken() + " arr affinity: " + azurePetStoreSessionInfo.getArrAffinity());

dpResponse.setDpResponseText(response.body().string());

dpResponse.setUpdateCart(true);
} catch (Exception e) {
LOGGER.error("Error retrieving cart items for session id: "
+ azurePetStoreSessionInfo.getSessionID() + " " + e.getMessage());
dpResponse.setDpResponseText("I'm sorry, I wasn't able to retrieve your shopping cart. "
+ azurePetStoreSessionInfo.getSessionID() + "|"
+ azurePetStoreSessionInfo.getCsrfToken());
dpResponse.setDpResponseText("I'm sorry, I wasn't able to retrieve your shopping cart. session id: "
+ azurePetStoreSessionInfo.getSessionID() + " csrf token: "
+ azurePetStoreSessionInfo.getCsrfToken() + " arr affinity: " + azurePetStoreSessionInfo.getArrAffinity());
} finally
{
if(response.body() != null)
Expand All @@ -116,25 +116,25 @@ public DPResponse completeCart(AzurePetStoreSessionInfo azurePetStoreSessionInfo
Request request = new Request.Builder()
.url(this.COMPLETE_CART_URL + "?csrf=" + azurePetStoreSessionInfo.getCsrfToken())
.method("GET", null)
.addHeader("Cookie", "JSESSIONID=" + azurePetStoreSessionInfo.getSessionID())
.addHeader("Cookie", "JSESSIONID=" + azurePetStoreSessionInfo.getSessionID()+"; ARRAffinity="+azurePetStoreSessionInfo.getArrAffinity())
.addHeader("Content-Type", "text/html")
.build();

response = this.client.newCall(request).execute();

LOGGER.info("Completed cart for session id: "
+ azurePetStoreSessionInfo.getSessionID() + " csrf: "
+ azurePetStoreSessionInfo.getCsrfToken());
+ azurePetStoreSessionInfo.getSessionID() + " csrf token: "
+ azurePetStoreSessionInfo.getCsrfToken() + " arr affinity: " + azurePetStoreSessionInfo.getArrAffinity());

dpResponse.setDpResponseText(response.body().string());

dpResponse.setCompleteCart(true);
} catch (Exception e) {
LOGGER.error("Error completing cart for session id: "
+ azurePetStoreSessionInfo.getSessionID() + " " + e.getMessage());
dpResponse.setDpResponseText("I'm sorry, I wasn't able to place your order. "
+ azurePetStoreSessionInfo.getSessionID() + "|"
+ azurePetStoreSessionInfo.getCsrfToken());
dpResponse.setDpResponseText("I'm sorry, I wasn't able to place your order. session id: "
+ azurePetStoreSessionInfo.getSessionID() + " csrf token: "
+ azurePetStoreSessionInfo.getCsrfToken() + " arr affinity: " + azurePetStoreSessionInfo.getArrAffinity());
}
finally
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,18 @@ public static String cleanDataFromAOAIResponseContent(String content) {

public static AzurePetStoreSessionInfo getAzurePetStoreSessionInfo(String text) {
AzurePetStoreSessionInfo azurePetStoreSessionInfo = null;

Pattern pattern = Pattern.compile("sid=(.*)&csrf=(.*)");
//text comes throgh from DP as "text https://azurepetstore.com/soulmachines?sid=[sessionId]&csrf=[csrfToken]&arr=[arrAffinity]"
Pattern pattern = Pattern.compile("sid=(.*)&csrf=(.*)&arr=(.*)");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
String sessionID = matcher.group(1);
String csrfToken = matcher.group(2);
String arrAffinity = matcher.group(3);
String newText = text.substring(0, text.indexOf("http")).trim();
azurePetStoreSessionInfo = new AzurePetStoreSessionInfo(sessionID, csrfToken, newText);
LOGGER.info("Found session id:" + sessionID + " and csrf token:" + csrfToken + " in text: " + text + " new text: " + newText);
azurePetStoreSessionInfo = new AzurePetStoreSessionInfo(sessionID, csrfToken, arrAffinity, newText);
LOGGER.info("Found session id:" + sessionID + ", csrf token:" + csrfToken + " and arr affinity:" + arrAffinity + " in text: " + text + " new text: " + newText);
} else {
LOGGER.info("No new session id or csrf token found in text: " + text);
LOGGER.info("No new session id, csrf token or arr affinity found in text: " + text);
}

return azurePetStoreSessionInfo;
Expand Down

0 comments on commit 49bbca3

Please sign in to comment.