How to change leaflet.js source based on location

I am working on a UI that will have a map integration written in react. The code is very simple:

return (
    <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
);

However I want the source to sometimes be from a different map, the idea is that the important parts of the map can be cached and viewed even when offline (this project will only run locally)

So something like this

if(0<=x<=5 && 8<=y<=12)
    return (
        <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://localhost/{z}/{x}/{y}.png"
        />
    );
else
    return (
        <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
    );

The problem with this javascript-like pseudo code is that I don’t have access to x, y and z. Is there a way to get these values when creating a request?

Download not renaming using local path

I have the following element:

<a href="/temp/8072ba11-999d-484c-b074-f9f2ce249056.xlsx" download="MyFile.xlsx">  </a>

Initiating a click event on the element causes a download to occur but the file is not renamed to MyFiles.xlsx.

The size of the file can range from 5KB to 150MB with the same results no matter the size.
The results are the same on Chrome, Edge and Firefox.

The element is generated and programmatically clicked in a Django Python environment in the success callback of an AJAX call. The JavaScript code that generates and clicks the element is:

var link = document.createElement('a');
link.href = response.url;
link.download = dl_name;
document.body.appendChild(link);
link.click();
console.log(link);
document.body.removeChild(link);

Previous posts have suggested this behavior could happen using cross-origin but my URL is same-origin.

Here is the raw response headers from the ajax call:
HTTP/1.1 200 OK
Date: Wed, 08 Jan 2025 14:48:37 GMT
Server: WSGIServer/0.2 CPython/3.11.5
Content-Type: application/json
X-Frame-Options: DENY
Content-Length: 57
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

I am expecting that the name of the downloaded file gets set to the value in download attribute of the anchor tag.

I have tried an endless number of things over the past week. Too many to list and honestly they are all just a jumble in my mind by now. They range from varying the path in the href, and even altering my approach all together to use a blob as the file link but that just resulted in a corrupted XLSX file which I also was unable to solve.

As a minimal reproduceable example, I placed the anchor tag element, as it is above in bold, as the only line in an HTML file. I ran the HTML file and manually clicked the link. I received the same behavior – no renaming of the downloaded file.

The div should extend beyond the window when its size is increased

I’ve got a list of words, which I would like to see like an infinite text on the screen. When you hover one of them the div expands and shows you a couple of hidden buttons from the left. It works for left and centre divs, but the most right div are going crazy cause it has not enough space to expand. Suggest me, please, how could I get flex window (definitely not grid) which fills by text?

JS (React):

        <div className={styles.wrapper}>{
                <div className={styles.word}>
                  <div className={styles.add}>{'u002B'}</div>
                  <div className={styles.like}>{'u2665'}</div>
                  {`${e.toUpperCase()}`}
                </div>}
        </div>)}
    </div>
  )
}

CSS:

.root {
    display: flex;
    flex-wrap: wrap;
    white-space: nowrap;
    width: 100%;
}


.wrapper { 
    flex-wrap: nowrap;
}

.word {
    display: flex;
    position: relative;
    font-size: 300%;
    word-spacing: -12px;
    padding: 3px;
    overflow: auto;
}

.like {
    display: flex;
    height: 0px;
    width: 0px;
    visibility: hidden;
}

.add {
    display: flex;
    height: 0px;
    width: 0px;
    visibility: hidden;
}

.country:hover .like {
    display: flex;
    visibility: visible;
    height: 40px;
    width: 40px;
    padding-right: 5px;
    overflow: auto;
}

.country:hover .add {
    display: flex;
    visibility: visible;
    height: 40px;
    width: 40px;
    padding-right: 5px;
    overflow: auto;
}

Creating a Child Object in Parent Class – Typescript

I want to create a Child Object in the Constructor, so i can directly access the Child class on my Parentclass without the need of creating the Child Object seperatly.

This is just a way to structure the code better for me.

But i run in the Problem of a circular dependency and get the Error “Class extends value [object Object] is not a constructor or null”.

These are my two classes:

  1. SteamSession (Parent)
