In CASL with JSON rulesets, can I check the attributes of the user rather than the subject?

This works fine from imported JSON:

[
  {
    "action": "update",
    "subject": "blogpost",
    "conditions": {
      "authorId": "{{userId}}"
    },
    "reason": "User is not the original author"
  }
]

I use Mustache to change the {{userId}} to the userId of the user that is requesting the permission to update.

{
    name: "User 1",
    userId: 1,
    roles: ["admin", "billingadmin"]
}

… so the JSON now looks like the below:

[
  {
    "action": "update",
    "subject": "blogpost",
    "conditions": {
      "authorId": "1"
    },
    "reason": "User is not the original author"
  }
]

If the blogpost object looks like this:

{
title”: “Test Blog Post”,
authorId: 1
}

… then CASL recognises the condition is met that the “authorId” of the blogpost is “1”, which is the same in the conditions in the JSON file. Great stuff.


However, now I want to check if the user has a specific role when trying to update the blogpost.

This is different, because I’m not checking an attribute of the subject, but an attribute of the user accessing the subject.

How do I do this in the JSON?

My user is like this:

{
    name: "User 1",
    userId: 1,
    roles: ["admin", "billingadmin"]
}

… so how would my JSON look like? It can’t look like the below as the ‘userrole’ attribute isn’t on the subject.

[
  {
    "action": "update",
    "subject": "blogpost",
    "conditions": {
      "userrole": "admin"
    },
    "reason": "User is not an admin"
  }
]

… so what’s the best approach?

How can I optimize loading times for a portfolio website that includes multiple images and animations?

My portfolio site has several images, animations, and a toggle for dark/light mode. It loads slowly, especially on mobile. What strategies can I use to optimize load times without compromising quality?

I’m working on making my portfolio website more mobile-friendly using CSS and Bootstrap. I’ve set up a responsive grid layout with Bootstrap and used media queries in CSS to adjust certain elements. However, when testing on smaller screens, I notice that some elements overlap, and the layout doesn’t adjust as smoothly as I expected. I was hoping the layout would stack the sections vertically on smaller screens and resize images to fit within the container.

Here’s what I’ve tried:

  1. I used Bootstrap’s col- classes (like col-md-6 and col-sm-12) to create responsive columns.
  2. Added CSS media queries to adjust font sizes and padding for mobile screens.
  3. Attempted to hide or resize images using display: none; and max-width: 100%; for images on smaller devices.

I expected these changes to make the site look clean and organized on both desktop and mobile, but the alignment issues persist, and the images still look stretched. Any advice on better approaches to manage Bootstrap’s grid and improve the responsiveness?

Collapsible HTML table from 2D array

My Data is this

[['State', 'Jan-24','Feb-24', 'Mar-24', 'Apr-24'
 'NY'         100,  200,    300,    400,
 'City - 1'   30,   50, 75, 100,
 'City - 2'   30,   50, 75, 150,
 'City - 3'   40,   100,    150,    150
 'IL',        500,  300,    345,  234
 'City-4',    500,  300,    345, 234]]

I am trying to acheive collapsible Table, State NY should be always visible, for example On click of NY row I am trying to expand the rows City-1,City-2 & City-3

I am following below examples,

Collapse Google Vis Table When Row Content Hidden

Collapsible & Expandable row with dynamic content based on cell

I am not sure how much this is possible in Google Table chart. Alternately I tried finding some examples in JS. I am finding hard time in understanding in the odd & even row concepts. My code looks really messy hence I didn’t add completely it in here.

I am trying to add this in my Google web app.

<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">   
<script type='text/javascript'>
    google.charts.load('current', {'packages':['corechart','controls']});
    google.charts.setOnLoadCallback(toggle_data);

function toogle_table(){
        google.script.run.withSuccessHandler(e=>{
          let array_json = JSON.parse(e);      
})
}
</script>

Seeking expert advise on this.

I’m a fresher with interests in web development and some experience with HTML and CSS. Should I choose a software engineering or AI/ML-focused cohort [closed]

I’m a fresher with interests in web development and some experience with HTML and CSS. I enjoy designing user interfaces and am considering learning JavaScript to build more dynamic websites. Should I choose a software engineering cohort to strengthen my web development skills or an AI/ML-focused cohort as it is in trend right now and what I hear from Seniors that AI is going to basically take over the tech world.?

ES7 Regex Mobile Phones Validation

I need to validate mobile numbers:

Numbers has to start with 3, have some patterns, and be 10 digits long: quite simple so far.

The odd par is that number some numbers starting with 335 and 336 can have both 9 or 10 digits:

More precisely, number starting with 3352,3353,3354,3362,3367 are 9 digits, all other are 10 digits.

I “wrote” this regex:

^(3((352)|(353)|(354)|(362)|(367))[0-9]{5})|(3((20)|(22)|(23)|(24)|(27)|(28)|(29)|(30)|(31)|(33)|(34)|(35)|(36)|(37)|(38)|(40)|(42)|(43)|(44)|(45)|(46)|(47)|(48)|(49)|(50)|(51)|(52)|(53)|(60)|(63)|(66)|(68)|(70)|(71)|(73)|(75)|(76)|(77)|(78)|(79)|(80)|(83)|(88)|(89)|(90)|(91)|(92)|(93)|(97))[0-9]{7})$

that (partially) works, but accept number starting with 3352(…) even if 10 digits long.. while it should not

I think I used a wrong approach, because now I think I should add in the latter part of regex, where I have (35) and (36) something like

"and not in 3352,3353,3354,3362,3367"

but do not have idea how to do it.

Can somebody suggest the right approach?

Thanks

Here the regex example

regex101.com/r/6Exsee/1

How do I put together a Blazor Page that will call a javascript file that needs to import an ESModule?

There is the following application called Fantastic Dice that is a javascript module. It can be loaded as such from the example provided here from this page.

https://codesandbox.io/p/sandbox/dice-es6-module-cdn-lhbs99?file=%2Fsrc%2Findex.js%3A1%2C1-2%2C1

I have tried doing this in a Blazor page with no success.

I have the following javascript file called dice.js

import DiceBox from "https://unpkg.com/@3d-dice/[email protected]/dist/dice-box.es.min.js";

export function DiceBoxCall() {
    let Box = new DiceBox("#dice-box", {
        assetPath: "assets/",
        origin: "https://unpkg.com/@3d-dice/[email protected]/dist/",
        theme: "default",
        themeColor: "#feea03",
        offscreen: true,
        scale: 6
    });

    Box.init().then(async (world) => {
        Box.roll(["4d20", "4d12", "4d10", "4d8", "4d6", "4d4"]);
    });
}

I call it from Blazor using the JSRuntime library

await JSRuntime.InvokeVoidAsync("DiceBoxCall");

This loads, but It cannot find DiceBoxCall. I’m pretty sure its the import but that import is vital to everything. The library fantastic dice uses is an ESModule and the import call is loading the library into a class object. I cannot find any other example that would help me here.

Bootstrap 5 Popover-Set Content Dynamically from Async Function

I’m trying to load a bootstrap 5 popover with dynamic content from an asynchronous function in which I have to wait for. I’m setting up my popover as so:

document.querySelectorAll('[data-bs-toggle="popover"]').forEach(function (popover) {

    new bootstrap.Popover(popover, {
        content: function () {
            (async () => {

                var x = await SetPopoverContent();
                return x;

            })()
        }
    });   
});

I’m then going back to the database and retrieving my data inside SetPopoverContent():

async function SetPopoverContent(popOver) {
    
    let contentText = '';
    let data = await dotNetReference.invokeMethodAsync('GetChatToInfo', messageId);
    if (data != null && data != undefined) {
        var outerDiv = '<div></div>';
        ...
        
        contentText = outerDiv.innerHTML;
    }
    else {

        contentText = '<p>Loading</p>';
    }
    
    return contentText;
}

I can see my html string inside my popover content function but the content never appears in the popover. Am I doing something wrong with the async callback method?

How can I measure the response times of an http request in Node?

I am working on a solution that makes http requests to different web services, and I need to measure the response times (detailed), I am currently using the “node:https” module, but I would like to know if there is a Library or package that is not ” request” since it is deprecated and with axios I have not managed to do it

I leave here an example of the code I use

import https from "node:https";

const NS_PER_SEC = 1e9;
const MS_PER_NS = 1e6;
const timings = {
  // use process.hrtime() as it's not a subject of clock drift
  startAt: process.hrtime(),
  dnsLookupAt: undefined,
  tcpConnectionAt: undefined,
  tlsHandshakeAt: undefined,
  firstByteAt: undefined,
  endAt: undefined,
};

let responseBody = "";

const req = https.request(
  {
    hostname: SERVICE_URL,
    port: 443,
    path: "/",
    method: "GET",
    timeout: 5000,

    headers: {
      "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
      Accept: "*/*",
      "Accept-Language": "en-US,en;q=0.9",
      "Accept-Encoding": "gzip, deflate, br",
    },
  },
  onAnyMessage
);

async function onAnyMessage(res) {
  res.once("readable", () => {
    timings.firstByteAt = process.hrtime();
  });
  res.on("data", (chunk) => {
    responseBody += chunk;
  });
  res.on("end", () => {
    timings.endAt = process.hrtime();
    console.log(responseBody);
    console.log(getTimings(timings));
  });
}

