HMAC authentication of secret and payload in Symfony 5.4

My JavaScript code is making the following POST API call to my endpoint:

const payload = {
   course: args,
   recipient: roomId
};
const signature = this.calculateSignature(JSON.stringify(payload), secret);

const response = await fetch(`https://crmpicco.co.uk/app/api/dsf7s9d8797987897987`, {
   method: 'POST',
   headers: {
      'Content-Type': 'application/json',
      'X-EchoBot-Signature-256': signature 
   },
   body: JSON.stringify(payload)
});

calculateSignature(payload, secret) {
   return "sha256=" + crypto
   .createHmac('sha256', secret)
   .update(payload)
   .digest('hex');
}

in my Symfony 5.4 PHP app I have the following code:

$echoSecret = "0IQgWRFC1872i6AQc3mDo3Dc48UfWATPCoRX";

$encodedPayload = json_encode(json_decode($request->getContent()));
$calculatedSecret = hash_hmac('sha256', $encodedPayload, $echoSecret);
if ($headers['x-echobot-signature-256'][0] == "sha256=" . $calculatedSecret) {
    $this->getLogger()->info('The signature is valid, proceed...', [
        'calculatedSecret' => $calculatedSecret,
        'headerSecret' => $headers['x-echobot-signature-256'][0]
    ]);
} else {
    $this->getLogger()->info('The signature is invalid :(', [
        'calculatedSecret' => $calculatedSecret,
        'headerSecret' => $headers['x-echobot-signature-256'][0]
    ]);
}

Everytime I call the endpoint the authentication fails and falls into the The signature is invalid :( else block.

The request looks like this:

“request”:{“stdClass”:{“course”:[“topaid33″],”recipient”:”!LjZCWlshucBDhBobTT:crm.com”}},”payload”:”{“course”:[“topaid33″],”recipient”:”!LjZCWlshucBDhBobTT:crm.com”}”,”headers”:{“accept-encoding”:[“gzip,
deflate,
br”],”content-type”:[“application/json”],”user-agent”:[“Amazon
CloudFront”],”x-amz-cf-id”:[“ndCQJ9lvWATP_vSerFFFFaqHBhYqOn_wdSLF2vWBShXCBA==”],”x-cloudfront-key”:[“RFC1872″],”x-matrixbot-signature-256”:[“sha256=3577f59ea6f1dd44af8af2e9240093387897897987987a029ccf818ae92ee2cdb99″],”x-forwarded-port”:[“443″],”x-forwarded-proto”:[“https”],”content-length”:[“78″],”via”:[“1.1
ip-10-82-2-81
(Varnish/7.2)”],”host”:[“s.crmpicco.co.uk”],”x-varnish”:[“3735722″],”x-php-ob-level”:[“1”]

Where am I taking a mis-step here?

Object position issue in threejs when replacing object in a scene

I Want to replace an object (objectToBeReplace) from the threejs scene, with the newObject.

I have written the function below.

export const replaceObject = async (
  objectToBeReplace,
  newObj,
  scene
) => {

  //update matrix world of the object
  objectToBeReplace.updateMatrixWorld(true);
  objectToBeReplace.updateMatrix();


    //replace object with the newobject with the same position and rotation
   newObj.position.copy(objectToBeReplace.position.clone());
   newObj.rotation.copy(objectToBeReplace.rotation.clone());
   newObj.scale.copy(objectToBeReplace.scale);
   newObj.quaternion.copy(object.quaternion);
 

  objectToBeReplace.parent.add(newObj);
  objectToBeReplace.parent.remove(objectToBeReplace);
  newObj.updateMatrixWorld(true);
  newObj.updateMatrix();
 

  console.log("object replaced");
};

I want to replace the cooker from the scene with the newCooker.

Before Replacement

Before Replacement

After Replacement
After Replacement

Link for the model
https://o.convrse.ai/pgLMzNwabk-0/low/W0a17ghen08x/armchair-cooker_DFSZa8q2zf95wQ6eFdZTD_optimized.glb

I am able to replace the object, buts it’s position and orientation is getting changed. I want to retain its position and orientation.

Are there any extra parameters in the Mesh or Geometry which affects the position and orientation of the object ?.

Manipulate markers in Google Maps Javascript API v3

I am really struggling with the structure of the new Google Maps Javascript API.

In the tutorial for adding a map with a marker, the new structure wants to async load the library, to load the relevant class(es):


  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

OK, so I wrap this in some sort of async method to init the map


const initMap = async () => {
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
  // ...
}

No problem.. but what happens if I want another method to add or manipulate a marker? Do I call importLibrary again?


const addMarker = async (blah) => {
  // Will this hit some sort of local cache of types??
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
  // ...
}

I mean.. is this thing cached, or is it going to try to import code from the interweb every time? Why do I have to async load just to get a class definition?

There is no top-level await in the browser (yet), so the load of these classes needs to be scoped to a function, which means they are not accessible outside that scope, like.. another function.

How are people doing this? The whole structure of this API seems bonkers to me.

What I want to do is something like this:


// This won't work, but this is what I want to do:
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

class GoogleMap {

  constructor() {
    this._map;
    this._markers = [];
  }

  init(elem) {
    this._map = new Map(elem, {...});
  }

  addMarker(position) {
    this._markers.push(new AdvancedMarkerElement({
      this._map,
      position: position,
    }));
  }
}

What is the best-practice guidance for using this [bonkers] API in this way?

How to check all checkboxes on one field? using JS

I have one field that has 5-6 checkboxes (and will increased more in the future), this field name email_notification, here’s the code that i find on google to automatic check all the check boxes on event Form – On Load.

var checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(function(checkbox) {
    checkbox.checked = true;
});

When I run the code, it will auto check all my checkboxes on field email_notification, it also check all checkboxes on other field. I just want only one field to automatically check all the checkboxes. Is there any clue to change the syntax? Thank you for helping.

I’m not familiar with Javascript, and I’ve been googling about this on one week but didn’t find any clue.

JavaScript Bezier curve compute offset distance

I am drawing a Bezier curve on drag cp1 and cp2 control points.

To draw Bezier Curve using D3js.

Bezier Curve four control points are line1,cp1,cp2 and line2.

I follow below steps to draw a Bezier curve

1)Moveto(Line1)

2)BezierCurve(Cp1 Cp2 Line2)