const SteamTotp = require('steam-totp');
const SteamUser = require('steam-user');
const Listings =  require('./listing');

class steamSession {

    public session;
    public cookies: string;
    public accessToken: string;
    public listing;
    private userName: string;
    private password: string;
    private sharedSecret: string;
    private identitySecret: string;

    constructor(authData: AuthData) {
        this.userName = authData.userName;
        this.password = authData.password;
        this.sharedSecret = authData.sharedSecret;
        this.identitySecret = authData.identitySecret;
        this.session = new SteamUser();
        this.listing = new Listings();
        this.initiateSession();
    }
}

module.exports = steamSession; // Export der Klasse
  1. Listing (Child)
const steamSession = require('./steamSession');

class listing extends steamSession {
    // Return all Active Listings of the steamSessio

    getListings() {
        console.log(Fetching Steam Session Listings);
     }
}

module.exports = listing;

Is there anyway to create the Object directly in the Parentclass?
So i can access the Method in Listing like this for example:

let session = new steamSession(authData);
session.listing.getListings();

Unable To Reset Archer Record Permission Field using Custom Object

The code below works perfectly fine when setting the record permission field.

But when resetting the selection from the cross reference, the record permission field gets cleared after clicking the save button, but when exiting the record to the view mode, the record permission field retains the previous value as if the value was not cleared/reset. It’s a weird behavior that started happening recently.

Anyone with a different code to reset/blank out the record permission field.
Thank you.

SaaS, Version: 2024.09, Build: 6.15.00302.10262

function AssignUser() {
    UserArr = [];
 
    var selectedUserId = $('input[name*="SelectedValues' + fldIds.SelectUser + '"]').val();
    if (selectedUserId != '[]') {
        var selUserId = selectedUserId.substring(1, selectedUserId.length - 1);
        userId = GetAssociatedContactUser(selUserId);
        UserArr.push({
            id: userId,
            name: ""
        });
    }
    GetUserName(UserArr);
    SetRecordPermission(UserArr, FieldId, 'user');
}
function GetUserName(userArr) {
    var i;
    for (i = 0; i < userArr.length; i++) {
        var url = baseURL + "/api/core/system/user/" + userArr[i].id;
        var headers = {
            'x-csrf-token': csrfToken
        };
 
        $.ajax({
            headers: headers,
            url: url,
            data: '',
            type: 'GET',
            contentType: 'application/json',
            processData: false,
            async: false,
            dataType: 'json',
            success: function (data, textStatus, jqXHR) {
                //alert(JSON.stringify(data.RequestedObject, undefined, 2));                        
                userArr[i].name = data.RequestedObject.DisplayName;
            },
            error: function (data, textStatus, jqXHR) {
                alert(JSON.stringify(data, undefined, 2));
            }
        });
    }
}
 
function SetRecordPermission(buStaff, flId, itemType) {
 
    var RPFieldRoot = ArcherTech.UI.ClientContentManager.GetInstance().getFieldById(flId),
        UsrArray = [];
    var RPFieldRootId = RPFieldRoot.clientId;
    var displayNames = "";
    var ids = "";
    var i;
    for (i = 0; i < buStaff.length; i++) {
 
        UsrArray.push({
            name: buStaff[i].name,
            value: buStaff[i].id + ":" + (itemType == "group" ? 2 : 1)
        });
        displayNames += buStaff[i].name + " ";
        ids += buStaff[i].id + ",";
 
    }
 
    var serialized = Sys.Serialization.JavaScriptSerializer.serialize(UsrArray);
    ids = ids.substring(0, ids.lastIndexOf(','));
 
    //alert(serialized);    
    $('input[id*="' + RPFieldRootId + '_"]').val(serialized);
    $('div[id*="' + RPFieldRootId + '_"] div:first-child').text(displayNames);
 
    if (itemType == "group") {
        $('#SelectedGroups' + flId).val(ids);
    } else {
        $('#SelectedUsers' + flId).val(ids);
    }
}
 
