JWT verification with hose is failing

I have the following Next.js/Clerk.js middleware:

import { authMiddleware } from "@clerk/nextjs";
import { jwtVerify } from "jose";

export default authMiddleware({
  publicRoutes: ["/", "/contact", "/pricing", "/api/webhooks/user", "/api/reviews/add", "/api/user"],
  afterAuth (auth, req, evt) {
    const secret = new TextEncoder().encode (process.env.CLERK_PUBLIC_KEY)
    const decoded = jwtVerify ("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJkZXYiOiJkdmJfMlpFZkVyUG91dHBuaFptQXZzdk0zMkVadkVhIiwiaWQiOiJjbGllbnRfMlpFZkpieUFQUXRWbVB4Q3R2SER4SE04a2tCIiwicm90YXRpbmdfdG9rZW4iOiJmaWNid25rZDE0aTVpNm5rZzJicjc1ODl5NWZqeGloemloZDk2dnprIn0.qURs213vHtEe_2DTmOVN8jCPCJhQfIIEjWLMIXgIVYs86U1J3P5BV9EHexjvXda416D4wHAFdxUhUzjKj42CNM4TYTrrsXRT4m_fMNq78NrvwMf7ge2tmcSYNf04c7gqInQzJMNiKILZbQXN0yxExZ1lBbPesg-ZCsx5HZ1544-g0yrcZvxu7HkSwIG56C3ITae51rtMj4lpxyYUxdR9MZ0JZ-HH2XlCT_F3BMDUn_IHNXj2IDF6gI-1kx3UWwYZ5uCyTipbsuOwgFCINFA2m8h3IM0jS9KXGLNrixaej9M0uDEcYkxVRvSwNKJfeHmnhJefYEk82192XpmXJDft8Q", secret)
    console.log(decoded)
  }
});