pathPoints = d3.path();
pathPoints.moveTo(allPaths[0].l1.x,allPaths[0].l1.y);
pathPoints.bezierCurveTo(cp1.x,cp1.y,cp2.x,cp2.y,item.l2.x,item.l2.y);

When I drag cp1 from the mouse events I get positions cp1.

Now I know line1 and cp1 how do I compute dist.

I am using reference code from here

Using pointFromLine function I get cp1 and cp2. I dont know dist.

I also have another function calculatePoint to get cp1 and cp2 on a line1.

cp1 = calculatePoint(item.l1,item.l2,50);
d1 = hypo(item.l1,cp1);
cp2 = calculatePoint(item.l2,item.l1,50);
d2 = hypo(item.l2,cp2);

d1 and d2 after finding the Euclidian Distance is not equal to 50.Is it correct Euclidian distance between line1 and cp1 give distance d1.

function pointFromLine(along, dist, p1, p2, res = {}) {
  const dx = p2.x - p1.x;
  const dy = p2.y - p1.y;
  res.x = p1.x + dx * along - dy * dist;
  res.y = p1.y + dy * along + dx * dist;
  return res;
}

function calculatePoint(a,b,distance)
{

  // a. calculate the vector from o to g:
  let vectorX = b.x - a.x;
  let vectorY = b.y - a.y;
  // b. calculate the proportion of hypotenuse
  let factor = distance / Math.sqrt(vectorX * vectorX + vectorY * vectorY);

  // c. factor the lengths
  vectorX *= factor;
  vectorY *= factor;

  // d. calculate and Draw the new vector,
  // return new Point((int)(a.X + vectorX), (int)(a.Y + vectorY));
  return {x:a.x + vectorX,y:a.y + vectorY}
}

function hypo(p0,p1){
  return Math.round(Math.sqrt((p1.x-p0.x)** 2  + (p1.y-p0.y)** 2 ))
}

Ajax for isn’t refreshing even after submitting the data into database [closed]