function GetAssociatedContactUser(ctId) {
    var id = 0;
    var userid;
    var url = baseURL + "/api/core/content/" + ctId;
    var headers = {
        'x-csrf-token': csrfToken
    };
 
    $.ajax({
        headers: headers,
        url: url,
        data: '',
        type: 'GET',
        contentType: 'application/json',
        processData: false,
        async: false,
        dataType: 'json',
        success: function (data, textStatus, jqXHR) {
            userid = data.RequestedObject.FieldContents[fldIds.RSAArcherUserAccountCT].Value;
        },
        error: function (data, textStatus, jqXHR) {
            alert(JSON.stringify(data, undefined, 2));
        }
    });
 
    if (userid !== null && userid !== 'undefined')
        return userid.UserList[0].Id;
    else
        return id;
}
});

Rotate and change position of a axis title on ChartJS

an image would be easier to understand :
chart

I’ve got this chart made with ChartJS 3, and I’d like to put the “€” symbol on top and rotate it so that we read it easily.

How can I do this ?

This is my current options object :

export const chartDashboardOptions = {
  animation: false,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'top',
      align: 'end',
      labels: {
        boxHeight: 7,
        usePointStyle: true,
        padding: 20,
      },
    },
  },
  scales: {
    x: {
      grid: {
        color: getStyle('--cui-border-color-translucent'),
        drawOnChartArea: false,
      },
      ticks: {
        color: getStyle('--cui-body-color'),
      },
    },
    y: {
      title: {
        display: true,
        text: '€',
        align: 'end',
      },
      beginAtZero: true,
      border: {
        color: getStyle('--cui-border-color-translucent'),
      },
      grid: {
        color: getStyle('--cui-border-color-translucent'),
      },
    },
  },
  elements: {
    line: {
      tension: 0.4,
    },
    point: {
      radius: 5,
      hitRadius: 10,
      hoverRadius: 4,
      hoverBorderWidth: 3,
    },
  },
}

Thank you !

Validation not triggered on Enter key after formatOnBlur in react-final-form

I’m using react-final-form library for displaying forms. I am using a simple form with a text input field in React. I am utilizing the format function with formatOnBlur: true to trim the input strings.

My goal is to run validations after the string has been trimmed (i.e., after the format function has been executed).

However, I am facing an issue where validations are not triggered if I press the Enter key to submit the form.

The validations work perfectly if I type something like “react ” in the input field and click on the submit button, showing the error as expected. But when I press Enter, the form submits successfully without throwing any validation errors.

Minimal Reproducer

import "./styles.css";
import { Field, Form } from "react-final-form";

export default function App() {
  const onSubmit = (values: any) => {
    alert(JSON.stringify(values));
  };

  return (
    <div className="App">
      <Form
        onSubmit={onSubmit}
        render={({ handleSubmit, submitting, values }) => (
          <form onSubmit={handleSubmit}>
            <Field
              name="firstName"
              validate={(value) =>
                ["react", "javascript"].includes(value)
                  ? "Enter some other value"
                  : undefined
              }
              format={(value?: string) => value && value.trim()}
              formatOnBlur
            >
              {({ input, meta }) => (
                <div
                  style={{
                    display: "flex",
                    flexDirection: "column",

                    alignItems: "center",
                  }}
                >
                  <label>First Name</label>
                  <input
                    {...input}
                    type="text"
                    placeholder="First Name"
                    style={{ margin: "8px" }}
                  />
                  {meta.error && meta.touched && (
                    <span style={{ color: "red" }}>{meta.error}</span>
                  )}
                </div>
              )}
            </Field>

            <div className="buttons" style={{ marginTop: "4px" }}>
              <button type="submit" disabled={submitting}>
                Submit
              </button>
            </div>
          </form>
        )}
      />
    </div>
  );
}

Expected Behavior:
The form should perform validations after formatting the field and should throw an error when I press the Enter key.

Current Behavior:
The form submits successfully when pressing the Enter key, bypassing validations.

Sandbox Link:
You can reproduce the issue in this sandbox.

How to Conditionally Inject a Script in a Browser Extension Without Requiring User Configuration?

