Is CASL React library safe for authorization?

I came CASL JavaScript library, which restricts what resources a given client is allowed to access.

My question is whether it can be used for role based access in a React app in a secure way?

And whether user can temper with the permission and gain unauthorized access if used only in front end to display/hide components as shown in following react code?

import React, { useContext } from 'react';
import { AbilityContext } from './Can'

export default () => {
  const createTodo = () => { /* logic to show new todo form */ };
  const ability = useContext(AbilityContext);

  return (
    <div>
      {ability.can('create', 'Todo') &&
        <button onClick={createTodo}>Create Todo</button>}
    </div>
  );
}

Reference: https://casl.js.org/v5/en/package/casl-react

JavaScript – why can’t I do that? [duplicate]

I’m very new to JavaScript and I’m learning it slowly in my free time in trial and error fashion. I just wanted an explanation on why can’t i add an onClick event to the button that is created with this function, can’t find answer anywhere on the Internet. Thank you in advance.

        function create_button(link) {
            if (link)
                return "<button onclick="myFunction()">" + link + "</button>";
            else return "";
        }

How can I animate/simulate a cross road (video attached) on C/C++, and how should I start off?

I’m not proficient with C/C++, and I would need help with animating/simulating a cross road with cars passing by, which is a difficult task for me. Other programming language may be used, but I would like to use C/C++ if possible.

A video example is here: https://youtu.be/vn5IP9oxWrM

Here are some pointers I would like you to take note:

  1. I don’t need to animate/simulate many cars in it, but I would at least like to come up with scenarios of having 1, 2, 3, 4 or more cars (coming from each side of the cars, at least). Then I would like to assign each car a so-called coordinate. A 2-D demonstration would be sufficient.

  2. I attached a C++ code below as well to show what kind of cross road I would like to animate/simulate:

#include <iostream>

using namespace std;

int main()
{
    cout<<"      X | X      n";
    cout<<"      X | X      n";
    cout<<"      X | X      n";
    cout<<"      X | X      n";
    cout<<"      X | X      n";
    cout<<"XXXXXXX | XXXXXXXn";
    cout<<"                 n";
    cout<<"--------+--------n";
    cout<<"                 n";
    cout<<"XXXXXXX | XXXXXXXn";
    cout<<"      X | X      n";
    cout<<"      X | X      n";
    cout<<"      X | X      n";
    cout<<"      X | X      n";
    cout<<"      X |□X      n";
    return 0;
}

and □ is a car.

  1. My teammate told me about using arrays, but I’m not sure how to print it out in my code example. It would be great if you could let me know how can print arrays, and I’m not sure how to print it out in my code example. You could also rectify my example in (2) (I know it’s in string only, because I had no idea how to write in array form).
  2. It doesn’t have to be complicated, and I would like to approach this problem with really simple methods.

Thank you in advance!

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. app crushed

I’m getting this error -> ” Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client “.I tried to apply JSON Web Token(JWT) in my app and every time it’s logging me out from app. I can’t understand is it server-side error or client-side. Pls check my code

Here is the code:


    // verifyJWT function
        function verifyJWT(req, res, next){
            const authHeader = req.headers.authorization;
            if (!authHeader) {
                return res.status(401).send({ message: 'Your access is unauthorized to BookPile' });
            }
        
        
            const token = authHeader.split(' ')[1];
            jwt.verify(token, process.env.ACCESS_TOKEN_SECRECT, (err, decoded) => {
                if (err) {
                    return res.status(403).send({ message: 'BookPile authority forbid your access' })
                }
                console.log('decoded', decoded);
                req.decoded = decoded;
                next();
            })
        
        
            console.log('inside verify function', authHeader);
            next();
        }

//API

// GET API for get token
        app.post('/login' , async(req,res) => {
            const user = req.body;
            const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
                expiresIn:'1d'
            });
            res.send({accessToken});
        }) 



// GET API for load items of logged in user
        app.get('/my_items' , verifyJWT ,  async(req,res) => {
            // const authHeader = req.headers.authorization;
            // console.log(authHeader);
            const email = req.query.email;
            const criteria = {email:email};
            const cursor = await booksCollection.find(criteria);
            const books = await cursor.toArray();
            res.send(books);
        })


    
//Client side
const getMyBooks = async () => {
            const email = user.email;
            const url = `http://localhost:5000/my_items?email=${email}`;
           
            try {
                const { data } = await axios.get(url, {
                    headers: {
                        authorization: `Bearer ${localStorage.getItem('accessToken')}`
                    }
                })

                setMyBooks(data);
            }

            catch (error) {
                console.log((error.message));
                if (error.response.status === 401 || error.response.status === 403) {
                    signOut(auth);
                    // navigate('/login');
                }
            }

           
        }
        getMyBooks();
    }, [user])

//Client side login
const handleForm = async event => {
        event.preventDefault();
        const email = emailRef.current.value;
        const password = passRef.current.value;

        await signInWithEmailAndPassword(email, password);
        const { data } = await axios.post('http://localhost:5000/login', { email });
        // console.log(data);
        localStorage.setItem('accessToken', data.accessToken);
        navigate(from, { replace: true });
    }

