Generate WordPress JWT User Token without credentials

**Retrieve user token **

In my case, I want to recover the WordPress Authentication Token from my logged in user.

To recover this token, I use the plugin jwt-authentication-for-wp-api

Lien plugin : https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

Here are the two endpoints proposed by the plugin that interest us:

This endpoint allows us to retrieve the token, using username' and password’

  • https://instance.fr/wp-json/jwt-auth/v1/token?username=username&password=password

This endpoint allows us to validate the token that we have just recovered

  • https://instance.fr/wp-json/jwt-auth/v1/token/validate?token

I already have a Javascript script that allows me to retrieve the token with my account credentials, and then use the latter to have the token validation message, which I put in the files of my wordpress theme. Here is the file path of the active theme on my WordPress instance:

  • instance.fr/httpdocs/wp-content/themes/astra-child/js/script.js

For now, I do everything in a test instance.

First, I retrieve the variables of the connected user from the filefunctions.php of the active theme.
instance.fr/httpdocs/wp-content/themes/astra-child/functions.php

functions.php

function transformation_variables_wp()
{
    $current_user = wp_get_current_user();

    wp_enqueue_script('transformation_variables_wp', get_stylesheet_directory_uri() . '/js/script.js');
    wp_localize_script('transformation_variables_wp', 'my_script_var_wp', array(
        'prenom_wp' => $current_user->user_firstname,
        'nom_wp' => $current_user->user_lastname,
        'courriel_wp' => $current_user->user_email,
        'username_wp' => $current_user->user_login,
    ));
}

add_action('wp_enqueue_scripts', 'transformation_variables_wp');

I then transform these variables into Javascript, so that I can manipulate them in my script below.

script.js

// ---------------- User variables retrieved in WordPress --------------------
        var prenom_e = my_script_var_wp.prenom_wp;
        var nom_e = my_script_var_wp.nom_wp;
        var courriel_e = my_script_var_wp.courriel_wp;
        var username_e = my_script_var_wp.username_wp; //
        
        
        // --- Transformation de variables --- //
        const firstname = prenom_e;
        const lastname = nom_e;
        const email = courriel_e;
        const username = username_e; //
        const password = "password"; //

        // --------------Variables------------------------------
        const urlInfoClient = "https://www.instance.fr";
        // -----------------------------------------------------

        // ---------------- API Environment URL's --------------------
        const urlGetToken = "https://instance.fr/wp-json/jwt-auth/v1/token";
        const urlValidateToken = "https://instance.fr/wp-json/jwt-auth/v1/token/validate";
        // -----------------------------------------------------

        async function GenerateToken() { 
            console.log(" ");
            console.log("GenerateToken() function");
            const res = await fetch(
                urlGetToken + `?username=${username}`+`&password=${password}`, 
                {
                    method: 'POST',
                    headers: {
                        "Content-type": "application/json; charset=UTF-8"
                    }
                }
            );

            if (res.status !== 200) {
                throw new Error(`Impossible de récuperer le token`);
            }
            let data = await res.json();
            console.log(data);
 
            if (data && data.token) {
              letoken = data.token 
            } else {
              console.log("La propriété 'token' n'existe pas dans la réponse JSON.");
            }
            
        }           

        async function UseToken() { 
            console.log(" ");
            console.log("UseToken() function");
            var token = letoken; 

            const res1 = await fetch( 
                urlValidateToken + `?${token}`, 
                {
                    method: 'POST',
                    headers: {
                        "Content-type": "application/json; charset=UTF-8",
                        "Authorization": `Bearer ${token}`
                    }
                }                
                );

            if (res1.status !== 200) { //
                throw new Error(`Impossible de récuperer le token`);
            }

            let data1 = await res1.json();
            console.log(data1);
            return data1;

        }

                // ---------------------actions------------------

        window.addEventListener('DOMContentLoaded', (event) => {
            document.getElementById("auth_button").onclick = function () {                
                GenerateToken()
                .then(() => UseToken())
                .catch((erreur) => {
                    console.error(erreur);
                });
        }});

When I click the button, the console generates these results:

GenerateToken() function
{token: ‘token_generated’, user_email: ‘[email protected]’, user_nicename: ‘stackov’, user_display_name: ‘Stack Overflow’}

UseToken() function

code: “jwt_auth_valid_token”
data:{status: 200}

I put the password in the Javascript script variables, to make the token generation function work.

But I want to recover the login token, without having to enter the password in my request. My goal is to retrieve the token variable from the JSON reponse, and use it to connect to another instance, which is not a WordPress instance. This token will bridge between my WordPress instance and the other instance. For now I have not found secure ways to do so.

Thank you all.
I remain available for more information

Dynamics 365: Page reload after setTimeout

I have a scenario in Quote form, where when the record is on a status, to display a Progress Indicator, but when status changes (from another procedure), this indicator must close.

function showIndicator(executionContext){
    var formContext = executionContext.getFormContext();
    var status = formContext.getAttribute('statuscode').getValue();
    var message = 'Quote is being processing'
    if(status == 493430001){
        Xrm.Utility.showProgressIndicator(message);
        setTimeout(function () {
                //Refresh Form
                formContext.data.refresh(false);
                });
        }, 3000);
    }else{
        Xrm.Utility.closeProgressIndicator();
    }
}

This function executes on load of the page. I want to refresh page after 3sec and check again the status of the record, if it’s still processing, to display the message, and then again refresh after 3sec

How can i make conference call In twilio by using @twilio/voice-sdk packege in react

Every time i try always Call disconnect.

I can able to make voice call by
params = {
To: number,
From: “+XXXXXXXXXXXX”,
}

const twilioCall = await device.connect({params});
But how can I Make Conference call.
I tryed
const twilioCall = await device.connect({To: conference:${sessionIDD}});
const twilioCall = await device.connect(params:{{To: conference:${sessionIDD}}});
const twilioCall = await device.connect({params:{conference:sessionIDD}});

But Every time i try Call disconnect

NextJs app giving Page not found after deployed but locally it works perfectly

As the title says, I recently deployed my app using Railway. I used railway before since am familiar with it and its easy to manage it.

When I deployed my next js app I am having the page not found error even though locally when I run it works. I read some documentation about possible migration of pages and app but I couldn’t figure out how to fit that with my app. Also I am new to next js so maybe someone can help me out here?

This is how my folder structure looks like:
enter image description here

And on railway everything checks out, I have no errors or warnings.

Thank you in advance

I excpect the app the run normally and for my page to be visible when its runing in production.

Images Not Displaying on Mobile and Tablet, Text and Header Do Not Update When Banners Change

I’m encountering an issue with my website where the images aren’t displaying on mobile and tablet devices. Additionally, when I switch between different banners (tabs), the associated text and header do not update as expected.

