Parsley + recaptcha v3 promise

I’m not able to get the following code to work:

$(function() {
    function verifyRecaptcha() {
        return new Promise((resolve, reject) => {
            grecaptcha.execute('RECAPTCHA_SITE_KEY', {action: 'submit'}).then(function(token) {
                postJson('frontend/verify_recaptcha/'+token, null, function(d) {
                    if (d.pass) {
                        resolve('Verified');
                    } else {
                        reject('Not verified');
                    }
                });
            });
        });
    };

    var parsleyForm = $('#enquiry-form').parsley().on('form:submit', function(formInstance) {
        var validationResult = false;

        verifyRecaptcha().then(function() {
            console.log('VERIFIED');
            validationResult = true
        }).catch(function() {
            console.log('NOT VERIFIED');
            validationResult = false;
        });

        console.log('Resultat: '+validationResult);

        return validationResult;
    });
});

I already tried a lot with await/async, but it always submits the form.

I think I cannot be the only one who needs to implement Parsley with recaptcha v3? Any ideas? 🙂

How to set a stream for a specific user with mongodb streams

I am trying to set up a mongodb stream for a specific user but the thing is that you won’t be able to know what someone will give as a username, in this case the field is called: charactername.

For this project I am using: mongodb, express, nodejs and socket.io. The socket.io broadcasts it to the frontend and refreshed the page once there is a change in the database. But the thing is right now if something is changed in the collection “users” the refresh happens for every user instead of a specific user of whose document gets updated.

This is the code for the backend:

User.watch([{ $match: {
operationType: 
{$in: ['update']},
"updateDescription.updatedFields.charactername": ""   //What should I put here ?
}}]).
on('change', data => {
  console.log('Update action triggered');
  console.log(new Date(), data.updateDescription.updatedFields);
  console.log(data)
  io.emit("DBchange", data);
});

This is the code for the front end:

<script>

socket.on("DBchange", (data) => {
console.log(data)
location.reload()
});

</script>

How can I fix this issue?

How to connect a localhost server and an html wbepage all into a single website? [closed]

I have created a signup form in HTML where the data collected is stored in excel using Javascript and a couple of libraries like exceljs, prohairesis, express, morgan, body-parser, etc. This is done on localhost, so to start the program, I use ‘npm start’ in command prompt.

However in any normal website, the user needs to be able to navigate from the home page to the signup webpage. But because my home page is just an HTML file and my signup page is a localhost server, I am unable to link the two.

I’m looking for a way to probably achieve the same task of collecting the data from the HTML form into an excel workbook without using a localhost server or a port.

Or if there is any other way of linking the home page and the signup page I would love to try it out. Just to be clear, navigating to and fro is my objective.

Here is the javascript code that collects data:

//importing necessary libraries
const express = require("express");
const morgan = require("morgan");
const Prohairesis = require("prohairesis");
const bodyParser = require("body-parser");
const Excel = require("exceljs");
const fs = require("fs");

const app = express();
const port = process.env.PORT || 8081;

let info = [];

app
  .use(express.static("public"))
  .use(morgan("dev"))
  .use(bodyParser.urlencoded({ extended: false }))
  .use(bodyParser.json())

  .post("/api/user", async (req, res) => {
    res.json(req.body);

    //collecting user data into a javascript string
    const user = req.body;
    const ud = JSON.stringify(user);
    const user_data = JSON.parse(ud);
    console.log(user_data);
    const user_li = [
      user_data.first,
      user_data.email,
      user_data.stdid,
      user_data.pwd,
      user_data.cpwd,
    ];
    console.log(user_li);

    //some simple validation
    for (i in user_li) {
      if (user_data.pwd < 8)
      {
        res.json("**Password must contain at least 8 characters**")
      }
      if (user_data.pwd != user_data.cpwd) 
      {
        console.log("**Password does not match**");
        res.json("**Password does not match**");
        break;
      }
      if (user_data.pwd == user_data.cpwd) 
      {
        res.json("Thank you for signing up with us!");
        info.push(user_li);
        console.log(info);

        //append row to excel worksheet
        const workbook = new Excel.Workbook();
        // for safety
        try {
          // check if `Login-Db.xlsx` file exists
          if (fs.existsSync("Login-Db.xlsx")) {
            // load existing workbook
            workbook.xlsx.readFile("Login-Db.xlsx").then((workbook) => {
              // get worksheet
              const worksheet = workbook.getWorksheet("Main Db");
              // append rows to worksheet
              worksheet.addRows(info);
              // save workbook
              workbook.xlsx.writeFile("Login-Db.xlsx").then((err) => {
                if (!err) {
                  console.log("Row added to excel file");
                  return;
                }
                // if error, print it
                console.log(err);
              });
            });
          } else {
            // create new worksheet
            const worksheet = workbook.addWorksheet("Main Db");
            // add new rows to worksheet
            worksheet.addRows(info);
            // save workbook
            workbook.xlsx.writeFile("Login-Db.xlsx").then((err) => {
              if (!err) {
                console.log("Row added to excel file");
                return;
              }
              // if error, print it
              console.log(err);
            });
          }
        } catch (error) {
          console.log(error);
        }
        break;
      }
    }
  })

  .listen(port, () => console.log(`Server listening on port ${port}`));