function getTimings(eventTimes) {
  return {
    // There is no DNS lookup with IP address
    dnsLookup:
      eventTimes.dnsLookupAt !== undefined
        ? getHrTimeDurationInMs(eventTimes.startAt, eventTimes.dnsLookupAt)
        : undefined,
    tcpConnection: getHrTimeDurationInMs(
      eventTimes.dnsLookupAt || eventTimes.startAt,
      eventTimes.tcpConnectionAt
    ),
    // There is no TLS handshake without https
    tlsHandshake:
      eventTimes.tlsHandshakeAt !== undefined
        ? getHrTimeDurationInMs(
            eventTimes.tcpConnectionAt,
            eventTimes.tlsHandshakeAt
          )
        : undefined,
    firstByte: getHrTimeDurationInMs(
      eventTimes.tlsHandshakeAt || eventTimes.tcpConnectionAt,
      eventTimes.firstByteAt
    ),
    contentTransfer: getHrTimeDurationInMs(
      eventTimes.firstByteAt,
      eventTimes.endAt
    ),
    total: getHrTimeDurationInMs(eventTimes.startAt, eventTimes.endAt),
  };
}

/**
 * Get duration in milliseconds from process.hrtime()
 * @function getHrTimeDurationInMs
 * @param {Array} startTime - [seconds, nanoseconds]
 * @param {Array} endTime - [seconds, nanoseconds]
 * @return {Number} durationInMs
 */
function getHrTimeDurationInMs(startTime, endTime) {
  const secondDiff = endTime[0] - startTime[0];
  const nanoSecondDiff = endTime[1] - startTime[1];
  const diffInNanoSecond = secondDiff * NS_PER_SEC + nanoSecondDiff;

  return diffInNanoSecond / MS_PER_NS;
}

req.on("socket", (socket) => {
  socket.on("lookup", () => {
    timings.dnsLookupAt = process.hrtime();
  });
  socket.on("connect", () => {
    timings.tcpConnectionAt = process.hrtime();
  });
  socket.on("secureConnect", () => {
    timings.tlsHandshakeAt = process.hrtime();
  });
});

req.on("error", (err) => {
  console.log(err);
});

req.end();

Alert pop up when a form is submitted

I want to display an alert pop-up when a form is submitted, but it is not working as expected. When I refresh the page, the alert pop-up does not hide itself; instead, it continues to display even after the page reloads. I want the pop-up to appear only when the form is submitted successfully without any errors. Below is my code:

Firstly, i set my isModalOpen to state to false

const [isModalOpen, setIsModalOpen] = useState(false)

In the handleSubmit function, here is my code

function handleSubmit(e){
    e.preventDefault();
    let hasError = false;

    // if there is no error, the form will be submitted
    if(!hasError){
      setIsModalOpen(true)

    if(firstName.trim() === ''){
      setFirstNameError('This field is required')
      hasError = true;
    }
    if(emailAddress.trim() === ''){
      setEmailError('Please enter a valid email address')
      hasError = true;
    }
    if(message.trim() === ''){
      setMessageError('This field is required')
      hasError = true;
    }
    }

}

And finally this is my code which render the pop-up message the form is submitted with no errors

{isModalOpen && (
       <div id='overlay'>
        <div className={`pop-up`}>
          <div className='flex gap-2 check'>
            <img src="./images/icon-success-check.svg" alt="" />
            <p>Message Sent!</p>
        </div>
  
        <p className='relative ml-[20px]'>Thanks for completing the form. We'll be in touch soon!</p>
        </div>
      </div>
    )}

changing an object key’s values

How can I change the **obj2 **values instead of doing it one by one as shown is there a way that doing it at once ?

const obj1={
  name:`serag`,
  age:30,
  children:
  {
    daughter:`leila`,
    son:`seif`
  }
};

const obj2 = JSON.parse(JSON.stringify(obj1));

let {name,age,children}=obj2;
// obj2.name =`omar`;
// obj2.age=30;
// obj2.children.daughter=`huda`;
// obj2.children.son=`ahmed`;

I just started to learn JS consider myself a beginner

Editable Tooltips in shinyWidgets::noUiSliderInput

I’ve been trying to customise shinyWidgets::noUiSliderInput with JS so that its tooltips are editable and the slider reacts to user inputs—something exactly like the example here, but in Shiny.

I created this shiny app to play with JS:

library(shiny)