$(document).ready(function () {
  $("#stuform").submit(function (event) {
    event.preventDefault();
    ajaxPost();
  });

  function ajaxPost() {
    var formData = {
      name: $("#name").val(),
      email: $("#email").val(),
      password: $("#password").val(),
    };

    //Do Post
    $.ajax({
      type: "post",
      contentType: "application/json",
      url: "http://localhost:8080/SpringMvcWebProjectNew2/savestudent",
      data: JSON.stringify(formData),
      datatype: "json",
      success: function (data) {
        if (data.status == "success") {
          alert("Data Saved Success");
          $("#stuform").reset();
        } else {
          alert("Data Saved Success");
          //$("#stuform").reset();
        }
        console.log(data);
      },
    });
  }
});

This is the javascript code where i am submitting the data into the database, the data is storing into database but the page field isn’t refreshing even after submitting the data, and dosent show any alert message help me find out is there any mistake in my above code

I have tried all the possibilities

HTTP Form Element vs Fetch and XMLHttpRequest

I am currently learning about web development and came across HTTP. One thing that is confusing me is how exactly to make HTTP requests. In the videos I’ve watched the main way they send HTTP requests are through Form Elements. Doing a little bit more research, I also found out that HTTP requests can be done manually via Fetch and XMLHttpRequest.

So I’m a bit confused on how all 3 of these work and the benefits of choosing one over the other. I do apologize if I make any mistakes, but I’m largely confused on the entire matter. I tried manually sending HTTP Requests like PUT and POST with Fetch, but that was kind of a mess. Most tutorials were using Form Elements to do so, so now I’m left wondering if that’s just how it should be done.

I also read over Sending forms through JavaScript but it completely went over my head.

So I tried looking up various tutorials and websites to explain the matter of HTTP requests with HTML/CSS & Javascript. I’m hoping that someone can explain the differences between Forms, Fetch, and XMLHttpRequest. And what are the tradeoffs of using one over the other if that is applicable in this case.

JS frontend technology(UI) that is more useful and efficient but not popular over developers [closed]

I am using vue js for my project, for frontend and I need to know about underated technology or more useful tech which is not widely used but has a potential to be used, like library for animations etc.

can you guys suggest any technolgy,framework or library which is more useful but not widely used by other developers to make our UI experience more creative and efficient or the one that you guys using personally in frontend

How can I make a given number of Promises run at the same time on Nodejs?

So I’m creating this scraping application that essentially uses a REST API for several entities on the server. The main functionallity is just:

let buffer = []
for(entity in entities){
   let data = await scrapingProcessForAnEntity(entity);
   buffer.push(data)
}

I oversimplified the script because the scraping process and how it is stored is not relevant, the point is that I have this function scrapingProcessForAnEntity that gets and returns all the information I need in a Promise.
The thing is, since there are a lot of entities, I want to make it so that I can run the process for multiple entities at a time, and once one of the processes is finished, a new one takes its place. I made some tests trying to use an array of Promises and Promise.race() but I can’t figure how to make the finished Promise quit the array. I also can’t just run the process for all entities at once with a Promise.all() because the server is not capable of handling too many requests at once. It should be ok if I limit it to 3~5 entities.

My current implementation is:

let promises = []
let buffer = []
async function run(){
   for(entity in entities){
      addPromise(() => scrapingProcessForAnEntity(entity))
   }
}

async function addPromise(prom){
   if(promises.length >= 3){ //In this example I'm trying to make it run for up to 3 at a time
      await moveQueue()
   }
   promises.push(prom())
}

async function moveQueue(){
   if(promises.length < 3){
      return
   }
   let data = await Promise.race(promises)
   buffer.push(data)
   promises.splice(promises.indexOf(data), 1) //<---- This is where I'm struggling at
   //how can I remove the finished promised from the array? 
}

Adding the data into to the buffer is not directly implemented in the Promise itself because there’s processing involved in it and I’m not sure if adding the data from 2 promises at the same time might cause an issue.

I also implemented a way to clear all the promises on the end. My only struggle is how to find which promise inside of the array has finished so that it can be replaced.

Bearer authorization token not working for k6 (javascript)

Through PostMAN getting the token successfully, like following

enter image description here

while trying same thing by using k6 java script, it is not working, I assuming the token generating but I might can not use it properly, could you please check what I’m missing here?

What I tried so far! (dummy links are there for posing here)

