How to launch a command on the server from a web page ( nodejs )

Viewed 46

I think that what i'm trying to do is simple, but I just don't know the proper wording to make my search efficient.

I have a webapp, in node js with the express.js framework. The web pages are templated with EJS and I have a database that contains my data ( MySQL ).

When I load a page, I get a list of all the items passed in an object and I have a foreach statement to generate a table.

The JS function :

listParts: (req, res) => {
    
    let query = `SELECT parts.*, l.product_vehicleId as InstalledOn, v.name as VehicleName FROM parts
                LEFT JOIN current_loadout as l ON idpart=l.parts_idparts
                LEFT JOIN dataRef.product as v ON v.idvehicle=l.product_vehicleId
                WHERE idpart>0;`
    db.query(query, (err, qResult) =>{
        if ( err == null )
        {
            res.render('listParts.ejs', { 
                title: 'RPA parts list',
                partList: qResult,
                url: req.originalUrl
            })
        }
    });
}

The EJS part :

     <tbody align="center">
                    <% partList.forEach((part, idx) => {%>
                        <tr>
                            <td><%=part.name%></td>
                            <td><%=part.serial%></td>
                            <td><%=Math.floor(part.ttsn/60).toFixed()%>:<%=Math.floor(Math.abs(part.ttsn%60)).toFixed(0).padStart(2,'0')%></td>
                            <td><%=part.maxTTSN%></td>
                            <td><%=part.maxCalendarDate%></td>
                            <td><%=part.VehicleName%></td>
                            <td><%if (part.serviceable) {%>
                                <a class="badge badge-success">Serviceable</a>
                                <%}else{%>
                                    <a class="badge badge-danger">Unserviceable</a>
                                <%}%>
                            </td>
                            <td><%if (part.serviceable) {%>
                                    <a href="11">  Make serviceable</a>
                                <%}else{%>
                                    <a href="11">  Make serviceable</a>
                                <%}%>
                            </td>
                        </tr>
                    <%})%>
                </tbody>

I would like to make a call on the server to query the DB to make a status change on my part object when the user click the button.

Usualy I use the href to my a REST API endpoint to call a delete object.

My struggle is : How to make it hidden from the user so people would not be able to call the REST endpoint with a script and change the status of all my parts ??

My background is C and C++ Python ... I am very new to javascript and all the Node module and especially, I am a total noob with frontend stuff.

Could somebody point me to a good direction É

1 Answers

As the saying goes, protect the route!

Now, how do we do that, especially when the calls from an un-authenticated client side request?

Enter JWT (JSON web tokens) It's easier then you think.

A JWT is a token, generated on your server that can contain any number of value, like appID, userID etc etc. These token are then 'encoded' and 'base64' before ultimately sending it back to the user. The token is encoded with a password, so if a person tries to modify the 'payload' in the token it wont pass the checksum and decode will fail.

So what does this really mean?

It means, you can now protect your routes with a token auth using middleware to check before processing the request. If the token does not match then no update will happen and you can return an unauthorized response to the client.

Setting this up is fairly easy, you can install the JWT npm package, this will allow you to generate and decode tokens. In your application you would create a 'getToken' endpoint. This would generate the token to pass back to the user ( this is typically done on authentication into the application )

The token is then sent back to the user and stored in a secure cookie ( you can store it however you like but a secure cookie will keep the token secure )

When you make your POST request to your other endpoints, simply add the token to the header OR as a post value.

On your route, as middleware OR in the route itself read the token, decode it, if there are no errors then the token was valid and process the request otherwise don't update it.

Related