Here is the code:

   <style>
        @media screen and (max-width: 1024px) {
            body {
                margin: 0;
                font-family: 'Nunito Sans', sans-serif;
            }

            .slideshow-container {
                width: 100vw;
                height: 100vh;
                position: relative;
                overflow: hidden;
                background-color: #000;
            }

            .slide {
                width: 100%;
                height: 100%;
                opacity: 0;
                visibility: hidden;
                position: absolute;
                top: 0;
                left: 0;
                transition: opacity 0.5s ease-in-out;
            }

            .slide.active {
                opacity: 1;
                display: inline;
            }

            .slide img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }

            .gradient-overlay {
                width: 100%;
                height: 100%;
                position: absolute;
                top: 0;
                left: 0;
                background: linear-gradient(to top, rgba(0, 0, 0, 0.5) 1%, transparent 25%);
                z-index: 2;
            }

            .tab-banners-horizontal {
                position: absolute;
                bottom: 10px;
                left: 50%;
                transform: translateX(-50%);
                display: flex;
                justify-content: space-around;
                align-items: center;
                z-index: 99;
            }

            .tab-banners-horizontal .tab-banner {
                padding: 10px 10px;
                cursor: pointer;
                color: #A4A4A4;
                transition: all 0.3s ease;
                font-size: 20px;
                font-weight: 400;
            }

            .tab-banners-horizontal .tab-banner.active {
                color: white;
            }

            .tab-banner.inactive {
                color: #A4A49B;
            }

            /* Stil for tekstseksjonen */
            .text-section {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                color: #fff;
                text-align: center;
                padding: 10px;
                max-width: 400px;
                z-index: 99;
            }

            .text-section h1 {
                font-size: 35px;
                line-height: 45px;
                font-family: 'Nunito Sans'!important;
                font-weight: 400;
                margin: 0;
                color: white;
            }

            .text-section p {
                font-size: 18px;
                line-height: 26px;
                margin: 10px 0;
                color: white;
            }

            .arrow-icon {
                background-image: url('');
                background-size: contain;
                background-repeat: no-repeat;
                width: 60px;
                height: 60px;
                cursor: pointer;
                position: absolute;
                bottom: 10px;
                left: 50%;
                transform: translateX(-50%);
            }

            .logo {
                position: absolute;
                top: 10px;
                left: 50%;
                transform: translateX(-50%);
                z-index: 100;
            }

            .logo img {
                width: 180px;
                height: auto;
            }
        }
    </style>

    <body>
    <div class="logo">
        <img src="">
    </div>

    <div class="slideshow-container">
        <div class="gradient-overlay"></div>
        
        <div class="slide" id="seil">
            <img src="">
        </div>
        <div class="slide" id="solseil">
            <img src="">
        </div>
        <div class="slide" id="rigg">
            <img src="">
        </div>
    </div>
    
    <div class="text-section">
        <h1 id="image-title">Tittel for valgt bilde/tab</h1>
        <p id="image-text">Dette er teksten som tilhører valgt tab/container.</p>
        <div class="arrow-icon" id="image-arrow"></div>
    </div>

    <div class="tab-banners-horizontal">
        <div class="tab-banner active" id="seil-banner">
            Seil
        </div>
        <div class="tab-banner" id="solseil-banner">
            Solseil
        </div>
        <div class="tab-banner" id="rigg-banner">
            Rigg
        </div>
    </div>

   <script>
    document.addEventListener("DOMContentLoaded", function () {
    const slides = document.querySelectorAll(".slide");
    const banners = document.querySelectorAll(".tab-banner");
    const imageTitle = document.getElementById("image-title");
    const imageText = document.getElementById("image-text");
    const arrowIcon = document.getElementById("image-arrow");

    const slideData = [
        {
            title: "Seil",
            text: "Seilservice er stolte representanter av OneSails og produserer kvalitetssikre seil i hele Norge – og verden. Ved å tilby turseil, jolleseil, regattaseil og service sørger vi får at du alltid er en bølge foran!",
            link: ""
        },
        {
            title: "Solseil",
            text: "Vi leverer både små og store solseil og seilløsninger til privat og næring. Solseil er en videreutvikling av seil og brukes i det daglige for å oppgradere estetikken i tilværelsen din, samtidig som du sørger for god beskyttelse mot omgivelsene. Ta kontakt med oss i dag for å finne din løsning.",
            link: ""
        },
        {
            title: "Rigg",
            text: "Vi streber etter å gi deg en pålitelig rigg som gir deg full kontroll og maksimal ytelse på vannet. Vi benytter kun materialer av høyeste kvalitet og våre produkter er designet for å vare. Vårt erfarne team står alltid til din disposisjon for reparasjoner og vedlikehold av riggen din, slik at du kan fortsette å nyte seilingen uten bekymringer.",
            link: ""
        }
    ];

    let currentSlideIndex = 0; // Store the index of the current slide

    const imagePreloads = [];
    for (let i = 0; i < slides.length; i++) {
        imagePreloads[i] = new Image();
        imagePreloads[i].src = slides[i].querySelector("img").src;
    }

    function updateSlideInfo(slideIndex) {
        imageTitle.textContent = slideData[slideIndex].title;
        imageText.textContent = slideData[slideIndex].text;
        arrowIcon.setAttribute("data-link", slideData[slideIndex].link);
    }

    function showSlide(slideIndex) {
        slides[slideIndex].style.opacity = 0; // Set initial opacity to 0
        slides[slideIndex].style.visibility = "visible"; // Set visibility to visible
        updateSlideInfo(slideIndex);

        // Use setTimeout to trigger the fade-in effect
        setTimeout(function () {
            slides[slideIndex].style.opacity = 1; // Set opacity to 1 for fade-in
        }, 5);
    }

    banners[0].classList.add("active");
    showSlide(0);
   });
   </script>