I am a beginner in web development and I’m quite stuck at this point….Hoping for assistance

Thanks in advance 🙂

Does anyone know what Tom Scott does on his video

Anyone know how to make YOUTUBE automatically change the title of my video

I can do that but every time I do I need to redirect to OAuth

And it also only runs when I’m opening the website or my localhost

I want Everytime there is a new viewer, YOUTUBE AUTOMATICALLY CHANGES TITLE without me

VueJs proper way to keep template clean without sacrificing performance

Our team is facing a problem with too much logics in template file which causes colleagues hard to debug.

I am thinking a proper way to increase the readability of the template file without losing performance.

Our team often include inline bitwise logic for dynamic class, style, etc. to fulfill the business logic under component template.


[Inline bitwise example]

<template> <!--Inline bitwise way-->
  <div class="listContainer">
    <div :class="`listItem ${_item.type == '1' ? 'itemTypeOne' : ''} ${_item.type == '2' ? 'itemTypeTwo' : ''}`" v-for="_item in list" :key="_item.key">
      <div class="itemBg" :style="{top: _item.type == '1' ? '10px' : '20px'}"></div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      list: [{key: "1", type: "1", value: "Value 1"}, { key: "2", type: "2", value: "Value 2"}],
    };
  },
  methods: {},
  computed: {},
}
</script>

To reduce these kind of logic code, I thought of using computed approach but I think it would cause computation overhead (Just in my opinion, feel free to correct me if I was wrong:)). It is because we cannot avoid using parameters with computed which lose the advantage of cache handled by vue itself. By using computed property with parameter approach, the parametrize anonymous function inside computed is keep being called which would potentially cause lower performance.


[Parametrized computed example]

<template>
  <div class="listContainer">
    <div :class="`listItem ${getItemClass(_item.type)}`" v-for="_item in list" :key="_item.key">
      <div class="itemBg" :style="getItemBgStyle(_item.type)"></div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      list: [{key: "1", type: "1", value: "Value 1"}, { key: "2", type: "2", value: "Value 2"}],
    };
  },
  methods: {},
  computed: {
    getItemClass: function(){
      return function($itemType){
        console.log("getItemClass called"); /* Keep being called even _item.key didnt changed */
        if($itemType == '1'){
          return 'itemTypeOne'
        }
        if($itemType == '2'){
          return 'itemTypeTwo'
        }
      }
    },
    getItemBgStyle: function(){
      return function($itemType){
        console.log("getItemClass called"); /* Same as getItemClass */
        return {
          top: $itemType == '1' ? '10px' : '20px'
        }
      }
    }
  },
}
</script>

Same with parametrized computed approach, parametrized method approach also cause this drawback. To keep this question in short, I’m not showing method approach here since it basically same with the computed approach. Here is the reference post that I studied: Can I pass parameters in computed properties in Vue.Js

My question is, is there a proper way to meet my aim (to keep template shorts without losing performance)?

Additionally, could anyone share with us the performance comparison between [Inline bitwise approach] vs [Parametrized computed approach] vs [Parametrized method approach].

AES-GCM Secret/Symmetric Key Validation with Encrypted Buffer Comparison of SubtleCrypto and SJCL

Our application has a group chat feature which involves end-to-end encryption of group chat messages.

The group is hosted at server.

All the encryption and decryption is handled on the clientside.

It also utilizes the same mechanism of encryption for the real-time messages.