export const config = {
  matcher: ["/((?!.*\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};

I’m using hose to verify a the JWT. But when the middleware is called I get an error:

Promise {
  [Symbol(async_id_symbol)]: 290979,
  [Symbol(trigger_async_id_symbol)]: 290975,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: {
  headers: [Getter],
  cookies: [Getter],
  mutableCookies: [Getter],
  draftMode: [Getter]
}
}
TypeError: Key for the RS256 algorithm must be of type CryptoKey. Received an instance of Uint8Array

What’s wrong here?

Google map marker auto update

I have a requirement in javascript, where I’m able to display a google map with multiple cars (all appearing in one direction) appearing in their current lat/lng, after a minute or so the cars might change its lat/lng co ordinates that needs to be updated automatically on screen’s google map without having to refresh the page. Also the car appearance might change either to car moving to west or east or south or north.

I’m looking for similar uber drivers map.

My progress is I’m able to read all cars lat/lng from database, create markers on map then display the map. Challenge is updating lat/lng of cars when they change, that must update their lat/lng on map as well.

For example Car A is appearing at co-ordinate 22.322/-83.3223 after 15 seconds Car A moved 100 meters now it has new co-ordinate that must reflect on map.

Any feedback is appreciated.

I don’t know what to try.

Is it possible to use wifi direct via JavaScript?

I would like to develop a web application on which users can exchange their photos via WiFi direct. I assume that the usage environment has only poor internet connection, so the image files can’t be tramsferred via the internet. The webserver provide a webpage which is similar to the Airdrop of apple device, but I wanna add some functions, and connect with different type of devices like iOS and Android.
To develop such webapp, I think the Javascript API of WiFidirect is needed, but I couldn’t find such thing. Isn’t it possible to use WiFidirect via JavaScript?

Firebase Auth returning 400 (Bad Request) when signing in

In my app, whenever the user tries to sign in using an email and password that does not exist in the system. I receive a 400 error. The 400 error only occurs when I have an @ symbol in the email input.
Here is the error: Full Error Log

Here is my code:

const loginForm = document.querySelector('#login');

loginForm.addEventListener("submit", e => {
        e.preventDefault();
        const email = document.querySelector("#login #email").value;
        const password = document.querySelector("#login #password").value;
        console.log(email, password);
        // Perform Login
        auth.signInWithEmailAndPassword(email, password).then((userCredential) => {
            console.log('User sign in successful');
            // userCredential has userID, email, display name
            setFormMessage(loginForm, "success", "");
        }).catch((error) => { 
            var errorCode = error.code;
            var errorMessage = error.message;
            setFormMessage(loginForm, "error", errorMessage);
        });
        
    });

I have enabled email / password in the firebase project as a sign-in method. I also get another 400 error when creating a new account with an existing email. I don’t think it should be a 400 error because when the input has no @ symbol, the error is just a normal auth error and doesn’t show an error in the console. Need some help! thank you.

Overlay element over video, img, or iframe, but do not stop onClick event propagation

I have a component that, depending on the content, displays either a <video>, an <img>, or an <iframe>.

I need to show a close button when the screen is tapped. I have an effect that listens for clicks and toggles the visibility of the close button.

The effect works fine, but I’m running into issues when attempting to maintain both that behavior and using the built-in controls for these playback components.

I’ve made two somewhat successful attempts, but they both have drawbacks.


First attempt:

Solution: Set the height of the <video>, <img>, or <iframe> to only a portion of the screen’s available height.

Behavior: Any click on the playback component will show their controls (but will not show my close button, since the playback component consumes the click). Any click on the rest of the screen will show my close button.

Drawbacks: I would rather the playback component take up the entire height. It’s not intuitive that clicking on only a portion of the screen will bring up the close button, and it doesn’t look as good. I don’t want to always show the close button either.


Second attempt:

Solution: Overlay another element over the entire screen.

<>
    <div
        style = {{
            position: 'relative',
            width: '100%',
            height: '100%',
            zIndex: 101
         }} />
            
    <video
        ...
        controls = {true}
        height = '100%'
        width = '100%'
        style = {{ position: 'absolute', zIndex: 100 }} />
</>

Behavior: Any click on the screen will show my close button.

Drawback: The playback controls will never show, since my overlay consumes the click.


Ideal behavior:

The playback components take up the entire screen’s height and width. Any click anywhere on the screen shows the built-in controls and also my close button.

Is there any way to accomplish this? I haven’t been able to find much, other than building my own playback controls. I really want to avoid this if possible, especially because it’s not going to work with the iframe, and I want a consistent approach to all three if possible.

How to convert React Component with dynamic states to html

I’m trying to convert a react component to html, so I can send it to a .pdf generator.
There’s many posts on generating html from components, but none address the case where the data inside the component is dynamic.

here’s my best attempt:

//createHtml.js

//imports omitted
export function someOtherComponent(){

function createHtml(){
 return renderToStaticMarkup(
          <dataProvider>  
 //doesnt work, it creates a new instance of dataProvider with no mydata
            <myComponent />
          </dataProvider>
        )
}
return (    <someButton onclick=createHtml>   )
}

It shows nothing. This is because there’s no context provider (I think). mydata doesn’t exist.
I tried rendering the context provider but that creates a new instance of the provider. mydata doesn’t exist there. Its only in the original provider.

Anyone have any ideas? I’d hate to delete all these components and generate an html string using vanilla javascript.

Any help is appreciated.

Here’s my components and stuff in case it helps (pseudocode, obviously):

//myComponent.js

import {getData} from 'dataProvider'
export function myComponent(props) {
    const { mydata } = getData();
    //just display some dynamic data
    return (    <div>    {mydata}    </div>    )
}

heres the context provider:

//dataProvider.js
const dataContext = createContext();

export default function datatProvider({ children }) {
  const [mydata, setData] = useState([]);
  const { Provider } = dataContext;
  return <Provider value={mydata}>{children}</Provider>;
}
export function getData() {
  return useContext(dataContext);
}

and then I have some startup code that populates mydata

//startup.js
import {getData} from 'dataProvider'
function startup(){
     const { setData } = getData();
     //load data from DB
     setData(res.data);
    
}

I’ve ommited all the react imports and stuff, for clarity.

how to be a good freelancer developer looking for detaile and road map (explained more) [closed]

i just wanna know what should i do after learning html css ?(my target is giving project and working in freelancer )
let me know about details guide me to prevent wasting time ?

im learning java script base give me lead to know which framework which library?
Tell me some topics to learn so that I can get a project more easily šŸ˜€
thank you

Is using getValue() on BehaviorSubject bad practice?

Ben Lesh and Angular University have contradictory stands on BehaviorSubject.

I am confused about the following. I have read from Ben Lesh himself that using getValue() on a behavior subject is a huge code smell.

He said this:

The only way you should be getting values “out of” an Observable/Subject is with subscribe!

If you’re using getValue() you’re doing something imperative in
declarative paradigm. It’s there as an escape hatch, but 99.9% of
the time you should NOT use getValue().

However, in this blog article from Angular University, I have read this:

Subject has one particularity that prevents us from using it to build
observable data services: if we subscribe to it we won’t get the last
value, we will have to wait until some part of the app calls next().

This poses a problem especially in bootstrapping situations, where the
app is still initializing and not all subscribers have registered, for
example not all async pipes had the chance to register themselves
because not all templates are yet initialized.

The solution for this is to use a BehaviorSubject. [Using getValue]
makes the BehaviorSubject the heart of the observable data service.

Can someone please clarify these obviously contradicting stands?

Please note that I am not asking for an opinion. The concept of a data service with RxJS is a standard way of managing state. I am asking only asking for a clarification on these two condradictions.

Input time save hour and minute in separate ids

I have a question, would it be possible to use input type=”time” to send separate information.
Example hour to id=”hour” minute to id=”minute”

I have code in which I would need this function.
It would be something like scheduling a function in the system.
Hour and minute.

`if($dados_agendamento[“frequencia”] == “1”) {

$descricao = “”.$lang[‘lang_info_gerenciador_agendamentos_info_frequencia1’].” “.$data.” “.$dados_agendamento[“hora”].”:”.$dados_agendamento[“minuto”].””;

} elseif($dados_agendamento[“frequencia”] == “2”) {

$descricao = “”.$lang[‘lang_info_gerenciador_agendamentos_info_frequencia2’].” “.$dados_agendamento[“hora”].”:”.$dados_agendamento[“minuto”].””;`

$descricao = "".ucfirst($dados_acao["acao"])." ".substr($lista_dias, 0, -2)." ".$dados_acao["hora"].":".$dados_acao["minuto"]." ".$playlist."";

A informação hora e minuto fica armazenado no banco se alguém puder ajudar

enter image description here

Hello, I have a question, would it be possible to use input type=”time” to send separate information.
Example hour to id=”hour” minute to id=”minute”

I have code in which I would need this function.
It would be something like scheduling a function in the system.
Hour and minute.

if($dados_agendamento["frequencia"] == "1") {

$descricao = "".$lang['lang_info_gerenciador_agendamentos_info_frequencia1']." ".$data." ".$dados_agendamento["hora"].":".$dados_agendamento["minuto"]."";

} elseif($dados_agendamento["frequencia"] == "2") {

$descricao = "".$lang['lang_info_gerenciador_agendamentos_info_frequencia2']." ".$dados_agendamento["hora"].":".$dados_agendamento["minuto"]."";
$descricao = "".ucfirst($dados_acao["acao"])." ".substr($lista_dias, 0, -2)." ".$dados_acao["hora"].":".$dados_acao["minuto"]." ".$playlist."";

The hour and minute information is stored in the bank if anyone can help

enter image description here

JSON decode with php [duplicate]

I have error when try to get “rate” data from JSON ({"code":"USD","name":"US Dollar","rate":76.63})

<?php
$tick = file_get_contents('https://bitpay.com/rates/ltc'); 
$data = json_decode($tick, TRUE);
$LTC = ($data["rate"]);
echo $LTC;
?>

Pleas help, where is error ?

Script for tabs

how can I write a script for a browser game so that two tabs of this game are in the same tab and you can switch between them with one button, what programming language is needed to write such a script and how much time will it take to develop?

I tried to do it through an iframe, but nothing worked

why do i keep getting an error message with my javascript

I keep getting the error message:

 store.js:102  Uncaught TypeError: Cannot set properties of undefined (setting 'innerText')
    at updateCartTotal (store.js:102:70)
    at HTMLButtonElement.removeCartItem (store.js:41:5)
updateCartTotal @ store.js:102
removeCartItem @ store.js:41

it doesn’t update the total cart price

The java script is as follows

function updateCartTotal() {
    var cartItemContainer = document.getElementsByClassName('cart-items')[0]
    var cartRows = cartItemContainer.getElementsByClassName('cart-row')
    var total = 0
    for (var i = 0; i < cartRows.length; i++) {
        var cartRow = cartRows[i]
        var priceElement = cartRow.getElementsByClassName('cart-price')[0]
        var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
        var price = parseFloat(priceElement.innerText.replace('$', ''))
        var quantity = quantityElement.value
        total = total + (price * quantity)
    }
    total = Math.round(total * 100) / 100
    document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total

Continue has no effect in for loop?

I’m a beginner trying to solve this kata:

In this kata you are required to, given a string, replace every letter
with its position in the alphabet.

If anything in the text isn’t a letter, ignore it and don’t return it.

“a” = 1, “b” = 2, etc.

My solution seems to be working until it encounters a whitespace in the given string, then it includes those as an element of the positions array. I know this is probably fixable by just filtering out the whitespaces but I would really like to know why my code isn’t working.

function alphabetPosition(text) {
  const alphabet="abcdefghijklmnopqrstuvwxyz".split('');
  const letters = text.toLowerCase().split('');
  let positions =[];
  for (i=0; i<letters.length; i++){
    if (!(alphabet.includes(letters[i]))){
      continue;
      }
      positions[i]=(alphabet.indexOf(letters[i])+1);          
    }
  return (positions.join(' '));  
}

I thought by using continue, it should just skip over the whitespaces within the letters array but the continue keyword seems to not have any effect.
I have tried to look up the correct use of continue and really can’t find my mistake.
Any help would be much appreciated, thanks in advance!

Match error: received value must be a mock or spy

Here is my function:

const download = async (method, url) => {
    // do sth
    setRequest(method, url)
    .then(res => res.blob())
    .then(res => {
        const url = window.URL.createObjectURL(new Blob([res]))
        downloadLink(url)
    }, (error) => {
        // do sth
    }
}

Here is my test:

global.fetch = jest.fn(() => {
    Promise.resolve({
        status: 200,
        ok: true,
        blob: jest.fn()
    })
})


test("test", async () => {
    jest.mock("../setRequest", () => jest.fn(async () => Promise.resolve({blob: jest.fn()})))
    jest.spyOn(downloadLink).mockImplementation(() => console.log("test"))

    await download("GET", "correctUrl");

    expect(setRequest).toHaveBeenCalled();
    expect(downloadLink).toHaveBeenCalled();
})

I would like to check if either setRequest/downloadLink has been called:

  • first expect statement results in this error: Match error: received value must be a mock or spy.
  • second expect statement results in 0 calls being made instead of 1.

How to fix: Firebase: Bad access token: {“code”:190,”message”:”Bad signature”} (auth/invalid-credential) in react native

I am trying to authenticate with facebook login in react native and getting this error below on all IOS Device using the module react-native-fbsdk-next

Firebase: Bad access token: {"code":190,"message":"Bad signature"} (auth/invalid-credential)

I tried different facebook accounts and iOS devices, and nothing seems to work.

The App ID and App Secret for facebook matchs in Firebase, and it is working on android device but not iOS devices

Here is the code snippet below

import { AccessToken, AuthenticationToken, LoginManager} from 'react-native-fbsdk-next';
import { getAuth, signInWithCredential,FacebookAuthProvider, } from "firebase/auth";

try {
  const result = await LoginManager.logInWithPermissions(['public_profile', 'email'], 'limited', 'my_nonce');

  if (result.isCancelled) {
    console.log('User cancelled the login process');
    return;
  }

  const data = await AuthenticationToken.getAuthenticationTokenIOS();

  if (!data) {
    throw new Error('Something went wrong obtaining the Facebook access token');
  }

  console.log('Facebook Access Token:', data.authenticationToken);

  const facebookCredential = FacebookAuthProvider.credential(data.accessToken);

  await signInWithCredential(auth, facebookCredential);

} catch (error) {
  console.error('Facebook login error:', error.message);
  // Handle other errors if necessary
}