Displaying several maps with leaflet in a table

I am trying to display several maps within a table, using Leaflet & Thymeleaf. This means that I have to name each map container differently or otherwise I get an error because a container with such name is already initialised. I managed to do it using Thymeleaf’s standard expression syntax and got no erros so far but the maps are not displaying. I am using these expressions to name the map container’s id after a ‘route id’ which is a numeric string.
if anybody could offer some advice on what am I doing wrong, it will be much appreciated.

        <tbody>         
                <tr th:each="route: ${listRoutes}">
                    <form th:action="@{/delete_route}" method="get">             
                        <td><input type="hidden" name ="routeID" th:value="${route.id}" class="form-control"></input> [[${route.id}]] </td>
                        <td><div th:id="${route.id}"></div>Map Container </td>
                        <td th:text="${route.owner.id}">Owner</td>
                        <td th:text="${route.participants}">Participants</td>
                        <td style="cursor:pointer"><input type="submit" value="Delete Route" class="btn btn-primary" /> </td>                  
                    <script th:inline="javascript">          
                        var map = new L.map("[[${route.id}]]");
                        
                        L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                        attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap </a>',
                        maxZoom: 18
                        }).addTo(map);
                            
                        L.control.scale().addTo(map);
                        var gpx = /*[[${route.directions}]]*/ "";
                        new L.GPX(gpx, {async: true}).on('loaded', function(e) {
                        map.fitBounds(e.target.getBounds());
                        
                        }).addTo(map);
                    </script>
                    </form> 
                </tr>
            </tbody>  

Is it possible to protect react redux states from clientside-manipulations?

Currently im coding a small math-game for the browser. The current plan is to have two redux states for the gamedata. One for operational data, which doesnt have to be stored in the database because it just contains data for the game-logic and another one for the savegame data. The savegame data will be stored in a database after every ingame-interval.

I just learned that states can be manipulated from the client-side, which wouldnt be very desireable since the game will have multiplayer components.

So i wonder if it is possible to protect the states from manipulation in any way.
Would welcome your ideas. Thank you in advance.

Viewing webpage full source in Chrome

There is a website with 50 questions and answers, you cant see “Explanation” Button unless you choose one of three answers, and after you click Explanation it explains why correct answer is correct. It is javascript i guess, how can i simulate clicks to all 50 answers and explanation so i get page source with explanation?

I have tried to change visibility settings.

how to decrees single item click using react and mongoDB

enter image description here

enter image description here

enter image description here

client site code