The group chat works by foremost someone creating this group at serverside, when a client is instating its creation they generate a new key [clientside], and validate it on their end [successful encryption and decryption of a same static text from SubtleCrypto], and then successfully hosts it by sending the encrypted buffer to server where groups are managed, storing it, and then others can join if they know the secret key. We use the same AES-GCM Symmetric Key / Secret Key that is generated for this purpose. The server-side doesn’t have the key stored anywhere.

Now, to validate whether the key a client trying to join this group is valid or not before joining is, with the key that was shared to them [by other means, such as email etc], at client-side, encrypt the SAME static text, and send its buffer. Then the buffer value stored at the server-side on creation time is compared to this new client joining with the buffer of the newly encrypted static text they performed on client-side, and if the buffer is equal on server-side, they are authorized into this group.

Now with reference to my previous question(s), I’m attempting to replace Web API SubtleCrypto to SJCL, and the newly generated SJCL encrypted buffer is always smaller than the SubtleCrypto. While encrypting and decrypting between each other is already established, the problem at hand is that their buffers don’t match, even though they’re both using the same key, IV, and AES-GCM mode. And they both have to simultaneously work for backwards compatibility of different client versions.

Here is an example:

const buf2hex = (buffer) =>
{
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}

const string2hex = (input) =>
{
    let hex;
    let result = "";
    let i = 0;
    for (i = 0; i < input.length; i++)
    {
        hex = input.charCodeAt(i).toString(16);
        result += ("000" + hex).slice(-4);
    }
    return result
}

const hex2bytes = (string) =>
{
    const normal = string.length % 2 ? "0" + string : string; // Make even length
    const bytes = new Uint8Array(normal.length / 2);
    for (let index = 0; index < bytes.length; ++index)
    {
        const c1 = normal.charCodeAt(index * 2);
        const c2 = normal.charCodeAt(index * 2 + 1);
        const n1 = c1 - (c1 < 58 ? 48 : 87);
        const n2 = c2 - (c2 < 58 ? 48 : 87);
        bytes[index] = n1 * 16 + n2;
    }
    return bytes;
}

//JWK K Value
const generateKey = async () =>
{
    const key = await window.crypto.subtle.generateKey(
    {
        name: "AES-GCM",
        length: 128
    }, true, ["encrypt", "decrypt"]);
    const key_exported = await window.crypto.subtle.exportKey("jwk", key);
    return key_exported.k;
}

//CryptoKey generated from SubtleCrypto:
const generateSubtleCryptoKey = async (kvalue) =>
{
    return window.crypto.subtle.importKey(
        "jwk",
        {
            k: kvalue,
            alg: "A128GCM",
            ext: true,
            key_ops: ["encrypt", "decrypt"],
            kty: "oct",
        },
        {
            name: "AES-GCM",
            length: 128
        },
        false,
        ["encrypt", "decrypt"]
    );
}

//Cipher generated from SJCL:
const generateCipherSJCL = (kkey) =>
{
    const ekkeyB64 = kkey.replace(/-/g, '+').replace(/_/g, '/');    // Base64url -> Base64 (ignore optional padding)
    const ebkey = sjcl.codec.base64.toBits(ekkeyB64);               // conert to bitArray
    const ecipher = new sjcl.cipher.aes(ebkey);
    return ecipher;
}

const encryptText = "STATIC TEXT";

const compareBuffers = async () =>
{
    const kkey = await generateKey();
    const cryptokey = await generateSubtleCryptoKey(kkey)
    const ecipher = generateCipherSJCL(kkey);

    const subtleCrypto = await window.crypto.subtle.encrypt(
    {
        name: "AES-GCM",
        iv: new Uint8Array(12)
    }, cryptokey, new TextEncoder().encode(JSON.stringify(encryptText)));

    const encryptionIv = sjcl.codec.hex.toBits(buf2hex(new Uint8Array(12).buffer));
    const encryptedMessageFormat = sjcl.codec.hex.toBits(string2hex(JSON.stringify(encryptText)));
    const sjclEncrypted = sjcl.mode.gcm.encrypt(ecipher, encryptedMessageFormat, encryptionIv);

    const originalEncryptedSJCL = Buffer.from(sjclEncrypted);
    console.log({subtleCrypto});
    console.log({originalEncryptedSJCL});
    const e1 = Buffer.from(new Uint8Array(sjclEncrypted));
    const e2 = Buffer.from(new Uint8Array(subtleCrypto));
    console.log({e1, e2});                                  //{e1: Uint8Array(11), e2: Uint8Array(29)}
    console.log(Buffer.compare(e1, e2));                    //should be 0, equal buffer.
}