ui <- fluidPage(
  tags$h2("Shiny noUiSlider with Editable Tooltips"),
  
  shinyWidgets::noUiSliderInput(
    inputId = "slider_id",
    value = c(10, 20),
    min = 0,
    max = 50
  ),
  
  # JS to create the slider with editable tooltips
  tags$head(tags$script(HTML(
    "$(document).ready((function() {
      var slider = document.getElementById('slider_id');
    
      function sp(event) { event.stopPropagation(); }

      function makeTT(i, slider) {
        var tooltip = document.createElement('div'),
            input = document.createElement('input');

        tooltip.className = 'noUi-tooltip';
        tooltip.appendChild(input);

        input.addEventListener('change', function() {
          var values = [null, null];
          values[i] = this.value;
          slider.noUiSlider.set(values);
        });

        input.addEventListener('mousedown', sp);
        input.addEventListener('touchstart', sp);
        input.addEventListener('pointerdown', sp);
        input.addEventListener('MSPointerDown', sp);

        slider.querySelector(i ? '.noUi-handle-upper' : '.noUi-handle-lower').appendChild(tooltip);
        return input;
      }

      // Create tooltip inputs
      var tooltipInputs = [makeTT(0, slider), makeTT(1, slider)];
    
      slider.noUiSlider.on('update', function(values, handle) {
        tooltipInputs[handle].value = values[handle];
      });
    })())"
  )))
)

# Server logic
server <- function(input, output, session) {
  observe({
    print(input$slider_id)  # For debugging
  })
}
shinyApp(ui = ui, server = server)

It doesn’t do what I expect, and I get this error:
null is not an object (evaluating 'slider.querySelector') when the following part of the makeTT function is being executed:

slider.querySelector(i ? '.noUi-handle-upper' : '.noUi-handle-lower').appendChild(tooltip);

That leads me to think the way I defined slider here var slider = document.getElementById('slider_id'); is incorrect (as it returns NULL, as the error says). But I’m not sure how else I should refer to this object.

Strapi Login Form Customization

I am trying to add a new field(for captcha) to my login form for the admin panel in Strapi(version 5.2.0). So far I have tried adding a custom plugin and also trying to inject a component to my login form, but I have failed since it seems that the login form doesn’t have any injection zones to inject customized components. I saw a video for earlier versions of Strapi where you could write an entirely customized login screen but it’s not working for the new version. I looked into the patching solution but it seems very unclean. Has anybody succeeded in adding a new field to the Strapi login form for the admin panel?

Can’t connect to EC2 Ubuntu instance from Next.js (JavaScript) via SSH

I’m trying to establish an SSH connection from my Next.js application to an AWS EC2 instance, but I’m encountering authentication failures. Here’s my setup:

  • Next.js application (JavaScript)
  • AWS EC2 instance running Ubuntu
  • Using ssh2-no-cpu-features library for SSH connection
import { Client } from 'ssh2-no-cpu-features';

const EC2_CONFIG = {
    host: 'XXXXXX.eu-north-1.compute.amazonaws.com',
    port: 22,
    username: 'ubuntu',
    algorithms: {
        kex: [
            'ecdh-sha2-nistp256',
            'ecdh-sha2-nistp384',
            'ecdh-sha2-nistp521'
        ],
        cipher: [
            'aes128-ctr',
            'aes192-ctr',
            'aes256-ctr',
            'aes128-gcm',
            'aes256-gcm'
        ],
        serverHostKey: [
            'ssh-rsa',
            'ecdsa-sha2-nistp256',
            'ssh-ed25519'
        ],
        hmac: [
            'hmac-sha2-256',
            'hmac-sha2-512'
        ]
    },
    debug: process.env.NODE_ENV === 'development' ? console.log : undefined,
    readyTimeout: 30000
};

function formatPrivateKey(key) {
    if (!key) throw new Error("Private key not found in environment variables");

    return key
        .trim()
        .replace(/\n/g, 'n'); // Handle escaped newlines
}

async function createSSHConnection() {
    const conn = new Client();

    try {
        const privateKey = formatPrivateKey(process.env.AWS_PRIVATE_RSA);
        const config = { ...EC2_CONFIG, privateKey };

        return new Promise((resolve, reject) => {
            conn.on('ready', () => {
                console.log('Connection ready');
                resolve(conn);
            });
            conn.on('error', (err) => {
                console.error('Connection error:', err);
                reject(err);
            });
            conn.connect(config);
        });
    } catch (error) {
        throw new Error(`SSH Connection failed: ${error.message}`);
    }
}

AWS_PRIVATE_RSA="-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAxGXAftWaE8kRSAWHRmKA/Jx9VtCyd2A3lal708ZnowfWCEyh
................
-----END RSA PRIVATE KEY-----"

I aim to connect to EC2, execute a command, and receive an answer to proceed.

The error:
Inbound: Received USERAUTH_FAILURE (publickey) Client: publickey (rsa-sha2-256) auth failed Client: publickey auth failed Connection error: Error: All configured authentication methods failed