const ManageInventory = () => {
//const { inventoryId } = useParams();
const [products, setProducts] = useInventory();
const handleDelete = id => {
    const proceed = window.confirm('Are you Sure?');
    if (proceed) {
        const url = `https://rocky-wildwood-46157.herokuapp.com/product/${id}`
        fetch(url, {
            method: 'DELETE'
        })
            .then(res => res.json())
            .then(data => {
                console.log(data);
                const remaining = products.filter(product => product._id !== id)
                setProducts(remaining);

            })
    }
};

server code:

app.put('/product/:id', async (req, res) => {
            const id = req.params.id;
            const delivered = req.body;
            const filter = { _id: ObjectId(id) };
            const options = { upsert: true };
            const updatedDoc = {
                $set: {
                    quantity: delivered.quantity
                }
            };
            const result = await productCollection.updateOne(filter, updatedDoc, options);
            res.send(result);
        })

how to decrees single item from some item click using react and MongoDB

Store multiple files in a single file

I’m building a presentation tool with Vue, like PowerPoint, where users can create slides with different content, for example videos and images.

Now I’d like users to be able to save the presentation as one single file, with all the content files embedded (jpg/mp4/etc.).

Is it possible to create such a “container file” from the browser?

And when the user loads this file I’d like to use these files in my HTML, for example by using <video src="file:///example.mp4">.

I could of course save all files as eg. base64 in a single file, but since especially videos can be rather large files it would be nice if the file(s) don’t have to be loaded into the RAM but can be accessible from the harddisk (as a stream?).

Warning: Cannot update a component (`BrowserRouter`) while rendering a different component (`Social`)

I’m getting this warning from ReactJS. I couldn’t understand what it meant and didn’t find any solution. How to fix this?

Here is the full warning

Warning: Cannot update a component (`BrowserRouter`) while rendering a different component (`Social`). To locate the bad setState() call inside `Social`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
at Social (http://localhost:3000/static/js/bundle.js:3074:130)
at form
at div
at Login (http://localhost:3000/static/js/bundle.js:1613:78)
at Routes (http://localhost:3000/static/js/bundle.js:58827:5)
at div
at App
at Router (http://localhost:3000/static/js/bundle.js:58760:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:57569:5)

Social.js

const Social = () => {
const [signInWithGoogle, user, loading, error] = useSignInWithGoogle(auth);
const navigate = useNavigate();
const location = useLocation();

const from = location?.state?.from?.pathname || '/';


if (user) {
    navigate(from, { replace: true });
}

return (
    <div>
        <div className='flex items-center'>
            <hr className='border-black w-5/12' />
            <p className='w-2/12 text-center'>Or</p>
            <hr className='border-black w-5/12' />
        </div>
        <div className='mt-3'>
            <p onClick={() => signInWithGoogle()} className='flex cursor-pointer justify-center items-center mx-auto text-white bg-slate-800 hover:bg-slate-900 p-1 rounded-md'><img className='w-4 h-4 mr-1' src={googleLogo} alt="" />Continue with Google</p>
        </div>
    </div>
);

};

How to add template reference Variable inside iframe of (button) element in angular 10.x

Note: Iframe is Dynamic generated.

  1. I need to add a template reference variable inside a dynamic generated Iframe of Button element and that button element will be display none.
    Like (<button #submitBtn style=”display: none;”> Submit )
    and
  2. I need to add a Angular event inside a dynamic generated Iframe of form element. Like (<form action=”” method=”post” (ngSubmin)=”submiFunction()”> )

How can I find many-to-many relations in nest.js

I try to view the document of typeorm (for v0.3 now). But the Nest.js application is based on v0.2.

The document said that I can use find method with find-option:

const questions = await questionRepository.find({
    relations: {
        categories: true,
    },
})

But when I try, the TypeScript tell me that the relations‘ type is string[]. So I change it to:

const questions = await questionRepository.find({
    relations: ['categories']
})

But raise an error:

Relation "categories" was not found; please check if it is correct and really exists in your entity.

I do not want to use createQueryBuilder because it uses the string and it is hard to deal with: Sometimes the original entity changes its name but TypeScript will never raise an error…

So can I use the relations on v0.2? I cannot find anything useful for this version.

is there a function to manipulate table data in javascript

so I’m creating a defi app and there are 3 main ‘divs'(volume,balance,amount traded). the idea is that anytime I click on a div the able should change contents. right now I haven’t worked out the blockchain aspect so all I want the divs to do is show just odd or just even column numbers. please help with a Javascript function. table code below.

<table class="table table-hover table-bordered rounded">
          <thead>
            <tr>
              <th scope="col">Name</th>
              <th scope="col">Chain</th>
              <th scope="col">Sector</th>
              <th scope="col">USD</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <th scope="row">1</th>
              <td>Mark</td>
              <td>Otto</td>
              <td>@mdo</td>
            </tr>
            <tr>
              <th scope="row">2</th>
              <td>Jacob</td>
              <td>Thornton</td>
              <td>@fat</td>
            </tr>
            <tr>
              <th scope="row">3</th>
              <td>Larry the Bird</td>
              <td>what what?</td>
              <td>@twitter</td>
            </tr>
            <tr>
              <th scope="row">4</th>
              <td>Mark</td>
              <td>Otto</td>
              <td>@mdo</td>
            </tr>
            <tr>
              <th scope="row">5</th>
              <td>Jacob</td>
              <td>Thornton</td>
              <td>@fat</td>
            </tr>
            <tr>
              <th scope="row">6</th>
              <td>Larry the Bird</td>
              <td>what what?</td>
              <td>@twitter</td>
            </tr>
            <tr>
              <th scope="row">7</th>
              <td>Mark</td>
              <td>Otto</td>
              <td>@mdo</td>
            </tr>
            <tr>
              <th scope="row">8</th>
              <td>Jacob</td>
              <td>Thornton</td>
              <td>@fat</td>
            </tr>
            <tr>
              <th scope="row">9</th>
              <td>Larry the Bird</td>
              <td>what what?</td>
              <td>@twitter</td>
            </tr>
            <tr>
              <th scope="row">10</th>
              <td>Mark</td>
              <td>Otto</td>
              <td>@mdo</td>
            </tr>
            <tr>
              <th scope="row">11</th>
              <td>Jacob</td>
              <td>Thornton</td>
              <td>@fat</td>
            </tr>
            <tr>
              <th scope="row">12</th>
              <td>Larry the Bird</td>
              <td>what what?</td>
              <td>@twitter</td>
            </tr>
          </tbody>
        </table>

Is it possible to delete the login and register pages? shopify

Is it possible to delete the login and register pages?

https://site.myshopify.com/account/login and https://site.myshopify.com/account/register

or you can remove the redirect to this page when you enter the wrong password on this form?

{% form 'customer_login', class:'form' %}
            <div class="title upper">вход</div>
            <div class="content">
                <div class="inputs">
                <input
                        type="email"
                        placeholder="E-mail"
                        name="customer[email]"
                        required
                        />
                <input
                        type="password"
                        placeholder="Пароль"
                        name="customer[password]"
                        required
                        />
                </div>
                <div class="forget-password">
                    <button onclick="window.location='/pages/forgot-password'" type="button" class="pointer hv-green">
                        Забыли пароль?
                    </button>
                    {% if template.name == 'login' %}
                        <div class="error-message">
                            {{ form.errors | default_errors }}
                        </div>
                    {% endif %}
                </div>
            </div>
            <div class="login">
                <button type="submit" class="pointer upper">
                войти
                </button>
            </div>
        {% endform %}