import http from 'k6/http';
import { sleep } from 'k6';
import { check } from 'k6';

export const options = {
    vus: 1,
    duration: '5s'
};

const BASE_URL_API = 'http://example.com/api/';
const username = 'your_username';
const password = 'your_password';

// Function to obtain the authentication bearer token
function getAuthToken() {
    const loginPayload = JSON.stringify({
        username: username,
        password: password
    });

    const loginHeaders = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    };

    const loginResponse = http.post(`${BASE_URL_API}login`, loginPayload, { headers: loginHeaders });

    // Check if the token request was successful (status code 200)
    check(loginResponse, {
        'API: Status code is 200 for obtaining token': (r) => r.status === 200
    });

    const token = loginResponse.json('token');
    return `Bearer ${token}`;
}

export default function() {
    // Obtain the authentication bearer token
    const authToken = getAuthToken();

    // Define the headers for authenticated requests
    const headers = {
        Authorization: authToken,
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    };

    // Send authenticated requests with additional headers
    const apiResp1 = http.get(`${BASE_URL_API}resource1`, { headers });
    check(apiResp1, {
        'API: Status code is 200 for resource1': (r) => r.status === 200
    });

}

Getting output out for following implementation, by considering output (below) assuming it is generating the token, but i’m not using it in proper way!

enter image description here

React-hook-form returns TypeError: can’t define property “score”: Object is not extensible

I am using react-hook-form as a form controller.
it retruns error as
TypeError: can't define property "score": Object is not extensible,
TypeError: can't define property "comment": Object is not extensible
where i wrapped MUI TextField to react-hook-form Controller component.
But it returns TypeError only in react production build not on a local.


const MarkDialog = (props) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const params = useParams();
  const location = useLocation();
  const { control, handleSubmit, formState, reset } = useForm({
    mode: 'onSubmit',
    resolver: yupResolver(
      yup.object().shape({
        comment: yup.string(),
        score: yup
          .number()
          .required('Пожалуйста, заполните поле.')
          .min(0, 'Минимальная оценка 0.')
          .typeError('Введите число')
          .max(
            parseInt(location.state?.maxScore, 10),
            `Максималное значения оценки за этот вопрос: ${parseInt(location.state?.maxScore, 10)}`
          ),
      })
    ),
  });
  const queryClient = useQueryClient();

  const evaluateMutation = useMutation(evaluate, {
    onSuccess: () => {
      dispatch(
        showMessage({
          message: 'Успешно оценена!',
          autoHideDuration: 6000,
          anchorOrigin: {
            vertical: 'top',
            horizontal: 'right',
          },
          variant: 'success',
        })
      );
      queryClient.invalidateQueries('evaluate');
      closeDialogScreen();
    },
  });

  const reEvaluateMutation = useMutation(reEvaluate, {
    onSuccess: () => {
      dispatch(
        showMessage({
          message: 'Оценка успешно изменена!',
          autoHideDuration: 6000,
          anchorOrigin: {
            vertical: 'top',
            horizontal: 'right',
          },
          variant: 'success',
        })
      );
      queryClient.invalidateQueries('reEvaluate');
      closeDialogScreen();
    },
  });

  function onSubmit(data) {
    const submissionData = {
      comment: data?.comment,
      score: data?.score,
      organizationId: props.params.orgId,
      blockNumber: props.location.state.blockNumber,
    };
    if (isNull(props?.location?.state?.score)) {
      evaluateMutation.mutateAsync(submissionData);
    } else {
      reEvaluateMutation.mutateAsync({
        ...submissionData,
        evaluationId: props?.location?.state?.evaluationId,
      });
    }
  }

  const closeDialogScreen = () => {
    reset({});
    dispatch(closeDialog());
    navigate(`/marking/orgs/${params.orgId}`, { state: location.state });
  };

  return (
    <Button
      sx={userSX.LoadingButtonView}
      startIcon={<DoneAll sx={{ color: 'white' }} />}
      onClick={() =>
        dispatch(
          openDialog({
            children: (
              <>
                <DialogTitle id="alert-dialog-title" className="text-center">
                  Пожалуйста, оцените этот вопрос
                </DialogTitle>
                <form onSubmit={handleSubmit(onSubmit)}>
                  <DialogContent>
                    <DialogContentText id="alert-dialog-description" className="text-center">
                      Максимальное количество баллов за этот вопрос:{' '}
                      {props?.location?.state?.maxScore} баллов
                    </DialogContentText>
                    <div className="mt-6">
                      <Typography>Балл:</Typography>
                      <Controller
                        control={control}
                        name="score"
                        render={({ field, fieldState }) => (
                          <TextField
                            placeholder="Количество баллов"
                            fullWidth
                            onChange={field.onChange}
                            inputRef={field.ref}
                            // {...field}
                            error={!!fieldState?.error}
                            helperText={fieldState?.error?.message}
                          />
                        )}
                      />
                    </div>
                    <div>
                      <Typography>Комментария:</Typography>
                      <Controller
                        control={control}
                        name="comment"
                        render={({ field, fieldState }) => (
                          <TextField
                            onChange={field.onChange}
                            placeholder="Дополнительные комментарии"
                            fullWidth
                            multiline
                            inputRef={field.ref}
                            // {...field}
                            error={!!fieldState?.error}
                            helperText={fieldState?.error?.message}
                          />
                        )}
                      />
                    </div>
                  </DialogContent>
                  <DialogActions>
                    <Button type="submit" color="primary">
                      Сохранить
                    </Button>
                    <Button onClick={closeDialogScreen} color="primary" autoFocus>
                      Назад
                    </Button>
                  </DialogActions>
                </form>
              </>
            ),
          })
        )
      }
    >
      {isNull(props?.location?.state?.score) ? 'Оценить' : 'Переоценить'}
    </Button>
  );
};

