Are cookies safe to store OTP [closed]

I am using NodeJS as backend for user authentication. Everytime a user registers , they have to confirm their email with an otp, I am sending otp to email using nodemailer , also i am storing this otp in the cookies so that i can take it to verify with the otp entered by the user. Even though i am storing the otp after hashing, still i dont feel safe. Please tell me how do i do this?

I tried of using sending confirmation link to the user. That way works , but i also wanted to know OTP approach

Having AND and OR in same condition, without parentheses [closed]

if((CaseType_c != null && CaseType_c != “INQUIRY” && CaseSubType_c !=”SAMA_COMPLAINT”) || CaseType1_c != null && CaseType1_c != “INQUIRY” && CaseSubtype1_c !=”SAMA Complaint” && PrimaryContactPartyId != null && LanguagePreference_c != null && CaseType1_c != “COMPLIANCE_SANCTIONED” && CaseType1_c != “COMPLIANCE_EDD”)

Above mention if condition works fine but not appropriate

Golang router endpoint not being hit

I have the following route mux.HandleFunc("POST /addtask", addTask) and the addTask function looks like this:

func addTask(w http.ResponseWriter, r *http.Request) {
    addTask := TaskAdd{}
    err := json.NewDecoder(r.Body).Decode(&addTask)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    newTask := TaskDetails{Id: strconv.Itoa(len(details) - 1), Name: addTask.Task}
    details = append(details, newTask)

    log.Println(details)

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    err = json.NewEncoder(w).Encode(newTask)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}

I’m trying to send data to the endpoint using the fetch API from a javascript function

            console.log(payload);
            console.log(JSON.stringify(payload))

            fetch('/addtask', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload)
            })
                .then(response => response.json())
                .then(data => console.log(data))
                .catch(error => console.log(error))
        }

But I’m getting 404 errors in the browser developer tools. The two console.log methods at the top of the code snippet does output the correct data. GET requests route correctly it is only and issue with POST requests.

I double and triple checked the code and cannot find an issue with the code. I changed the HTML code so that the form is submitted on a button click

            <form action="/addtask" method="post">
                <div class="input-group mb-3 mt-auto">
                    <span class="input-group-text" id="basic-addon1"><i class="fa-solid fa-circle-plus"></i></span>
                    <input type="text" name="add-task" id="add-task" class="form-control"
                           placeholder="Add Task" style="border-color: red; margin-bottom: 20px">
                    <button type="submit" class="btn btn-outline-primary">Add</button>
                </div>
            </form>

But that had the same results.

What am I missing here? Any help will be appreciated, thanks.

What wrong whit this { “message”: “Terjadi kesalahan server”, “error”: “Cannot read properties of undefined (reading ’email’)” }?

when i do testing in postman i get terror like that
enter image description here

this is the configuration that i have, i have tested it in postman as i have attached the picture above but it causes error and i don’t know what causes the error. please help me to fix it because i am very confused to fix it
enter image description here

My simple reset password firebase cloud function is only returning internal error?

I am writing a cloud function to reset password but I am getting internal error, I am unable to figure out why.

[firebase_functions/internal] internal

Here is the code that is calling the function

  Future<bool> forgotPassword(String email) async {
    try {
      final HttpsCallable callable =
      FirebaseFunctions.instance.httpsCallable('resetPasswordTesting');
      final response = await callable.call({'email': email});
      if (response.data['success']) {
        SnackbarHelper.success(message: "Reset mail sent");
      }
      return true;
    } catch (e) {
      SnackbarHelper.success(message: "Error - $e");
      print(e);
      return false;
    }
  }