I am developing a browser extension and would like to control when the extension’s script is executed, limiting it to specific domains. Before injecting the script, I want to make an API call to a server, passing the current domain. If the server indicates that the extension should run, I will inject the script; otherwise, I will skip it.

It seems that using a background worker could be a potential solution, specifically with the following configuration:

 "background": {
    "service_worker": "background.js"
  }

However, this approach requires the user to explicitly enable background.service_worker, at least in Firefox. I would prefer not to have the browser require the user to modify default settings.

Here is the current content of the background.js file:

browser.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
  // Only run when the page has fully loaded
  if (changeInfo.status === 'complete') {
    // Check if the URL meets the criteria
    const shouldInject = await checkUrlAgainstApi(tab.url);
    
    if (shouldInject) {
      // Inject content script manually
      browser.scripting.executeScript({
        target: { tabId },
        files: ['content.js']
      });
    }
  }
});

async function checkUrlAgainstApi(url) {
  console.log('Allowing script injection for: ' + url);
  return true;
}

Here is my manifest.json

{
  "manifest_version": 3,
  "name": "Sample",
  "version": "1.0",
  "description": "Sample",
  "permissions": [
    "activeTab",
    "tabs"
  ],
  "host_permissions": [
    "http://*/*",
    "https://*/*"
  ],
  "background": {
    "scripts": [
      "background.js"
    ]
  },
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "content.js"
      ],
      "css": [
        "styles.css"
      ]
    }
  ]
}

I tried to use a background script like this

{
  "manifest_version": 3,
  "name": "Sample",
  "version": "1.0",
  "description": "Sample",
  "permissions": [
    "activeTab",
    "tabs",
    "scripting",
"webNavigation"
  ],
  "host_permissions": [
    "http://*/*",
    "https://*/*"
  ],
  "background": {
    "scripts": [
      "background.js"
    ]
  }
}

Then my background.js file:

chrome.webNavigation.onCompleted.addListener((details) => {
  console.log('completed event... here we inject the script if the API returns true.', details);
});

But I don’t get any console.log('') confirming that my extension is loaded.

Is there a way to implement this functionality without requiring the user to adjust settings, or is there an alternative approach I should consider?

High performance websocket on Node JS – delayed throughput

I have a websocket that sends me a lot of messages.
I needed to create a Node JS client that will:

  1. get the message
  2. add some properties
  3. publish it to a specific Kafka topic

the service runs in a docker container.
the amount of messages varies during the day, but has a very big peak at 14:30, of around 30,000 messages per second, for about 2 minutes, and then it fades.

my current solution is composed of a parent process, that connects to the websocket, gets the messages, and sends them as they arrive (via IPC) to a child process.
the child process adds the needed properties, and sends it via the Kafka producer.

the problem: during the peak time, the data gets published to Kafka 6-10 seconds after the message (supposedly) arrives in the websocket, which is unacceptable.

I tried: single/multiple process logic, Kafka high throughput producer settings, npm library fast-json-stringify, but still I’m not able to avoid this delay.
the container runs in a Google cloud VM with 4 CPU cores and 16 GB RAM.

how can I avoid this delay?

server.js code:

import websocket from "websocket";

import path from "path";
import { fileURLToPath } from "url";
import cp from "child_process";
import { resolve } from "path";
const __filename = fileURLToPath(import.meta.url); // get the resolved path to the file
const __dirname = path.dirname(__filename); // get the name of the directory
const worker = cp.fork(resolve(__dirname, "worker.js"));

const url = "myurl";

let ws;

function createSocket() {
    ws = new websocket.w3cwebsocket(url);

    ws.onerror = (err) => console.log(`${prefix}error in socket`, err);
    ws.onclose = (msg) => {
      const { code } = msg;
      console.log(`${prefix}Connection closed | reason: "${JSON.stringify(code)};"`);
      setTimeout(function () {
          createSocket();
      }, 1000);
    };
    ws.onmessage = (msg) => {
        worker.send(msg);
    }
}

worker.js code:

import kafka from "./kafka.js";

async function run() {
  process.on("message", async (input) => {
    try {
      const msg = {
        src: "i",
        sym: input.sym,
        p: input.p,
        s: input.s,
        t: input.t,
        vt: input.tv,
        ot: Date.now(),
      };
      kafka.producer.send({
        topic: "i",
        messages: [{ key: msg.sym, value: JSON.stringify(msg) }],
      });
    } catch (err) {
      console.log(`service general error`);
    }
  });
}

run().catch((e) => console.error(`[worker/producer] ${e.message}`, e));

kafka.js code:

import dotenv from "dotenv";
import { KafkaJS } from "@confluentinc/kafka-javascript";

dotenv.config();

const Kafka = KafkaJS.Kafka;
const kafakStr = "ws";

const kafka = new Kafka({
  kafkaJS: {
    clientId: kafakStr,
    brokers: [process.env.KAFKA],
  },
});

const kafkaObj = {
  producer: kafka.producer({
    "batch.size": 100000,
    "linger.ms": 50,
    "compression.type": "lz4",
    kafkaJS: { acks: 1 },
  }),
  consumer: kafka.consumer({ kafkaJS: { groupId: kafakStr } }),
};

export default kafkaObj;

Get data hidden in ellipses while web scraping

I’m attempting to grab episode title shown at the header of this website. When inspecting the page elements myself I can see near the top a line of HTML like this:

<h1 id="epName">...</h1>

which when clicking on the ellipses opens to

<h1 id="epName">Friendship is Magic, Part 1</h1>

I’ve attempted to automate this so I can save the corresponding episodes as their actual title as opposed to a season-episode code I’m currently using

I’ve tried basic request calling

url ='https://fim.heartshine.gay/?s=1&e=1&res=480&lo=0'
x = requests.get(url)
text = x.text
print(text)

but the important result of that was

</head>
<body onload="initPage();">
<h1 id="epName"></h1> <div>

with no actual info between the h1 tags.

I’ve also tried Selenium as I’ve guessed this might be a JavaScript enabled function:

from selenium import webdriver
driver = webdriver.Safari()
driver.get("https://g1.heartshine.gay/?s=1&e=46&res=480")
print(dir(driver))
driver.execute_script('changeEp') #this button controls the resulting epName
p_element = driver.page_source
print(p_element)

but again I get the same relevant output from above

Automation build: Seeking alternative solutions – generate US representative contact information based on greographical location

We’ve developed a tool that generates petitions addressed to U.S. state representatives, using the user’s information from their account and the representative’s details. This process includes fetching the representative’s mailing address from a geopolitical database via an API. However, the current database we use is deprecated, so we need to select a new one.

Congress.gov offers an API, but integrating it would require significant code changes. Rather than creating another ad hoc solution, I’m looking for a better alternative.

Any recommendations is appreciated.

Expected functionality when the tool is working correctly:

  • User information is entered manually or pasted as JSON data from the user’s application, including a signature line.
  • A request is made to the database based on the user’s address to retrieve the representatives for that area.
  • The database returns the representatives’ information, and the petitions are generated with both the user’s and representatives’ details.
  • Once generated, the user can download a zip file containing all the prepared petitions.

Currently, due to the deprecated database, the tool cannot retrieve all the representatives’ information, preventing petition generation.

How can I get an array of all overlapping date ranges across a given set?

I am using fullcalendar.io JS library to visualize the bookings on my rental company. I store the motorbikes as arrays of categories (engine sizes) with a children array containing all the motrobikes belonging to each, as in the example below:

// The resources array contains information about the motorbikes in a rental store.
// The parent array contains the information about the motorbike engine, 
// while the children array contains the information about the unique motorbikes belonging to each engine category.
resources = [{
    id: "scooter50",
    title: "Scooter 50",
    children: [{
            id: "aa123ab",
            title: "AA 123 AB"
        },
        {
            id: "aa456cd",
            title: "AA 456 CD"
        },
        {
            id: "aa789ef",
            title: "AA 789 EF"
        },
        {
            id: "aa101gh",
            title: "AA 101 GH"
        }
    ]
},
{
    id: "scooter125",
    title: "Scooter 125",
    children: [{
            id: "bb123ab",
            title: "BB 123 AB"
        },
        {
            id: "bb456cd",
            title: "BB 456 CD"
        },
        {
            id: "bb789ef",
            title: "BB 789 EF"
        },
        {
            id: "bb101gh",
            title: "BB 101 GH"
        }
    ]
},
{
    id: "scooter250",
    title: "Scooter 250",
    children: [{
            id: "cc123ab",
            title: "CC 123 AB"
        },
        {
            id: "cc456cd",
            title: "CC 456 CD"
        },
        {
            id: "cc789ef",
            title: "CC 789 EF"
        },
        {
            id: "cc101gh",
            title: "CC 101 GH"
        }
    ]
}
];

Then, I have some events (bookings) belonging to each resource:

// The events array contains information about the motorbikes that are rented, including the start and end date of the rental.
events = [{
    start: new Date(2025, 0, 6, 0, 0),
    end: new Date(2025, 0, 9, 23, 59, 59),
    resourceId: "bb101gh",
    title: "Event 0"
},
{
    start: new Date(2025, 0, 11, 0, 0),
    end: new Date(2025, 0, 14, 23, 59, 59),
    resourceId: "bb101gh",
    title: "Event 1"
},
{
    start: new Date(2025, 0, 7, 0, 0),
    end: new Date(2025, 0, 11, 23, 59, 59),
    resourceId: "bb123ab",
    title: "Event 2"
},
{
    start: new Date(2025, 0, 9, 0, 0),
    end: new Date(2025, 0, 14, 23, 59, 59),
    resourceId: "bb456cd",
    title: "Event 3"
},
{
    start: new Date(2025, 0, 7, 0, 0),
    end: new Date(2025, 0, 10, 23, 59, 59),
    resourceId: "bb789ef",
    title: "Event 4"
},
{
    start: new Date(2025, 0, 11, 0, 0),
    end: new Date(2025, 0, 15, 23, 59, 59),
    resourceId: "bb789ef",
    title: "Event 5"
},
{
    start: new Date(2025, 0, 6, 0, 0),
    end: new Date(2025, 0, 15, 23, 59, 59),
    resourceId: "cc101gh",
    title: "Event 6"
},
{
    start: new Date(2025, 0, 8, 0, 0),
    end: new Date(2025, 0, 11, 23, 59, 59),
    resourceId: "cc123ab",
    title: "Event 7"
}
]

The events can be visualized in this screenshot of my fullcalendar.io timeline chart.