compareBuffers();

I suppose I should preface this by stating that I have very limited cryptography knowledge, but why would the buffers differ when they’re both encrypted and decrypted across both libraries when the mechanism is same?

background color not displayed after building the react app

I have a react app using material ui, created drawer in it and there is a problem with its background color(color is not displayed), and burger menu toogle(when drawer is opened, burger menu button is lost), after I do npm run build and then start it with serve -s build
here are my deps:

"@emotion/react": "^11.4.1",
        "@fortawesome/fontawesome-free": "^5.15.4",
        "@fortawesome/fontawesome-svg-core": "^1.2.36",
        "@material-ui/core": "^4.12.3",
        "@material-ui/icons": "^4.11.2",
        "react": "^17.0.2",
        "react-dom": "^17.0.2",
        "react-icons": "^4.2.0",
        "react-redux": "^7.2.5",
        "react-router": "^6.0.0-beta.8",
        "react-router-dom": "^6.0.0-beta.8",
        "react-scripts": "4.0.3",
        "web-vitals": "^1.1.2"

drawer code:

 const isMobile=useMediaQuery(theme.breakpoints.down(885))
const classes = useStyles();
const drawerContentClass = isMobile===true?
classes.content:clsx(classes.content, { [classes.contentShift]: open})


<div className={classes.root}>
            <CssBaseline />
            <AppBar
              position="fixed"
              className={clsx(classes.appBar, {
                [classes.appBarShift]: open,
              })}
            >
              <Toolbar style={{background:'#00314D'}}>
                  <IconButton
                    color="inherit"
                    aria-label="open drawer"
                    onClick={()=>clickFn(!open)}
                    edge="start"
                  >
                    <MenuIcon />
                  </IconButton>
              </Toolbar>
            </AppBar>
            <Drawer
              className={classes.drawer}
              variant="persistent"
              transitionDuration={{
                enter: theme.transitions.duration.leavingScreen,
                exit: theme.transitions.duration.leavingScreen
              }}
              classes={{
                paper: classes.drawerPaper
              }}
              PaperProps={{ elevation: 9 }}
              anchor="left"
              open={open}
              onClose={closeDrawer}
            >
                     //drawer content
              </Drawer>
            <main className={drawerContentClass} style={{backgroundColor:'rgb(0, 49, 77)'}}> //tried to hardcode here, but this not helped
                <div className={classes.drawerHeader} />
                
            </main>
        </div>

What document contentTypes does Chrome render as monospaced HTML?