and this is the code for the function, which generates a temporary password and updates the user profile. I have removed the code for password email part for testing.

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.resetPasswordTesting = functions.https.onCall(async (data, context) => {
  const email = data.email;

  if (!email) {
    throw new functions.https.HttpsError("invalid-argument", "Email is required");
  }
  
  function generatePassword() {
    const characters = "ABCDEFGHJKLMNPQRSTUVWXYZ";
    const numbers = "23456789";
    let password = '';
    for (let i = 0; i < 3; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length);
        password += characters[randomIndex];
    }
    for (let i = 0; i < 5; i++) {
        const randomIndex = Math.floor(Math.random() * numbers.length);
        password += numbers[randomIndex];
    }
    return password; 
  }

  try {
    const tempPassword = generatePassword();

    const user = await admin.auth().getUserByEmail(email);

    await admin.auth().updateUser(user.uid, { password: randomPassword });

    const updateData = {
      Is_Password_Temporary: true,
      Temporary_Password: tempPassword,
    };

    await admin.firestore().collection('User_Info').doc(user.uid).set(updateData, { merge: true });

    return { success: true, message: "Password reset successfully" };
  } catch (error) {
    console.error("Error resetting password:", error);
    throw new functions.https.HttpsError("unknown", error.message || "Failed to reset password");
  }
});

The internal error is not verbose and every other user online seem to encounter this error in different scenarios so I can’t figure out what exactly is the issue. Any help is greatly appreciated, if you need any other information to solve this do tell.

how Menu should be imported correctly in `preload`?

Under the preload/index.ts directory:

I imported {Menu} from “electron”; however, when I printed Menu, it turned out to be undefined.

import { Menu, ipcRenderer } from 'electron';

console.log('imported status: ', Menu, ipcRenderer)  // the Menu: undefined, the ipcRenderer has value

Could you please tell me how it should be imported correctly?

my electron version: "electron": "^31.0.2",

FreeCodeCamp JavaScript Calculator

I have passed all the tests except test 12: I should be able to perform any operation (+, -, *, /) on numbers containing decimal points.

The expression “10.5 + 5.5” should produce an output of “16” : expected ‘110.5’ to equal ’16’
AssertionError: The expression “10.5 + 5.5” should produce an output of “16” : expected ‘110.5’ to equal ’16’

Here is my code :