What I’ve Tried:
I’ve checked that the image paths are correct.
I’ve tested the site on multiple mobile and tablet devices with the same result.
The text and header do not update when I switch between banners.

Expected Behavior:
I expect the images to display correctly on mobile and tablet devices. Additionally, when I switch between different banners, I want the text and header to update to match the selected banner.

Any help or insights on what could be causing this issue would be greatly appreciated. Thank you!

Folder heirarchy using just html and javascript

i’m trying to make a vs code like folder heirarchy structure by just using html and vanilla javascript

something like this

But i’m finding it hard to

  • push new folders and files into deeply nested objects
  • Vice-Versa getting them out of objects to be rendered into the DOM

Problem is

  • if there’s a folder inside another folder i cannot push a file into it
const folderStruture = document.querySelector('#root')
const name = document.querySelector('#add-input')
const addBtn = document.querySelector('#add')
const app = document.querySelector('#root')
let fileCounter = 1
let folderCounter = 1
localStorage.setItem('folder', 'root')

const directory = [
    {
        id: 'root',
        name: 'root',
        isFolder: true,
        files: [
            { id: 'fd1', name: 'folder3', isFolder: true, files: [] },
            { id: 'fl2', name: 'file2.js', isFolder: false },
        ],
    },
    { id: 'folder-2', name: 'folder', isFolder: true, files: [] },
]

// update directory object

function createEntry(fName, folderID) {
    for (const dir of directory) {
        if (dir.id === folderID) {
            // file
            if (fName.match(/[.]/g) !== null) {
                dir.files.push({ id: `fl-${fileCounter}`, name: fName, isFolder: false })
                fileCounter++
            }
            // folder
            else {
                dir.files.push({
                    id: `fd-${folderCounter}`,
                    name: fName,
                    isFolder: true,
                    files: [],
                })
                folderCounter++
            }
        } else {
            // file
            // if (fName.match(/[.]/g) !== null) {
            //  directory.push({ id: `fl-${fileCounter}`, name: fName, isFolder: false })
            //  fileCounter++
            // }
            // // // folder
            // else {
            //  // break
            //  console.log('entered else')
            //  directory.push({
            //      id: `fd-${folderCounter}`,
            //      name: fName,
            //      isFolder: true,
            //      files: [],
            //  })
            //  folderCounter++
            // }
        }
    }
}

// add new file or folder

addBtn.addEventListener('click', (e) => {
    createEntry(name.value, localStorage.getItem('folder'))
})

How to render external file/component into my React app?

I want to know how can I render external file/component into my react js app?

I have this file name file.jsx it contain some code:

import React from "react";

 const TestingFile = () => {
    return(
        <div>
            Hello world!
        </div>
    )
 }
 export default TestingFile;

and it is outside my react app. I want it to be render without import stuff…my issue here is that I don’t know how to do it, or is it possible to this kind of rendering?
And this is my React app code:

import  React from "react";
function App() {

  return (
    <React.Fragment>
     <TestingFile />
    </React.Fragment>
  );
}

export default App;

note: My React app and file.jsx stand on different directory!!!

Be able to output or rendering external file/component to the browser interface.

React Class component inside Function component is not re-rendering after state changes

99% of my app is functional components, but there’s a legacy class component (MyPDF) nested inside a functional component (MyApp) that I have to use (it’s too much effort to rewrite the class as a function). There is a state value, url, being passed to the class component from the functional component. However when then url changes in the parent functional component, those changes aren’t propagating down to the class component, and it isn’t re-rendering.

The class component is also written in TypeScript whereas the parent functional component is in JavaScript, if that matters at all.