If i remove Controllers from MarkDialog component the error disappears. I tested data object for is it extensible which is from handleSubmit of react-hook-form and it appears to be extensible.

Will window.close work only work if the window shares a domain with the window trying to close it?

I’m trying to understand when window.close() will / won’t work. I know there are some requirements around the window being script closeable etc., but it seems like there are some additional requirements that I can’t find formally laid out (at least, not laid out in terms I can’t understand with my current javascript knowledge.)

At a high level, my use case is as follows:

  • a user clicks a button
  • I do some stuff and then do something like windowRef = window.open(“http://example.com/somedocument.pdf”,”popup”).
  • Once the user takes clicks a different button, I want to be able to call windowRef.close() and have it close the pdf I opened in a popup.

My current implementation works as long as the url I’m opening shares a domain with the window that’s trying to close it, and not otherwise. That’s fine (I can guarantee the PDF will come from the same domain as the window trying to close it) but I’d like to understand why this doesn’t work for URLs with different domains (and if there are other cases where it won’t work that I haven’t run into yet).

Based on some experimenting in my application / the browser console, it seems like window.close() will work if the url I’m opening shares a domain with the window I’m trying to close it from, but not otherwise. That’s purely based on testing / guessing though, I haven’t found documentation explaining why this might be the case.

I’ve read the MDN documentation for window.close, but I can’t seem to find it documented when exactly this function will work, and when it will just return “undefined” (but not log an error like “Scripts may not close windows that were not opened by script.)

I thought this might have to do with the Same-origin policy, but that article calls out window.close() as not having the same-origin requirement, and some tests I ran seem to confirm this.

Can someone explain to me what needs to be true for me to be confident that, if I’m opening a pdf in a popup window using window.open() to send a window to a URL to the pdf, I can later close that popup with window.close()

Dealing with a large amount of text data in JavaScript/VS code

I am working on a react native app that has a lot of text data and the plan is to make it work offline so its all going to be compiled in the app. Its a resource app so there are a few categories but basically it is 400 articles in 3 or 4 categories each (1200-1600 total), or at least for the higher volume ones. Currently about 30% through the first one and it is approaching 18,000 lines in an object. Would it be faster and more efficient to have each article in a json and bring it in by name compared to one object? I don’t think look up would be slow in the object because there are only 400 or so ids to look up but I am running into an issue with vscode getting really slow. The text is made outside the file and I copy it in but copying the ids for reference throughout the app is getting slow and it made me reconsider how I am storing the data. I am not seeing any performance issues on the app so far as it is loaded into a flatlist but I am curious if there is a better way to handle it in code.

I looked around online and saw more info on rendering it, which is not an issue and I think this is a bit more of a VSCode issue.