Whenever all motorbikes in a category are fully booked for a certain slot, I’d like to have some red background on the resource level (example here.) That can be easily achieved through background events (https://fullcalendar.io/docs/background-events). My problem is that I haven’t found any way to store the date ranges where the bookings overlap across “n” resources (where “n” is the number of motorbikes in a engine size category) in a reliable and efficient manner.

So far, I have managed to find a semi-working solution by taking the minimum and maximum dates across all events, iterating over them using 30 minutes time frames and storing a background event for the engine category when all its resources are booked at a certain timeslot. Here is the code:

// Get the minimum and maximum date in the events array
minDate = events.map(event => event.start).reduce((a, b) => a < b ? a : b);
maxDate = events.map(event => event.end).reduce((a, b) => a > b ? a : b);

// Iterate between the dates using 30 minutes intervals.
unavailableDateRanges = [];
for (let i = minDate; i <= maxDate; i.setMinutes(i.getMinutes() + 30)) {
    // Filter the events that are happening at this time and get the resources that are being used.
    let usedResources = events.filter(event => event.start <= i && event.end >= i).map(event => event.resourceId);

    // If all resources from a certain category are used, store a 30 minutes unavailable range for that category.
    let unavailableCategories = resources.filter(resource => resource.children.every(child => usedResources.includes(child.id))).map(resource => resource.id);
    for (category of unavailableCategories) {
        let start = new Date(i);
        let end = new Date(i);
        end.setMinutes(end.getMinutes() + 30);
        unavailableDateRanges.push({
            start: start,
            end: end,
            resourceId: category,
            title: "Unavailable",
            display: "background"
        });
    }
}

This does not reliably achieve the desired result since it only checks 30 minutes intervals while a booking could start at a different minutage. Say that a booking starts at 9:45, this code would not mark the period from 9:45 to 10:00 as unavailable. Since the red background would be visible at differnt levels of detail, that will be an issue.

Since dates represent a continuous variable (UNIX), I guess that it could be achievable to filter the events by the parent engine size category and then check what date ranges have an overlap across “n” number of motorbikes, assuming that bookings for a certain motorbike do not overlap (which I’ve already made sure of). I tried to code this solution with no results.

I know that there are some libraries to work with date ranges, like date-fns, but it does not look like it can help.

Can anyone more experienced please help me?

CORS HTTPS withCredentials: true

so basically I am trying to send GET request to by node.js webserver locally hosted but to ensure HTTPS I’m using NGROK.

Here’s the frontend:

$.ajax({
        url: apiPath+'/conf/api/validate-session',
        method: 'GET',
        xhrFields: {
            withCredentials: true
        },
        headers: {
            'Content-Type': 'application/json'
        },
        success: function(data) {
            console.log(data);
        },
        error: function(err) {
            console.error(err);
        }
    });

Here’s the CORS settings of my webserver:

const corsOptions = {
    origin: (origin, callback) => {
        if (allowedOrigins.includes(origin) || !origin) {
            callback(null, true);
        } else {
            callback(new Error('Not allowed by CORS'));
        }
    },
    credentials: true,
    methods: ['GET', 'POST', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
};

app.use(cors(corsOptions));
app.options('*', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', 'https://myfrontend.com');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.setHeader('Cache-Control', 'no-store');
    res.sendStatus(204);
});
app.set('trust proxy', true);

Here are the errors that I’m getting:

[Error] Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.
[Error] XMLHttpRequest cannot load https://mybackend.com/conf/api/validate-session due to access control checks.
[Error] {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function, …}
    error (login.js:115)
    c (jquery.min.js:2:28453)
    fireWith (jquery.min.js:2:29194)
    l (jquery.min.js:2:80212)
    (anonymous function) (jquery.min.js:2:82607)
[Error] Failed to load resource: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true. (validate-session, line 0)

I’m dealing with this 2. day and I don’t know what I am doing wrong. I’ve tested the request localy with curl and it was fine.

Thank you for any help.

I’ve expected to remove the CORS issue

Firebase and Next.js user authentication

I’m creating an app with Next.js and firebase, and I’m using JWT for session persistance for user authentication storage. My question is what really happens when I invoke siginWithEmailAndPassword()? Because, for a good security of my app, I’m trying to execute every operation that request firebase, on my next.js backend.

The function signinWithEmailAndPassword request firebase and return a promise that result in a user, if success. But, readying documentation, for me looks that it executes on navigator, not in backend. I’m trying to get currentUser on getAuth(app).currentUser and it does not works on server.

Therefore, I need a solution to execute operation signin with email and password in firebase and save this state (auth state) locally on the user navigator to get success on signOut function imported from “firebase/auth” or other solution to persist user.

Thank’s, let’s code.

// /database/session-controller.js
import { encrypt } from “@/utils/jwt-lib.js”
import { siginWithEmailAndPassword, signOut, getAuth } from  ‘firebase/auth’
import  { auth } from “@/database/firebase-config.js”

export async function login(email, pwd){
   try {
       const user = await signinWithEmailAndPassword(auth, email, pwd)
       .then(user=>{
           return user;
       }

       cookies().set(“user”, encrypt({user: user}), {httpOnly: true});

   } catch (err) {
       return false
       console.log(err)
   }
   
}

export async function logout(){
   //??
   // sigOut(getAuth(app)) ???
}

I write this code by my memory without my pc, please replace the imports with the correct, if some of them are incorrect. Thanks!