myapp.js

import React, { useState } from "react";
import MyPDF from "./mypdf.tsx";

function MyApp() {
  const [url, setURL] = useState("https://initialpdf.com");
  const onClick = () => {
    setURL("https://newpdf.com");
  };
  console.log("url", url); // this url changes correctly
  return (
    <>
      <h1>This is my app</h1>
      <MyPDF data={url} />
      <p>PDF (Function): {url}</p>
      <button onClick={onClick}>Change URL</button>
    </>
  );
}
export default MyApp;

mypdf.tsx

import React from "react";

interface State {
  url: string;
}
class MyPDF extends React.Component<{}, State> {
  state = { url: "" };
  constructor(props: any) {
    super(props);
    this.state.url = props.data;
  }

  render() {
    return <div>PDF (Class): {this.state.url}</div>; // why isn't this.state.url changing?
  }
}
export default MyPDF;

How can I get the class component to re-render & follow changes in the parent state?

Node.js Socket.io w/ Redis – How to change only a specific key in object?

Clients can create lobbies which are stored into redis in an object { } format. Clients then join/leave the lobbies, which would need updating of only specific keys inside the lobby object.

Specifically here, when a client disconnects, if in a lobby, the server registers the information by get the entire LOBBY_LIST, updating a small part delete json[user.currentLobby].users[socket.id] then set stores the entire LOBBY_LIST back into the database. This seems to be both sloppy and incorrect, and is already giving me problems.

What’s the correct way of implementing a function such as this?

socket.on( 'disconnect', async ( ) => {
    try {
        console.log(`x1b[33m[Worker${process.pid}]x1b[0m ${user.id} disconnected` );
        
        if( !user.currentLobby ) return;
        
        const LOBBY_LIST = await storeClient.get( 'LOBBY_LIST' );
        var json = JSON.parse( LOBBY_LIST );
        
        if( json[user.currentLobby] == null ) return;
        
        delete json[user.currentLobby].users[socket.id];
        
        if( Object.keys( json[user.currentLobby].users ).length == 0 ) delete json[user.currentLobby];
        
        storeClient.set( 'LOBBY_LIST', JSON.stringify( json ) );
        socket.emit( 'serverJoinLobby', 'success' );
    }
    catch( e ) {
        console.log( e );
    }
});

Each lobby’s object

const lobby = {
    name: data.name,
    map: data.map,
    type: data.type,
    userMax: data.userMax,
    users: { }, // holds room's client's socket.id
    host: socket.id
};

Puppeteer to fill username password details on the alert dialog

I am using puppeteer for taking screenshots for some sites periodically. These sites require login before entering which i did for the few sites where html content is loaded by examining the input name, class elements but i came across one site where html content is not loaded and i am shown an alert box for entering username and password. I am attaching image here on the screen.

Site having alert box for entering username and passowrd

Can anyone please guide me how to enter username password details on the alert box using puppeteer?

I tried using page.authenticate method of puppeteer but it didn’t work for me.

await page.authenticate({ username, password, });

I am unable to find input username and password elements otherwise i would have used the following:-

 const usernameInput = await page.$('input[name="username"]');
  const passwordInput = await page.$('input[name="password"]');
  const loginButton = await page.$("button.tb-button-login");
await usernameInput.type(username);
    await passwordInput.type(password);
    await loginButton.click();

how let. Cumulative blood loss. ( javascirpt ) [closed]


             var pikachu = { 
                hp: [194,194], 
                mp: [129,129], 
                def: 20, 
                atk: 30,
  
              
              var  charmander =
              {
                hp: [194,194], 
                mp: [129,129], 
                def: 20,
                atk: 30,




let  battle = (x,y) =>{      

              
 {
             while ( x <= y)
       
             var  z = x - y;
             var  x = z;

              console.log(z);
                }

            } 


battle(charmander.hp[1],pikachu.atk);

        }

        )

it seem is right ,and no got error, but why it can not Cumulative blood loss?
it only got one times of blood loss

how let hp Cumulative blood loss?thanks

