Is there a lightweight JS library to validate a RS256-signed JWT token in a **Web browser**?

I have a Single-Page App and I’d like to validate the RS256 signature of JWT Access Tokens that an API returns to me.

I found tons of libraries for NodeJS but very little for Web browsers – and the few ones I found for Web browsers are quite heavy (hundreds of KB). I am surprised because I would have expected that there is already everything that is needed in terms of crypto code inside a web browser, since it does TLS, and so there would be built-in crypto functions available.

Any pointers to a lightweight JS library for RS256?

Javascript object returining undefinrd not as a error but as a warning

const loadUser = async () => {
   try {
       const response = await users.getUsersById();

       if (!response.ok) return console.log("Error");
       usersId = response.data
       var count = 0
       console.log(usersId)
       while (count != usersId.lenght - 1) {
           if (usersId[count].id == userId) {
               setUserFound(true)
               setUser(usersId[count].name)
               console.log(usersId[count].id)
           }
           count++
       }
   } catch (error) {
    console.log(error)
   }
};
    

And the error showing is as follows

undefined is not an object (evaluating ‘usersId[count].id’)

How to watch for partials change in devserver webpack5?

I am using webpack-dev-server with hot:true and use partials in templateParameters for HTML-webpack-plugin, HMR works fine when I change one of pages, but it doesn’t when I change one of partials. How can I make dev-server to watch for some files constantly in every HTML file? Like if I change header.html then it will refresh every page displayed. Or the better one solution would be if somehow I can add dependencies for my HTML files to watch. I tried to add WatchPartials class from here https://github.com/vuejs/vue-loader/issues/1929, but it doesn’t work.

My Partials, that will be added to templateParameters:

const PARTIALS = {}
fs.readdirSync(path.join(__dirname,'src','partials')).forEach((file) => {
    PARTIALS[file.replace(/.html/,'')] = fs.readFileSync(`./src/partials/${file}`,{encoding:'utf-8'})
}) 

My HtmlWebpackPlugin config:

plugins:[
    ...PAGES.map(page => new HtmlWebpackPlugin({
        template:`${PAGES_DIR}/${page}`,
        templateParameters:{
            PARTIALS
        },
        filename:`./${page}`,
        chunks:[page.replace(/.html/,'')],
        minify:{
            collapseWhitespace:isProd
        }
    })),

and devserver config:

devServer:{
    port:4200,
    compress:true,
    hot:true,
    watchFiles:['src/**/*.html'],
},

and I call partial in html like this:

<%= PARTIALS.header %>
    <div class="wrapper">
        <main class="main">
            <div class="wrapper"><h1>Webpacks</h1></div>
            <div class="logo"></div>
            <div class="card"><h2>SCSS</h2></div>
        </main>
<%= PARTIALS.footer %>

Is that possible to make dev-server to watch partials without usage of partials plugins like Handlebars?

Notifications: Angular updating the array variable but not refreshing the HTML view using websocket

I have done implemention of RXJS websocket RXJS Websockets for my angular application. It is used to show the notifications on the homepage which is route /home. So once the user logins in, he receives the notifications in a mat card and a count in a mat badge using angular material lib, until this everything is fine. Now if I route to another page say for example /games, I still receive my WS messages which is fine. But now if I revisit home page /home I don’t see the new WS message which I had received being at /games route, it shows the old count. This is problem one. The second problem is now if I try to send any new live message to my angular application it listens to it properly, also updates the variable which is notificationList in this case but doesn’t sync with HTML view.It shows the count which we had when we logged in.
Below is the snippet of my code:

Here is the HTML part which contains count and notification list:

    <button mat-button #menuTrigger="matMenuTrigger" [matMenuTriggerFor]="notifications"
    <mat-icon [matBadge]="counter" [matBadgeHidden]="counter < 1" matBadgeColor="warn">notifications</mat-icon>
</button>
<mat-menu #notifications="matMenu">
<ul>
    <li *ngFor="let item of notificationList; let i = index">
        
    </li>
</ul>
</mat-menu>

Here is the TS part which contains RXJS websocket code a short snippet of my code:

import { webSocket } from 'rxjs/webSocket';
public retryConfig = 3000;
public myWebSocket: WebSocketSubject<any>;
this.url = 'ws://localhost:8081';
fetchNotificationData() {
    this.myWebSocket = webSocket(this.url);
    this.myWebSocket.pipe(
      retry(this.retryConfig)).subscribe(
      (dataResponse: any) => {
        this.counter = this.dataResponse.length;
        this.notificationList = this.dataResponse;
      },
      // Called whenever there is a message from the server
      (err: any) => console.error("CONNECTION FAILED::", JSON.stringify(err)),

      // Called if WebSocket API signals some kind of error
      () => console.log('complete')
      // Called when connection is closed (for whatever reason)
    );
  }

Any help or advice will be appreciated. Thanks a ton.

assigning and object to react state conditionally?

I have the following code and I want to manipulate sate under certain condition how to add the targeted state to the state object ? I tried tow options none has worked

const trueArr = { a: true, b: true, c:true };
const falseArr ={ a: false, b: false, c: false };
    
    setSate({
      ...iniciSate,
     [foo == 'test'  ? trueArr : falseArr]
    });
    
    
    setSate({
      ...iniciSate,
     {foo == 'test' ? ...trueArr : ...falseArr}
    });

PHP , AJAX & JS E-Signature pad – Adding two text fields to signature pad

I have a signature pad built into my domain for capturing a proof of delivery signature when a parcel is delivered. I am using the script found here [https://www.freeonlinetest.in/tutorials/e-signature-with-php-and-ajax][1] Unfortunately there is no place to ask questions on that page
There are two basic files, index.php which holds the signature pad script layout and signature.php which uploads the signature in png format, There is also an asset folder and js folder accompanying these two files.. All works perfectly. What I am battling with is the addition of two text fields where the recipient can sign the pad as well as type their names (fname and last name) which when the signature is submitted it must also submit the typed names to the database.
I have tried every possible method I can think of and either the names are submitted and the signature not, or the signature stops working. I am putting this down to my very limited knowledge of javascript. I have added the fields within their own form but above the SUBMIT button in index.php which doe snot work,. I have tried posting the POST data to the web page refer page (e.g signature.php?fname={xyz}&lname={lname}) as posted variables and using GET in signature.php to obtain those values and then using them to insert with INSERT TO dba query to my database placed directly below the file_put_contents function but nothing works.. I cannot find any similar question / solution on many forums and google search. Can someone please help me…I would greatly appreciate it,

My files
Index.php

`<?php
if(!session_id()) session_start();


if( !isset($_SESSION['loggedin'] ) ) { header("Location: login.php"); die(); }
$order_no =$_GET['order_no'];

//echo"order=".$_GET['order_no'];

$order_no = $_SESSION['order_no']=$_GET['order_no'];


<!DOCTYPE html>
<html>
<head>

PHP Signature Pad Example

.kbw-signature { width: 400px; height: 200px;}
#signature canvas{
width: 100% !important;
height: auto;
}
.container{
margin-left: 10px;

}

border=”0″ cellspacing=”0″ cellpadding=”3″ style=”border: 1px solid #BBBBBB;”>PROOF oF DELIVERY sIGNATURE

E-Signature:

Clear Signature

Submit

var signature = $(‘#signature’).signature({syncField: ‘#sigpad’, syncFormat: ‘PNG’});
$(‘#clear’).click(function(e) {
e.preventDefault();
signature.signature(‘clear’);
$(“#sigpad”).val(”);
});

$(“#Submit”).click(function(){

//url = “http://192.168.1.147:8080/sign/signature.php”;
//url = “https://leisureafrica.co.za/delivery/admin/sign/signature.php”;
url = “http://localhost/leisure/delivery/admin/sign/signature.php”;
sigpad= $(“#sigpad”).val();
$(‘#res’).html(‘loading….’);
$.ajax({
type : ‘POST’,
url : url,
data : {signature_image: sigpad},
success: function(result){
$(‘#res’).html(‘Signature Uploaded successfully’);
// location.reload();

},
}) ;

});

setTimeout(“window.close();”, 6000);

window.onunload = refreshParent;
function refreshParent() {
window.opener.location.reload();
}

‘

#######signature.php

' if(!session_id()) session_start();
$order_no = $_SESSION['order_no']; 
//print_r($_POST);
$folderPath = "upload/";

$image_parts = explode(";base64,", $_POST['signature_image']);

$image_type_aux = explode("image/", $image_parts[0]);

$image_type = $image_type_aux[1];

$image_base64 = base64_decode($image_parts[1]);

$file = $folderPath . $order_no . '.'.$image_type;

file_put_contents($file, $image_base64);
$_SESSION['pod_added']=1;
echo "1";

?>
'

Please advise if I need to paost the jquery.signature.js file.
Many thanks in advance

checking if a function with no return executed properly

I have simple function that aims to log a user in via localstorage,
and then a second one that checks if the user can be found ( i need it separated because i need the logincheck elsewhere)

  logInUser(user: IPerson): Boolean {
    localStorage.setItem(this.userID, JSON.stringify(user));
    return this.isUserLoggedIn();
  }

 isUserLoggedIn(): Boolean {
    return Boolean(localStorage.getItem(this.userID));
  }

But this code seems bad to me because im not actually verifying that logInUser did its job, im just calling another function for this.
I was thinking about converting this into a Promise of boolean and chain .then() but this doesnt work with setItem()

technically, setting something to a storage does not return anything, so i dont know how to verify correctly that it did and catch errors.

How to prevent a website to scroll to a particular section when the section slider auto-slides on mobile-view?

I have 2 sliders, a story-list-carousel, and a story-view-carousel. When on mobile view, the screen starts auto-scrolling up to this section after the user passes this section and scrolls down towards the footer.

Video preview: https://www.youtube.com/watch?v=WYXcrMBQEHA

As in the video, the top slide listCarousel and the bottom section where 3 images are shown, is the storyMainCarousel.

Slider JS code:

let storyMainCarousel = new Splide('#story-view-carousel', {
    type: 'fade',
    pagination: false,
    arrows: false,
    cover: true,
    autoplay: true,
    rewind: true,
}).mount();

let listCarousel = new Splide('#story-list-carousel', {
    direction: 'ttb',
    width: '100%',
    height: '100%',
    perPage: 8,
    perMove: 1,
    autoplay: true,
    rewind: true,
    isNavigation: true,
    gap: 18,
    pagination: false,
    arrows: false,
    cover: true,
    start: 0,
    dragMinThreshold: {
        mouse: 4,
        touch: 10,
    },
    breakpoints: {
        767: {
            direction: 'ltr',
            height: '4rem',
            perPage: 2.4,
            perMove: 1,
            gap: 10,
            autoplay: true,
            rewind: true,
            padding: { left: '0rem', right: '0rem' },
            start: 0,
            focus: 'center',
        },
    },

}).mount();
storyMainCarousel.sync(listCarousel);

HTML and SCSS code:

How to connect SQL Server with JavaScript [closed]

I’ve been building a website and I have Database (SQL Server) which contains a lot of data that I would like to use in JavaScript. Well, my question is how to let the JavaScript to use all the information of the table. How to connect the table with JS? How can I work with table’s queries while using JavaScript? Also, can I get an array of the the data of each user?

Updating a prisma field using the “where” clause causes an error

I’m having this error when updating a field depending on the id of the model but I’m getting a Invalid prisma.resource.update() invocation: error.

This is my query:

const upvote = await prisma.resource.update({
  where: {
    id: body.resourceID,
  },
  data: {
    totalUpvotes: {
      increment: 1
    },
    userUpvoted: true,
  },
});

When I run the same query but use a string value instead of the body.resource variable,

const upvote = await prisma.resource.update({
  where: {
    id: "cl5njhgc90435e8sx2o6d",
  },
  data: {
    totalUpvotes: {
      increment: 1
    },
    userUpvoted: true,
  },
});

I’m getting the desired output. Can you tell me why this might be happening

I’m using NextJS, Prisma and PlanetScale for this application

Thanks in advance.

Why do I get the message “user does not exist” after successful registration?

I’m creating a simple login and registration page. When I enter all the fields in the registration page, it responds with a “user registered successfully” yet when I log in to that user I get “user does not exist”. Again, when I register with the same credentials, I get “user already exists”? What could be wrong here? Here’s my auth controller:

const bcrypt = require('bcrypt');
const User = require('../models/User');
const jwt = require("jsonwebtoken");
const config = require("config");

module.exports.register = (req, res) => {
    const { username, email, password } = req.body;
    const newUser = new User({ username: username, email: email, password: password });
    const saltRounds = 10;
    User.findOne({ email })
        .then(user => {
            if (password) {
                if (user) {
                    res.status(400).send("User already exists.", user);
                } else {
                    bcrypt.genSalt(saltRounds, function (err, salt) {
                        bcrypt.hash(password, salt, function (err, hash) {
                            if (err) throw err;
                            newUser.password = hash;
                            newUser.save()
                                .then(user => {
                                    jwt.sign(
                                        { id: user._id },
                                        config.get('jwtsecret'),
                                        { expiresIn: 3600 },
                                        (err, token) => {
                                            if (err) throw err;
                                            console.log({
                                                token,
                                                user: {
                                                    id: user._id,
                                                    username: user.username,
                                                    email: user.email
                                                }
                                            });
                                            res.send("User registered.")
                                        }
                                    )
                                })
                        });
                    });
                }
            }
        })
}

module.exports.login = async (req, res) => {
    const { email, password } = req.body;
    User.findOne({ email })
        .then(user => {
            if (!user) res.status(400).json({ msg: "User does not exist" });
            bcrypt.compare(password, user.password)
                .then(matched => {
                    if (!matched) res.status(400).json(({ msg: "Invalid credentials" }))
                    jwt.sign(
                        { id: user._id },
                        config.get('jwtsecret'),
                        { expiresIn: 3600 },
                        (err, token) => {
                            if (err) throw err;
                            res.send({
                                token,
                                user: {
                                    id: user._id,
                                    name: user.name,
                                    email: user.email
                                }
                            });
                        }
                    )
                })
        })
}

Here’s my login post request:

setUser({ email: form.email.value, password: form.password.value });
        axios.post("http://localhost:4000/login", user)
        .then(res => {
            console.log(res);
        })
        .catch(err => {
            console.log("An error occured: ", err.response);
        })

And my register post request:

axios.post("http://localhost:4000/register", user)
    .then(res => {
        console.log(res);
        setRegistered(true);
    })
    .catch(err => {
        console.log("An error occured: ", err.response.data);
    })

Also, when I click on the register button it doesn’t show anything. I have to click twice to get the response. Why does that happen?

js code only works on first button dosen’t work for the second button

I have a show more button to expand a div, but i won’t need it if the things in it don’t exceed it’s max height (550px), and i have a working code for that,

code

HTML

<div class="ccontainer" id="ccontainer">
  <p id="context"> content </p>
  <div class="img" id="cntimgcon" >
    <img src="imagesimage2.jpg" id="cntimgp1">
  </div>
  <p id="context"> content </p>
</div>
<Button class="showmore"> show more </button>

Js

// btn function
const buttons = document.getElementsByClassName("showmore");
Array.from(buttons).forEach(button => button.addEventListener("click", (e)=> {
  e.preventDefault();
  const collapse = button.previousElementSibling;
  collapse.style.maxHeight = collapse.style.maxHeight == 'none' ? '550px' : 'none';
}));



// showmore btn show/hide
const btn = document.querySelector('.showmore');
const height = document.querySelector('#ccontainer').clientHeight;
if (height <= 530) {
  btn.style.display = 'none'; // hide
} else {
  btn.style.display = ''; // unhide
}

but i have more than one div, so this code (which hides/show the button) only hides the first button for the first div, this code doesn’t work for the second button for the second div, is there a way to fix this issue.

HTML DOM delete row and calculation problem

I am working in a html file that contains a table and by clicking ‘Add rows’ the rows are being added and the total sum of all the ‘Total price’ is being stored in ‘Sub total’. But when I want to remove or delete a row the the proper value of ‘Sub total’ is not coming. Where is the problem and what’s the solution?? I am pasting the necessary lines.

                         <div class="row">
                            <table>
                              <tbody id="mytable">
                                <tr>
                                  <td>
                                    <label>Category</label>
                                    <span>*</span>
                                    <select class="form-control Category">
                                      <option>Select</option>
                                      <option>A</option>
                                      <option>B</option>
                                      <option>C</option>
                                      <option>D</option>
                                    </select>
                                  </td>
                                  <td>
                                    <label>Test Name</label>
                                    <select class="form-control TestName">
                                      <option>Select</option>
                                      <option>A</option>
                                      <option>B</option>
                                      <option>C</option>
                                      <option>D</option>
                                    </select>
                                  </td>
                                  <td>
                                    <label>Price</label>
                                    <input type="text" id="Price" name="Price[]" class="form-control Price" />
                                  </td>
                                  <td>
                                    <label>Discount(%)</label>
                                    <div class="row">
                                      <div class="col-lg-6">
                                        <input type="text"  name="discount1[]" class="form-control Discount1" />
                                      </div>
                          
                                      <div class="col-lg-6">
                                        <input type="text" name="discount2[]" class="form-control Discount2" />
                                      </div>
                                    </div>
                                  </td>
                                  <td>
                                    <label>Total Price</label>
                                    <input type="text" name="totalPrice[]" id="tp" class="form-control totalPrice">
                                  </td>
                                  <td class="close"  >

                                <span class="close">x</span>
                                </td>
                                </tr>
                              </tbody>
                            </table>
                          </div>
                          <button type="button" id="add">Add rows</button>


                         <script>

                            const table = document.getElementById("mytable");

                            document.getElementById("add").addEventListener("click", e => {
                            var row = table.querySelector("tr").cloneNode(true);
                            row.querySelectorAll("input").forEach(inp => inp.value = "");
                            table.append(row);
                            });

                            table.addEventListener("input", e => {
                            
                            let gtotal=0;
                            let totaldiscount=0;
                            table.querySelectorAll("tr").forEach(row => {

                                
                                const price = +row.querySelector(".Price").value;
                                const discount1 = +row.querySelector(".Discount1").value;
                                const percent = discount1 / 100;
                                const discount2 = price * percent;
                                const total = price - discount2;
                                row.querySelector(".Discount2").value = discount2;
                                row.querySelector(".totalPrice").value = total;
                                gtotal +=total;
                                totaldiscount +=discount2;
                                document.querySelector(".Subtotal").value= gtotal;
                                document.querySelector(".disc1st").value= totaldiscount;

                                
                                
                            });
                            var closebtns = document.getElementsByClassName("close");
                                var i;

                             
                              for (i = 0; i < closebtns.length; i++) {
                              closebtns[i].addEventListener("click", function() {
                                
                                this.parentElement.style.display = 'none';
                                var totalST= +document.getElementById("st").value;
                                var currentPrice= +document.getElementById("tp").value;
                                var currentST= totalST-currentPrice;
                                document.getElementById("st").value= currentST;
                               

                                
                            });
                            }

                           
                        
                            });


                        </script>


                     <div class="row" >
                            <div class="col-lg-7"></div>
                            <div class="col-lg-5"  id="BillSum">
                                <label>Bill summary</label><br>

                                <div class="row">

                                    <label>Sub total</label>
                                    <input type="text" id ="st" name="Sub total" class="form-control Subtotal" value="0.00">

                                </div>


                                <label>Tax</label><br>
                                <div class="row">

                                    <div class="col=lg-6">
                                        <input type="text" id="tax1" name="tax1" class="form-control tax1"  onkeyup="calculate(this.value);">
                                    </div>

                                    <div class="col=lg-6">
                                        <input type="text" id="tax2" name="tax2" class="form-control tax2">
                                    </div>

                                </div>


                                <label>Discount(-)</label><br>
                                <div class="row">
                                    <input type="text" id="discBill" name="Discount_Bill" class="form-control disc1st"  onkeyup="calculate(this.value);">

                                </div>

                                <label>Net payable</label><br>
                                <div class="row">
                                    <input type="text" id="net_payable" name="Net_Payable" class="form-control disc2st" >

                                </div>

                                <label>Received ammount</label><br>
                                <div class="row">
                                    <input type="text" id="received_ammount" name="Received_ammount" class="form-control ra"
                                        placeholder="Enter payment ammount">

                                </div>


                                <label>Payvia</label><br>
                                <div class="row">
                                    <select class="form-control">
                                        <option>Select</option>
                                        <option>A</option>
                                        <option>B</option>
                                        <option>C</option>
                                        <option>D</option>
                                    </select>

                                </div>



                                <label>Remarks</label><br>
                                <div class="row">
                                    <input type="text" name="Sub total" class="form-control"
                                        placeholder="Write your remarks">

                                </div>






                            </div>

                         </div>


                      <script>

                         function calculate(value){

                            var st1= +document.getElementById("st").value;
                             var t1= +document.getElementById("tax1").value;
        
                             var tax1=  +((st1*t1)/100);
                             
                             document.getElementById("tax2").value=tax1;

                             var discBill= +document.getElementById("discBill").value;
                             var np= (st1+tax1)-discBill;
                             document.getElementById("net_payable").value=np;

                           }
                 
                      

                        </script>

React 18 children array

i have a Root component which contains multiple Panel components

export interface RootProps{
    children: React.ReactNode,
    className?: string,
    scheme?: 'light' | 'dark',
    activePanel: string
}

const Root = ({scheme, children, activePanel, className}: RootProps) => {
    const rootClassName = ['root']
    if(scheme === 'dark') rootClassName.push('dark')
    else rootClassName.push('light')
    if(className) className.split(' ').forEach(c => rootClassName.push(c))

    const panels = React.Children.toArray(children) as React.ReactElement[]

    return (
        <div className={rootClassName.join(' ')}>
            {panels.map((child: React.ReactElement) => {
                const panelClassName = ['panel-wrapper']
                if(child.props.id === activePanel) panelClassName.push('active')
                return <div className={panelClassName.join(' ')}>
                    {child}
                </div>
            })}
        </div>
    );
};
export interface PanelProps{
    children: React.ReactNode,
    id: string
}

const Panel = ({children}: PanelProps) => {
    const className = ['panel']
    return (
        <div className={className.join(' ')}>
            {children}
        </div>
    );
};

when i am using these components in a project

function App() {
    return (
        <Root activePanel={'root'}>
            <Panel id={'root'}>
                <Button>aboba</Button>
            </Panel>
            <Panel id={'not-root'}>
                <Button>aboba</Button>
            </Panel>
        </Root>
  );
}

there is a problem in <Root>: This JSX tag’s ‘children’ prop expects a single child of type ‘ReactElement<any, string | JSXElementConstructor>’, but multiple children were provided.