function App() {
  const [output, setOutput] = useState('0');
  const [input, setInput] = useState('0');
  const [prevValue, setPrevValue] = useState('');
  const [operator, setOperator] = useState('');
  const clear = () => {
    setOutput('0');
    setInput('0');
    setOperator('');
    setPrevValue('');
  };

  const handllOperation = (op) => {
    const lastChar = output.slice(-1);
    const secondLastChar = output.slice(-2, -1);

    if (op === '-' && ['+', '-', 'x', '/'].includes(lastChar)) {
      if (lastChar === '-' && ['x', '/'].includes(secondLastChar)) {
        return;
      }
      setInput(op);
      setOutput((prev) => prev + op);
      return;
    }
    if (['+', '-', 'x', '/'].includes(lastChar)) {
      if (['+', '-', 'x', '/'].includes(secondLastChar)) {
        setOutput((prev) => prev.slice(0, -2) + op);
      } else {
        setOutput((prev) => prev.slice(0, -1) + op); 
      }
      setOperator(op);
      return;
    }

    if (prevValue === '') {
      setPrevValue(input);
    } else if (input !== '-') {
      const result = calculate(prevValue + operator + input);
      setPrevValue(result.toString());
    }
  
    setOperator(op);
    setInput(op);
    setOutput((prev) => prev + op);
  };
  const handleInput = (value) => {
  const lastChar = output.slice(-1);

  if (['+', '-', 'x', '/'].includes(value)) {
    handllOperation(value);
  } else if (value === '-' && ['+', '-', 'x', '/'].includes(lastChar)) {
    setInput(value);
    setOutput((prev) => prev + value);
  } else {
    const newInput = input === "0" || ['+', 'x', '-', '/'].includes(input) ? value : input + value;
    setInput(newInput);
    setOutput((prev) => (prev === "0" ? value : prev + value));
  }
};

  const calculate = (expression) => {
    const operators = {
      '+': (a, b) => a + b,
      '-': (a, b) => a - b,
      'x': (a, b) => a * b,
      '/': (a, b) => a / b,
    };

    const tokens = expression.match(/(?<!d)-?d+(.d+)?|[+x/-]/g); 
    if (!tokens) return 0;

    const nums = [];
    const ops = [];

    for (let token of tokens) {
      if (!isNaN(token)) {
        nums.push(parseFloat(token));
      } else if (token in operators) {
        while (ops.length && precedence(token, ops[ops.length - 1])) {
          process(nums, ops, operators); 
        }
        ops.push(token);
      }
    }

    while (ops.length) {
      process(nums, ops, operators);
    }

    return nums[0];
  };

  const precedence = (curr, prev) => {
    const precedenceOrder = { '+': 1, '-': 1, 'x': 2, '/': 2 };
    return precedenceOrder[prev] >= precedenceOrder[curr];
  };

  const process = (nums, ops, operators) => {
    const b = nums.pop();
    const a = nums.pop();
    const op = ops.pop();
    nums.push(operators[op](a, b));
  };

  const handleEqual = () => {
    if (operator && prevValue && input) {
      const result = calculate(output);  
      setOutput(result.toString());
      setInput(result.toString());
      setPrevValue('');
      setOperator('');
    }
  };

  const handleDecimal = () => {
    if (!input.includes(".")) {
      setInput((prev) => prev + ".");
      setOutput((prev) => prev + ".");
    }
  };

  return (
    <div className='h-screen flex justify-center items-center'>
      <div className='h-[650px] w-[400px] bg-[#1c1c1c] rounded-md flex flex-col p-2'>
        <div id='display' className='flex flex-col text-end'>
          <div id='output' className='text-white text-5xl h-20'>{output}</div>
          <input type="text" className='bg-transparent h-20 text-white text-5xl text-end' id='input' value={input} onChange={(e) => setInput(e.target.value)} />
        </div>
        <div className='w-full grid grid-cols-5 content-start'>
          <div className='grid grid-rows-4 col-span-4 gap-2'>
            <div className='grid grid-cols-3 self-end flex-row w-full'>
              <button id='clear' onClick={clear} className='rounded-full bg-[#D4D4D2] w-[275px] h-20 text-white col-span-3 text-2xl font-sans'>AC</button>
            </div>
            <div className='grid grid-cols-3 row-span-3 gap-2'>
              <button id='seven' className='rounded-full bg-[#505050] w-20 h-20 text-white text-2xl font-sans' onClick={() => handleInput("7")}>7</button>
              <button id='eight' className='rounded-full bg-[#505050] w-20 h-20 text-white text-2xl font-sans' onClick={() => handleInput("8")}>8</button>
              <button id='nine' className='rounded-full bg-[#505050] w-20 h-20 text-white text-2xl font-sans' onClick={() => handleInput("9")}>9</button>
              <button id='four' className='rounded-full bg-[#505050] w-20 h-20 text-white text-2xl font-sans' onClick={() => handleInput("4")}>4</button>
              <button id='five' className='rounded-full bg-[#505050] w-20 h-20 text-white text-2xl font-sans' onClick={() => handleInput("5")}>5</button>
              <button id='six' className='rounded-full bg-[#505050] w-20 h-20 text-white text-2xl font-sans' onClick={() => handleInput("6")}>6</button>
              <button id='one' className='rounded-full bg-[#505050] w-20 h-20 text-white text-2xl font-sans' onClick={() => handleInput("1")}>1</button>
              <button id='two' className='rounded-full bg-[#505050] w-20 h-20 text-white text-2xl font-sans' onClick={() => handleInput("2")}>2</button>
              <button id='three' className='rounded-full bg-[#505050] w-20 h-20 text-white text-2xl font-sans' onClick={() => handleInput("3")}>3</button>
              <button id='zero' className='col-span-2 rounded-full bg-[#505050] w-[200px] h-20 text-white text-2xl font-sans' onClick={() => handleInput("0")}>0</button>
              <button id='decimal' className='rounded-full bg-[#505050] w-20 h-20 text-white text-2xl font-sans' onClick={handleDecimal}>.</button>
            </div>
          </div>
          <div className='flex flex-col-reverse gap-2'>
            <button id='equals' className='rounded-full bg-[#FF9500] w-20 h-20 text-white text-2xl font-sans' onClick={handleEqual}>=</button>
            <button id='add' className='rounded-full bg-[#FF9500] w-20 h-20 text-white text-2xl font-sans' onClick={() => handllOperation("+")}>+</button>
            <button id='subtract' className='rounded-full bg-[#FF9500] w-20 h-20 text-white text-2xl font-sans' onClick={() => handllOperation("-")}>-</button>
            <button id='multiply' className='rounded-full bg-[#FF9500] w-20 h-20 text-white text-2xl font-sans' onClick={() => handllOperation("x")}>x</button>
            <button id='divide' className='rounded-full bg-[#FF9500] col-span-2 w-20 h-20 text-white text-2xl font-sans' onClick={() => handllOperation("/")}>/</button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;

any suggestions?

How to use fast-xml-parser’s arrayMode to parse only one element into JSON Array instead to JSON object

I have the played around with following XML-snippet(contents might not be correct but to highlight my question):

My problem is that if I only have one entry (as in layoutsX) the value inside this tag gets parsed as JSON object rather than JSON Array however when there are more than one values it gets parsed as Array.

<keyboard group="126" id="-11687" name="Untitled" maxout="3">
  <layouts>
    <layout first="0" last="17" mapSet="ANSI" modifiers="Modifiers"/>
    <layout first="10" last="17" mapSet="ANSI" modifiers="Modifiers"/>
  </layouts>
  <layoutsX>
    <layoutX first="10" last="17" mapSet="ANSI" modifiers="Modifiers"/>
  </layoutsX>
</keyboard>

I have looked into this: https://stackoverflow.com/questions/67193928/parsing-a-particular-tag-as-array-using-fast-xml-parser-in-nodejs it says you could use the option arrayMode

Unfortunately this does not work for me.
I use the below code but it still gives me an object for 1 element (layoutsX) and an array of objects for several elements (layouts)

How would I get an array of object no matter if I have 1 or several elements?

  const options = {
    ignoreAttributes: false,
    attributeNamePrefix: '@_',    // to access the attribute
    arrayMode: true
  };

 const xmlFile = readFileSync(filename, 'utf8');
 const parser = new XMLParser(options);
 const jsonObj = parser.parse(xmlFile); // get plain Object

 const oneEle:any[] = jsonObj.keyboard.layoutsX
 const twoEle:any[] = jsonObj.keyboard.layouts

 console.log("oneEle",typeof(oneEle),oneEle, oneEle[0],oneEle.length)
 console.log("twoEle",typeof(twoEle),twoEle,twoEle[0], twoEle.length)

Identify Dynamic Requests made by javascript for Purpose of Web Scraping

I would like to do web scraping to this webpage, and the following is what I have done trying to find the dynamic URL that is behind the javascipt of that page.

  1. Open the page in Google Chrome.

  2. “Inspect” from the right click menu.

  3. Switch to the “Network” tab.

  4. Triger the javascript fetch by F5 key.

  5. Check the “Fetch/XHR” sub-tab, and find a “jobs” that has a “Response” (sub sub tab) that contains json of the jobpostings.

  6. Go to the “Headers” sub sub tab, and the “Request URL” is https://cheo.wd10.myworkdayjobs.com/wday/cxs/cheo/External_Site/jobs

  7. Open the above request url, resulting a response reads as

    {“errorCode”:”HTTP_500″,”errorCaseId”:”E46F9EM40PAYV2″,”httpStatus”:500,”locale”:”en-GB,en-US;qu003d0.9,en;qu003d0.8,zh-CN;qu003d0.7,zh;qu003d0.6″,”message”:””,”messageParams”:{}}

In the past, I have had some successes following the above steps find the dynamic urls for other webpages. For this page (and lots of other ones), I must be missing some thing. My questions are

  1. How are the steps for one to get the dynamic url for the purpose of web scraping the mentioned webpage?
  2. Are there any detailed tutorials on this topic?

By the way, I am using PHP and Simple_html_dom when I do web scraping.

How can I store and get large Excel file from mongodb in mernstack app

I am building webapp using mernstack where mine feature is to let user upload the excel file and then get that file When required by user and perform some process ,In process mine frontend is performing some calculation row by row like finding average,sum,max number,min number in every row and add that to there new columns.

But I am having problem with large files which contains large number of rows to store and process

Firstly I was converting excel file in json using xlsx library and was saving that json directly into database but the issue arises when mine excel sheet is large which may contain 1 lakhs (100000) row then I m getting bson (16 mb) size limit error.so now I am thinking of using gridfs and save file directly in mongodb and then get that file in frontend upon retrieval I will convert that file in json and perform mine process part but that also consume time in frontend because xlsx library take a time to convert 1 lakhs row in json so what will be the best approach to make this feature more optimised

google drive api erros

I’m having trouble integrating the Google Drive API with my app.
I need to back up my app data

I’m not able to integrate, I haven’t gotten any results yet.
I have an app that uses native firebase, my project is developed with expo but using native libraries

When modifying document in another window, why do changes appear then vanish when using the return value of window.open() but not window.opener?

I have a webpage which opens a new window in the same domain, then I want to have the first window modify DOM properties in the second window.

Using window.opener works correctly, but I am actually using Typescript and this way is not type-safe.

I’m trying to change it to instead use the return value of window.open. The changes I make to the second window appear for a fraction of a second then go away.

This is Javascript in the browser only, nothing server-side.

Working way, using window.opener

This works correctly but is unsafe in Typescript.

You do not need a web server for this; you can open it in a browser using a file:// URL.

first.html:

<!DOCTYPE html>
<html>
<head>
  <title>First window - using window.opener</title>
</head>
<body>
  <script>

    // This global function is called from the second window.
    function onSecondWindowReady(paragraphElement) {
      document.body.append(`Received a ${paragraphElement.constructor.name} from the second window.`);
      paragraphElement.style.background = "yellow";
      paragraphElement.innerText += " It should be yellow now."
    }

    document.addEventListener("DOMContentLoaded", () => {
      const secondWindow = window.open("second.html", "secondWindow");
      if (!secondWindow) {
        document.body.append("Second window didn't open, please check web browser popup blocker.");
      }
    });
  </script>
  <p>This is the first window.</p>
</body>
</html>

second.html:

<!DOCTYPE html>
<html>
<head>
  <title>Second window - using window.opener</title>
</head>
<body>
  <script>
    document.addEventListener("DOMContentLoaded", () => {
      window.opener.onSecondWindowReady(document.querySelector("p"));
    });
  </script>
  <p>This is the second window.</p>
</body>
</html>

Expected result:

  • In the first window, the text “Received a HTMLParagraphElement from the second window” is added to the page.

  • In the second window, the text says “This is the second window. It should be yellow now” with a yellow background.

Non-working way, using return value of window.open()

You must use a web server for this. If you open it in a browser using file:// you’ll get a cross-origin DOMException. The server just needs to serve static files, for example the Live Server extension for VS Code works.

first.html:

<!DOCTYPE html>
<html>

<head>
  <title>First window - using window.open() return value</title>
</head>
<body>
  <script>
    document.addEventListener("DOMContentLoaded", () => {
      const firstWindow = window;
      const secondWindow = window.open("second.html", "secondWindow");
      if (secondWindow) {

        function accessTheSecondWindow() {
          const paragraphElementInSecondWindow = secondWindow.document.querySelector("p");
          if (paragraphElementInSecondWindow) {
            firstWindow.document.body.append(`Found a <p> in the second window.`);
            paragraphElementInSecondWindow.style.background = "yellow";
            paragraphElementInSecondWindow.innerText += " It should be yellow now.";
          } else {
            // Sometimes happens due to dev server caching or live reload?
            firstWindow.document.body.append("Couldn't find a <p> element in the second window, please reload this page.");
          }
        }

        if (secondWindow.document.readyState === "complete") {
          firstWindow.document.body.append("The second window already finished loading. ");
          accessTheSecondWindow();
        } else {
          firstWindow.document.body.append("The second window is still loading, adding event listener. ");
          secondWindow.document.addEventListener("DOMContentLoaded", () => {
            firstWindow.document.body.append("DOMContentLoaded event fired in second window. ");
            accessTheSecondWindow();
          });
        }
      } else {
        document.body.append("Second window didn't open, please check web browser popup blocker.");
      }
    });
  </script>
  <p>This is the first window.</p>
</body>
</html>

second.html:

<!DOCTYPE html>
<html>
<head>
  <title>Second window - using window.open() return value</title>
</head>
<body>
  <p>This is the second window.</p>
</body>
</html>

Expected result: same as in the previous section.

Actual result:

  • In the first window, the text “Found a <p> in the second window.” is added to the page.
  • In the second window, the text “It should be yellow now” appears and the background is yellow for a short time, then the text and background color are removed.
  • Reloading first.html causes the text and color to reappear then vanish in the second window.
  • Tested in Firefox and Chrome on Windows, with extensions disabled.
  • 16-second screen recording: https://www.youtube.com/watch?v=pTT-JUEb_UI

Inaccessible File

I was trying to create a simple input and output terminal when my program was halted by two errors.

This one from the webpage.
Your file couldn’t be accessed
It may have been moved, edited or deleted.
ERR_FILE_NOT_FOUND

and this from VSCode

Could not read source map for chrome-error://chromewebdata/: Unexpected 503 response from chrome-error://chromewebdata/neterror.rollup.js.map: Unsupported protocol "chrome-error:"

Here is the code.

<html>
  <head>
    <title>Practice</title>
  </head>
  <body>
    <h1>Personal Logs</h1>
    <h1>The Arrangement</h1>
    <p>I am XXXX XXXXXXXX, a refugee of XXXXX as a member of the X.X. XXXXX force.<br>I vow to protect the xxxxxxxxxxxxx interests.</p>
    <form action="send-email.php" method="post">
       <input type="text" size="25" maxlength="40" placeholder="input" id="Input">
       <input type="image" src="amongus/amonus.webp" alt="amongus" width="72" height="72"  onclick="spitBack('Input');">
       Press Red Boi to enter
    </form>

    <script>
       function spitBack(fieldId){
        var spit = document.getElementById(fieldId).value;
        alert(spit + " is among us.");

       }

    </script>
  </body>

The core of the problem is that after i call the function i get the two errors in their respective applications and how to make it stop. My guess is that the program doesn’t have the right keyword(s) to tell it to return me back to the state of the webpage before i pressed the amongus image. I searched the web and they said it was some sort of google chrome browser version or extension compatibility issue.

I checked my only extension to see if it was the problem. It was not and my browser works fine when i remove the button and text box code.

Thanks for any help and i am a beginner if you think the code looks messy.

React Native expo 404 error for app url after expo export to deployment environment

I have broken my react native app into two components – CancerHomepageApp and ChemoHomepageApp. When I run the app locally I can access each app by going to http://localhost:8081/cancer and http://localhost:8081/chemo. However when I deploy my app to the google cloud, which uses firebase, I get a 404 error.

enter image description here

Here is my index.js file which has the App screens:

import { MainSideBarWeb } from './MainSideBarWeb.js';
import React from 'react';
import {Text, View} from 'react-native';
import { registerRootComponent } from 'expo';

const Stack = createNativeStackNavigator();

const App = () => {
    return (
        <NavigationContainer linking={{
            prefixes: ['http://localhost:8081', 'http://cancer-hacked.web.app'],
            config: {
                screens: {
                    CancerHomepageWeb: 'cancer',
                    ChemoHomepageWeb: 'chemo'
                }
            }
        }}>
            <Stack.Navigator initialRouteName="CancerHomepageWeb">
                <Stack.Screen
                    name="CancerHomepageWeb"
                    component={CancerHomepageWeb}
                    options={{ title: 'Cancer Homepage' }}
                />
                <Stack.Screen
                    name="ChemoHomepageWeb"
                    component={ChemoHomepageWeb}
                    options={{ title: 'Chemo Homepage' }}
                />
            </Stack.Navigator>
        </NavigationContainer>
        );
};
export default registerRootComponent(App);

Here is my deployment script:

npx expo export -p web
mv dist/index.html src/main/www/index.html
mv dist/metadata.json src/main/www/
mv dist/favicon.ico src/main/www/
rm -rf src/main/www/assets
mv dist/assets src/main/www/assets
rm -rf src/main/www/_expo
mv dist/_expo src/main/www/_expo
firebase deploy