i want do a like Pokémon game in the net,

Handling client disconnect/abort during streaming response in `Deno.serve`

I have some Deno server code that looks roughly like this:

Deno.serve((req) => {
  let asyncIterator = getChunkIterator(req.url);

  const stream = new ReadableStream({
    async pull(controller) {
      try {
        const { value, done } = await asyncIterator.next();
        if (done) {
          controller.close();
          return;
        }
        controller.enqueue(value);
      } catch (err) {
        controller.error(err);
      }
    }
  });
  
  let response = new Response(stream);
  return response;
});

The response streaming can take several seconds, and the client may disconnect half-way through. I need to detect this so that I can stop the (separate) “worker” server that is producing the chunks of data for that client.

I have no idea how to do this, since with Deno.serve you just return the Response object, rather than being given a stream to write to.

How do I read a value from a Realm database when a React Native app starts up?

I am new to Realm and trying to read from the database.

I made an object schema called _AppRegistry which will have a single entry. If that entry exists, the app has been loaded before. If it does not, then the app does not need to be loaded.

I have been following the Quick Start guide for making the app, and I am stuck getting making the function that goes inside the RealmProvider tags.

My understand from the Quick Start guide is that I make a new function and put a tag inside my RealmProvider tags that match the function name, then the code should just return from there.

However, I am getting the following error:

ERROR  Invariant Violation: View config getter callback for component `initialiseApp` must be a function (received `undefined`). Make sure to start component names with a capital letter.
 
 This error is located at:
     in initialiseApp (created by App)
     in Unknown (created by App)
     in RCTView (created by View)
     in View (created by App)
     in App
     in RCTView (created by View)
     in View (created by AppContainer)
     in RCTView (created by View)
     in View (created by AppContainer)
     in AppContainer
     in ps2319(RootComponent), js engine: hermes

How do I connect to and read from the Realm database in my app?

Below is my main app function that I export as default

const App = () => {
    //initDB();
    
    const {RealmProvider, useRealm, useObject, useQuery} = createRealmContext({schema: [_AppRegistry, Attachments, ReceiptAttachments, Receipts, ReceiptTags, Tags]});
    return (
        <RealmProvider>
            <initialiseApp />
        </RealmProvider>
    );
    
};

// Other code...

export default App;

And my initialiseApp function looks like this:

function initialiseApp() {
    const appRegistry = useObject(_AppRegistry, 0);
    if(appRegistry == null){
        return(
            <View>
                <Text>App Registry is not set up!</Text>
            </View>
        );
    }else{
        return(
            <View>
                <Text>App Registry is set up!</Text>
            </View>
        );
    }
}

AppScript UserProperties within cell vs from menu

I’m developing an AppScript, and I’ve noticed some strange behavior regarding UserProperties.
I have the followng function that is triggered by a menu button:

function inputApiKey() {
  var ui = SpreadsheetApp.getUi();
  var apiKeyValue;
  if (!!PropertiesService.getUserProperties().getProperty(API_KEY)) apiKeyValue = ui.prompt('Your current API Key is:n' + PropertiesService.getUserProperties().getProperty(API_KEY) + 'nnEnter your new API Key below:n', ui.ButtonSet.OK);
  else apiKeyValue = ui.prompt('Add your API Key here:n', ui.ButtonSet.OK);
  if (apiKeyValue.getResponseText()) PropertiesService.getUserProperties().setProperty(API_KEY, apiKeyValue.getResponseText());
}

Now let’s say the spreadsheet was created by User 1, and User 1 uses the above function to input an API key. Then suppose User 1 shares the sheet with User 2, and User 2 inputs a separate API key.

Now suppose I have a second function:

function MyApiKey() {
  return PropertiesService.getUserProperties().getProperty(API_KEY);
}

If User 1 calls this function from a menu button, it returns User 1’s API key. If User 1 calls this function from within a cell, it returns User 1’s API key.

If User 2 calls this function from a menu button, it returns User 2’s API key. But if User 2 calls this function from within a cell, it returns User 1’s API key.

Can someone help me understand why this is happening and how to resolve it?