Some Chrome URLs are just text files that are rendered as monospaced text files.
As an example, this is the Public Suffix List (https://publicsuffix.org/list/public_suffix_list.dat), and looks like this:

Public Suffix List

You can also get to this type of page by going to any raw GitHub user content, like https://raw.githubusercontent.com/github/docs/main/README.md.

This is the HTML wrapper I see for these type of monospaced text documents:

<html data-lt-installed="true">
  <head></head>
  <body>
    <pre style="word-wrap: break-word; white-space: pre-wrap;">
    "Lots of text!"
    </pre>
  </body>
</html>

Some contentType values predictably get rendered in this HTML. image/png does not get rendered this way, but text/css and text/js do. Additionally, application/json also gets rendered in this way, like https://ip-ranges.amazonaws.com/ip-ranges.json.

Question

For which document.contentType values does Chrome render this monospaced text content with this HTML wrapper?

Show preloader gif only when input fields are filled?

I have a site built via flask that takes the information provided by the user and performs some action . I also have a loader that shows up when this action is done in the background, the trouble is , if the user were to click on the button “process” without filling the details , the loader is still shown .

How do i make the loader appear only when all the input fields are entered by the user and then clicks on “process” button

   <form action="/result" method="post">
    <tbody>
 <tr>
        <td><input type='text' name="ip" id='ipadd' required="required" placeholder="8.8.8.8" pattern="((^|.)((25[0-5])|(2[0-4]d)|(1dd)|([1-9]?d))){4}$" value style="margin-bottom: 5px;" autocomplete="off"></td>

       </tr>
    </tbody>

  </table>

  <button  class="btn btn-outline btn-success"  style="padding-right: 15pt;"onclick="loading();">Process</button>
   </form>


  <script type="text/javascript">// <![CDATA[
        function loading(){
            $("#loading").show();
            $("#content").hide();
        }
// ]]></script>

Why react map function is not working properly?

when I use the map in react, do I get an unexpected token error?

import React, { useState, useEffect } from "react";
import axios from "axios";

export default function ApiHook() {
  const [employees, setEmployees] = useState([]);

  useEffect(() => {
    axios
      .get("http://dummy.restapiexample.com/api/v1/employees")
      .then((response) => {
        console.log(response);
        setEmployees(response.data);
      })
      .catch((e) => console.log(e));
  }, []);
  return (
      {employees.map((employee) => {
        return <p>{employee.employee_name}</p>;
      })}
  );
}

Why does express validator doesn’t run on desired routes?

i am trying to validate request body and path params in post and delete routes respectively

this is my body validation rules :-

const { body, validationResult } = require('express-validator');

const requestBodyValidationRules = [
  body('originalUrl')
    .not()
    .isEmpty()
    .withMessage({
      error: 'Invalid Request Body',
      detail: {
        originalUrl: 'Request Syntax Error! originalUrl parameter is required',
      },
    }),
  body('originalUrl')
    .isURL({
      protocols: ['http', 'https', 'ftp'],
      require_protocol: true,
    })
    .withMessage({
      error: 'Invalid Request Body',
      detail: {
        originalUrl: 'Invalid URL format, please try again!',
      },
    }),
  body('convertedUrlId')
    .optional({ checkFalsy: true })
    .matches(/^[~A-Za-z0-9/./_/-]*$/)
    .withMessage({
      error: 'Invalid characters',
      detail: {
        convertedUrlId:
          'Invalid characters! Only [A-Z],[a-z],[0-9], _ , - , . , ~ are allowed',
      },
    }),
  body('convertedUrlId')
    .optional({ checkFalsy: true })
    .isLength({ min: 5, max: 6 })
    .withMessage({
      error: 'Invalid length',
      detail: {
        convertedUrlId:
          'Invalid Length! Character length >=5 and <7 characters are allowed',
      },
    }),
  (req, res, next) => {
    const errors = validationResult(req);
    console.log('errors', errors);
    if (!errors.isEmpty()) {
      const errorMsg = errors.array()[0].msg;
      return res.status(400).json(errorMsg);
    }
    next();
  },
];
module.exports = requestBodyValidationRules;

this is my param validation rules

const { param, validationResult } = require('express-validator');

const requestParamValidationRules = [
  param('convertedUrlId')
    .isLength({ min: 5, max: 6 })
    .withMessage({
      error: 'Invalid length',
      detail: {
        convertedUrlId:
          'Invalid Length! Character length >=5 and <7 characters are allowed',
      },
    }),
  param('convertedUrlId')
    .matches(/^[~A-Za-z0-9/./_/-]*$/)
    .withMessage({
      error: 'Invalid characters',
      detail: {
        convertedUrlId:
          'Invalid characters! Only [A-Z],[a-z],[0-9], _ , - , . , ~ are allowed',
      },
    }),
  (req, res, next) => {
    const errors = validationResult(req);
    console.log('errors', errors);
    if (!errors.isEmpty()) {
      const errorMsg = errors.array()[0].msg;
      return res.status(400).json(errorMsg);
    }
    next();
  },
];

module.exports = requestParamValidationRules;

this my app.js

app.get(
  '/api-docs',
  swaggerUI.serve,
  swaggerUI.setup(swaggerJsDocs, swaggerOptions)
);
app.get('/:shortUrl', redirectUrlRouter);
app.post(
  '/users/anon-user/urls',
  checkRequestBodyParams,
  fetchTimeStamp,
  convertAnonUrlRouter
);
app.post(
  '/users/auth-user/urls',
  checkRequestBodyParams,
  fetchTimeStamp,
  convertAuthUrlRouter
);
app.get('/users/auth-user/urls', fetchAuthUserHistoryRouter);
app.patch('/users/auth-user/urls', fetchTimeStamp, editConvertedUrlRouter);
app.delete(
  '/users/auth-user/urls/:convertedUrlId',
  checkPathParams,
  deleteConvertedUrlRouter
);

app.use((req, res) => {
  res.status(404).json({ error: 'route not found' });
});

when ever i am trying to post, delete validations are running, why is that so?

Desired behaviour :- for post, request body validations should be running