Flatten/refactor data set for alert array

I am working on a d3.js gannt chart – and I’ve got the following data set coming out – but I need to flatten the array by date, then also group it by type — so there is one entry for the starting/ending time and refactor a tool tip textual parameter that can showcase the grouped information

So like on hovering on a bar — it reads (Device: pH, Humidity)(Report: Swelling)(Clinician Assessment: Pain Level)

What would be the best approach to refactoring this data set to something as mentioned.

let array = [
{text: "pH", starting_time: 1693347129000, ending_time: 1693350729000, type: "device"},
{text: "humidity", starting_time: 1693347129000, ending_time: 1693350729000, type: "device"},
{text: "pH", starting_time: 1693339929000, ending_time: 1693343529000, type: "device"},
{text: "pH", starting_time: 1692958329000, ending_time: 1692961929000, type: "device"},
{text: "humidity", starting_time: 1692958329000, ending_time: 1692961929000, type: "device"},
{text: "pH", starting_time: 1692738729000, ending_time: 1692742329000, type: "device"},
{text: "humidity", starting_time: 1692738729000, ending_time: 1692742329000, type: "device"},
{text: "temperature", starting_time: 1692735129000, ending_time: 1692738729000, type: "device"},
{text: "pH", starting_time: 1692735129000, ending_time: 1692738729000, type: "device"},
{text: "humidity", starting_time: 1692213729000, ending_time: 1692217329000, type: "device"},
{text: "humidity", starting_time: 1692130929000, ending_time: 1692134529000, type: "device"},
{text: "pain level", starting_time: 1695972618000, ending_time: 1695976218000, type: "report"},
{text: "swelling", starting_time: 1695597028000, ending_time: 1695600628000, type: "report"},
{text: "level of pain", starting_time: 1695597028000, ending_time: 1695600628000, type: "clinicianAssessment"}
]

would it be something like this

function alertBreakdown(result){
    let schedule = [...result];

    //flat all the dates to one array
    const timestamps = schedule.flatMap(_ => _.starting_time);

    //flatten also for ending_time? so if same starting/ending time?

    //console.log("timestamps", timestamps);

    //count the occurrences of each date in a dictionary structure
    const day2count = {};
    timestamps.forEach(timestamp => {
        //console.log("--<timestamp", timestamp);
        const day = moment(timestamp).format("YYYY-MM-DD");//.toString().split('T')[0];
        //const day = timestamp.toString().split('T')[0];
        day2count[day] = (day2count[day] || 0) + 1;
    });

    //console.log("day2count", day2count);
       
    // convert the map to an array of entries
    const scheduleResult = Object.entries(day2count).map(([date, value]) => ({date: moment(date), value: value, toolTipText: "test" }))
          .sort((a,b) => moment(a.date) - moment(b.date))

    return scheduleResult;

}

How do I add a border and shadow (or marker) to the head of my animated circle?

So I’m using this component, and I’m trying to figure out a way to make the ring overlap with itself when it overfills (exceeds 100%), but to indicate that we need a border and shadow for wherever the head of the animated ring is. I’ve converted the code into JavaScript, so we need to do this in JavaScript for React Native.

    <Svg
      width={scaledWidth}
      height={scaledHeight}
      viewBox={viewBox}
      style={{ position: "absolute" }}
    >
      <Defs>
        <LinearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
          <Stop offset="0%" stopColor={gradientEndColor} />
          <Stop offset="100%" stopColor={gradientStartColor} />
        </LinearGradient>
      </Defs>
      <G rotation={-90} originX="90" originY="90">
        <Circle
          cx="50%"
          cy="50%"
          r={radius + 5} 
          stroke="black" 
          fill="transparent"
          strokeWidth={11}
        />
        <Circle
          cx="50%"
          cy="50%"
          r={radius}
          stroke={bgColor}
          fill="transparent"
          strokeWidth="19"
        />
        <AnimatedCircle
          cx="50%"
          cy="50%"
          r={radius}
          stroke="url(#gradient)"
          fill="transparent"
          strokeWidth="19"
          strokeDasharray={circleCircumference}
          strokeDashoffset={strokeDashoffset}
          strokeLinecap="round"
        />
      </G>
      {customIcon(radius)}
    </Svg>

I’ve tried making a circle that creates a ball and follows the end of the animated circle, not sure how to do that though. Also I’ve tried to create a marker for strokeLinecap, but I don’t think it supports that.

Basically I’m trying to get this to function exactly like the Apple Activity Rings on the watch. Any help would be greatly appreciated.

Linkedin invalid url when requesting for access token: Nodejs

I’m having a challenge when requesting for linkedin access token for sign in with linkedin product.

> Social [email protected] dev
> node server --watch
http://localhost:3001
error TypeError: Failed to parse URL from POST https://www.linkedin.com/oauth/v2/accessToken?code=AQR_FCYP4tOggx6VpjiWj3gKU8fLKZzloCDcc0BJAifQ1ECmnpgKE8B2aQvvSPol-_VodYfIgAy-fwvSWd48V69c4tTme5mau6U4EPBptZDdjpbrdLmj8rs5cCNTV4eTfngmJgUUlsN2CD1THp34FJ0SK0DzpomMzft0Jgb3ySRCw1mUbJG3kOywbhAwaJQbGjHMA2yWvAuHSWYEm_8&grant_type=authorization_code&client_id=idq&client_secret=secret&redirect_uri=http%3A%2F%2Flocalhost%3A3001%2Fapi%2Flinkedin%2Fredirect
    at Object.fetch (node:internal/deps/undici/undici:11372:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async RedirectHelper (file:///C:/Users/paull/Documents/projects/others/web/web%20servers/sign_with_linkedin/AuthHelper.js:24:18) {
      at new URL (node:internal/url:775:36)
      at new _Request (node:internal/deps/undici/undici:5055:25)
      at fetch2 (node:internal/deps/undici/undici:9195:25)
      at Object.fetch (node:internal/deps/undici/undici:11370:18)
      at fetch (node:internal/process/pre_execution:282:25)
      at RedirectHelper (file:///C:/Users/paull/Documents/projects/others/web/web%20servers/sign_with_linkedin/AuthHelper.js:24:24)
      at file:///C:/Users/paull/Documents/projects/others/web/web%20servers/sign_with_linkedin/server.js:29:14
      at Layer.handle [as handle_request] (C:UserspaullDocumentsprojectsotherswebweb serverssign_with_linkedinnode_modulesexpresslibrouterlayer.js:95:5)
      at next (C:UserspaullDocumentsprojectsotherswebweb serverssign_with_linkedinnode_modulesexpresslibrouterroute.js:144:13)
      at Route.dispatch (C:UserspaullDocumentsprojectsotherswebweb serverssign_with_linkedinnode_modulesexpresslibrouterroute.js:114:3) {
    code: 'ERR_INVALID_URL',
    input: 'POST https://www.linkedin.com/oauth/v2/accessToken?code=AQR_FCYP4tOggx6VpjiWj3gKU8fLKZzloCDcc0BJAifQ1ECmnpgKE8B2aQvvSPol-_VodYfIgAy-fwvSWd48V69c4tTme5mau6U4EPBptZDdjpbrdLmj8rs5cCNTV4eTfngmJgUUlsN2CD1THp34FJ0SK0DzpomMzft0Jgb3ySRCw1mUbJG3kOywbhAwaJQbGjHMA2yWvAuHSWYEm_8&grant_type=authorization_code&client_id=77if1emcoje12q&client_secret=j1N3thirTkhxOVnY&redirect_uri=http%3A%2F%2Flocalhost%3A3001%2Fapi%2Flinkedin%2Fredirect'
  }
}

It throws INVALID URL error but I can’t exactly locate where the exact problem is.

Below is my code:

AuthHelper.js
    import 'dotenv/config';
import querystring from 'node:querystring';

const AuthHelper = () => {
    // client id
    // response type
    // redirect url
    // scope
    // state -optional

    return encodeURI(`${process.env.LINKEDIN_AUTH_URI}?client_id=${process.env.LINKEDIN_CLIENT_ID}&response_type=code&scope=${process.env.LINKEDIN_SCOPE}&redirect_uri=${process.env.LINKEDIN_REDIRECT_URI}`)
}

const RedirectHelper = async(code) => {

    const payload = {
        code,
        grant_type: 'authorization_code',
        client_id:  process.env.LINKEDIN_CLIENT_ID,
        client_secret: process.env.LINKEDIN_CLIENT_SECRET,
        redirect_uri: process.env.LINKEDIN_REDIRECT_URI,
    };

    const data = await fetch(`${process.env.LINKEDIN_ACCESS_TOKEN_URI}?${querystring.stringify(payload)}`,{
        method: 'POST',
        headers: {
            'Content-Type': 'x-www-form-urlencoded'
        }
    })
    .then((response) => {
        console.log("response", response);
        return response.json();
    }).catch((err) =>{
        console.log("error", err);
        return err;
    });

    return data;
}

export {
    AuthHelper,
    RedirectHelper,
};


server.js

import express from 'express';
import { AuthHelper, RedirectHelper } from './AuthHelper.js';


// APP INSTANCE ----------------------------------------------------------------
const app = express();


// APP SETTINGS ----------------------------------------------------------------
app.use(express.json());



const PORT = 3001;
const HOST = 'http://localhost'




app.get('/api/linkedin/authorize', (req, res) => {
    return res.redirect(AuthHelper());
});

app.get('/api/linkedin/redirect', async(req, res) => {
    res.json(RedirectHelper(req.query.code));
});

app.listen(PORT, () => {
    console.log(`${HOST}:${PORT}`);
});

What am I not getting right? I want to add a functionality to enable users of my application to sign in with linkedin.
I’m able to get the linkedin screen for password and allowing the application to access my profile.
I have added the redirect url and also verified the application and counter checked my credentials and they are correct.

I appreciate your help in advance.

webRTC audio – Don’t know how to resume streaming after closing/stoping it

I was trying webRTC for a chatbot with voice prompts. I was successful on incorporating the voice prompts to the chat, but i have a problem. I noticed the mediaRecorder.stop doesn’t stop the streaming, so the red circle in the window will not dissapear. I want it to only be streaming when the user is recording the message.

What i tried:
I searched other solutions and found that this line will successfully end the streaming:
stream.getTracks().forEach( track => track.stop() );

The problem is, I don’t know how to resume the streaming after that, the record button turns unresponsive.

This is my entire code, sorry for not providing a more compact one, i’m not too keen with javascript to leave things behind:

  let mediaRecorder;
  let recordedChunks = [];
  let isRecording = false; // Track the recording state

  // Function to start recording
  function startRecording() {
    if (mediaRecorder && mediaRecorder.state === 'inactive') {
      mediaRecorder.start();
      isRecording = true;
    }
  }

  // Function to stop recording
  function stopRecording() {
    if (mediaRecorder && mediaRecorder.state === 'recording') {
      mediaRecorder.stop();
      isRecording = false;
    }
  }
  // Function to initialize the MediaRecorder
  function initializeMediaRecorder() {
    if (!mediaRecorder) {
      // Initialize the MediaRecorder with audio constraints
      navigator.mediaDevices
        .getUserMedia({ audio: true })
        .then((stream) => {
          mediaRecorder = new MediaRecorder(stream);

          // Add data to the recordedChunks array when data is available
          mediaRecorder.ondataavailable = (e) => {
            if (e.data.size > 0) {
              recordedChunks.push(e.data);
            }
          };

          // When the recording is stopped, you can process the recorded data
          mediaRecorder.onstop = () => {
            const audioBlob = new Blob(recordedChunks, { type: 'audio/wav' });
            const audioSize = audioBlob.size;
            recordedChunks = [];

            // Example: Send the audio data to the server or do something else with it
            const messageItem = document.createElement('li');
            messageItem.classList.add('message', 'sent');
            messageItem.innerHTML = `
                <div class="message-text">
                    <div class="message-sender">
                        <b>You</b>
                    </div>
                    <div class="message-content">
                        Audio size: ${audioSize}. Recording state: ${mediaRecorder.state}
                    </div>
                </div>`;
            messagesList.appendChild(messageItem);
            //stream.getTracks().forEach( track => track.stop() );
          };
        })
        .catch((error) => {
          console.error('Error accessing audio:', error);
        });
    }
  }

  // Attach click event handler to the "Record" button
  const recordButton = document.querySelector('.btn-record');
  recordButton.addEventListener('click', () => {
    if (!isRecording) {
      // Start recording
      startRecording();
      initializeMediaRecorder(); // Initialize the MediaRecorder 

    } else {
      // Stop recording
      stopRecording();
    }
  });

I know some conditions are redundant, i was debugging.
Thanks.

Compass Arrow Rotate to Follow Cursor With Javasript

I’m trying to create this interactive compass so that the arrow always points to the mouse cursor and on mobile where you place your finger.

I’m new to coding so I asked Google Bard to generate some code for me but it’s not working correctly. I brought the HTML, CSS, and Javascript in to VS Code and it kind of works but it’s not there. I think the code is calculating the arrow rotation based on the center of the image and not the top so it just spins wierd and never points at my mouse. Thank you in advance for anyone taking a look at this post!

GOOGLE BARD CODE:

<div id="arrow">
  <img src="arrow.png">
</div>

#arrow {
  position: absolute;
  top: 0;
  left: 0;
  transform: rotate(0deg);
}

document.addEventListener("mousemove", function(event) {
  // Get the mouse cursor position.
  var mouseX = event.clientX;
  var mouseY = event.clientY;

  // Calculate the angle between the center of the arrow and the mouse cursor.
  var angle = Math.atan2(mouseY - 25, mouseX - 25) * 180 / Math.PI;

  // Rotate the arrow to the calculated angle.
  var arrow = document.getElementById("arrow");
  arrow.style.transform = "rotate(" + angle + "deg)";
});

Why is this code not testing for all the values of i?

I’m not looking for solutions to this code, rather looking why the current code is failing.

function HFC_x(x) {
  let xArr = [];
  let i = x;
  while (i > 1 && x % i == 0) {
    xArr.push(i);
    i--;
  }
  console.log(xArr);
}

HFC_x(15);

The code is for HCF. I am planning to do it this way.

This is how I want to to do GCD

I don’t want to directly use Euclid’s algorithm, I want to use it different way.

I first divide 15 by 3, then….till I get 1 as divisor.

Same for 12.

Currently, my code is only publishing 15. As I said I’m not looking for code solutions, but rather why is this happening. I tried debugger in vs code but it was not showing full steps/logs.

How to make monaco-editor block window object and document object?

Because of special needs, it is necessary to let the user try not to use the window or document object, if the user inputs the window or document so that monaco-editor does not appear code prompts;

I know that monaco-editor’s code hints for window may be coming through the window object of the current browser environment, and I tried to block it with window=null, but this reports an error.

window = null;
this.editor = monaco.editor.create(this.editorElement.nativeElement, {
      value: '',
      language: 'javascript',
    });

I don’t know how to make monaco editor not show code hints related to window or document objects

How to avoid “is not a function” error in javascript

I have a code to remove the milliseconds of a video duration, but when I try to remove it with c1seconds.setMilliseconds(0) but I get the error is not a function.

Here is my code:

var test = document.getElementById('test');
setInterval(function asas() {
if(video.readyState > 0) {
    var minutes = parseInt(video.currentTime / 60, 10);
    var seconds = video.currentTime % 60;
    var c1seconds = seconds.setMilliseconds(0);
test.innerHTML = minutes + ":" + c1seconds;
}
}, 0100);

Note: I am a beginner in javascript and I need an answer without the use of jquery

how to use math.js in a js file?

I want to use math.js in my code, but I can’t reference functions in math.js, I don’t want to use the pattern of npm install mathjs, only include math.js from local.

below is my code head, the lodash.js works correctly, but math.js can not find create and all functions.

import { create, all } from './math.js';

import { get, cloneDeep } from './lodash.js';

Thanks

where I could study data structure in javascript

I have a strong desire to build a solid foundation in data structures and algorithm complexity, starting from the fundamentals and gradually progressing to more advanced topics. However, I’ve encountered challenges in finding comprehensive resources to facilitate this learning journey. While I have been diligently following the FreeCodeCamp course, I’m uncertain whether it alone is sufficient to fulfill my ambitions.

In light of this, I’m seeking advice and recommendations on where to further enhance my knowledge and practical skills in data structures and algorithm analysis. The goal is to become a proficient programmer, capable of solving complex problems and optimizing code for efficiency

about javascript

Why does non-reactive variable behave strange in Vue3?

Here is the code

<template>
  <input type="button" value="click" @click="clickBtn"/>
  <div id="reactiveDiv">{{ reactiveVariable }}</div>
  <div id="noneReactiveDiv">{{ noneReactiveVariable }}</div>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue"

const reactiveVariable = ref('reactive')

let noneReactiveVariable = 'non reactive '

function clickBtn(){
  reactiveVariable.value = (new Date().getTime()).toString()
  noneReactiveVariable = (new Date().getTime()).toString()

  nextTick(()=>{
    console.log('next tick')
  })
}

</script>

I have two variables: reactiveVariable is reactive and noneReactiveVariable is not.

My question is:

  1. When I click the button, both variables in template change. I think noneReactiveVariable should not be changed because it’s defined without ref or reactive key words. My guess is that the reactive variable reactiveVariable’s value change caused the template to update and caused the noneReactiveVariable in template change too. I don’t know for sure.

  2. if I change the template like this:

<template>
  <input type="button" value="click" @click="clickBtn"/>
  <div id="noneReactiveDiv">{{ noneReactiveVariable }}</div>
</template>

In this case, when I click the button, the noneReactiveVariable in template doesn’t change. It seems ok now. But I have a nextTick in function clickBtn, I can see the log in console when I click the button which means the UI or template has updated. I think if the template has updated, why doesn’t the noneReactiveVariable in template change just like before, the reactiveVariable change caused the noneReactiveVariable change?

Using setTimeout() better than this [closed]

typingEffect() iterates through an array of strings that type out on the screen like a chatbot. I originally put typedMessage.textContent = “”; inside the looping function to simplify things, but it was really hard to time the clearing text feature with how long some of the strings are.

I tried to change the timing around, but because the loop function can only be set to one set time, I couldn’t make it work. Any help is greatly appreciated!

    const typingEffect = (message, item, i = 0) => {
    message.textContent += item[i];
    if (i === item.length - 1) {
        return;
    }
    setTimeout(() => { 
        typingEffect(message, item, i + 1)
    }, 30);
}

typingEffect(typedMessage, messageArray[0]);
setTimeout(() => {
    typedMessage.textContent = "";
}, 3000)
setTimeout(() => {
    typingEffect(typedMessage, messageArray[1]);
}, 3100)
setTimeout(() => {
    typedMessage.textContent = "";
}, 7000)
setTimeout(() => {
    typingEffect(typedMessage, messageArray[2]);
}, 7100)
setTimeout(() => {
    typedMessage.textContent = "";
}, 11000)
setTimeout(() => {
    typingEffect(typedMessage, messageArray[3]);
}, 11100)
setTimeout(() => {
    typedMessage.textContent = "";
}, 15000)

Cross platform end to end encryption (Swift & Node)

I’ve generated 2 sets of priv/pub keys and exported to pem, now I’m trying to import them into both swift and a js script but they seem to be generating different shared keys so swift can’t decrypt a message from js and vice versa. Given the fact that I’m able to import the keys then export them and the output matches the original input I’m sure they key pairs are fine, so my issue must lie in deriving the shared key.

In swift I’m using CryptoKit and js webcrypto.

JS:

async function deriveKey(publicKey, privateKey) {
    return await crypto.subtle.deriveKey(
        { name: "ECDH", public: publicKey },
        privateKey,
        { name: "AES-GCM", length: 256 },
        true,
        ["encrypt", "decrypt"]
    );
}
let sharedKey1 = await deriveKey(publicKey2, privateKey);
let exportedKey = await crypto.subtle.exportKey('raw', sharedKey1);
let keyString = Buffer.from(exportedKey).toString('base64');
console.log(keyString);

Which outputs: 1vF4AK9IqDDHNZ86zxt5zavx3h+V7AFCfpBU5Yv8Zro=

Swift:

func deriveSymmetricKey(privateKey: P256.KeyAgreement.PrivateKey, publicKey: P256.KeyAgreement.PublicKey) throws -> SymmetricKey {
    let sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: publicKey)

    let symmetricKey = sharedSecret.hkdfDerivedSymmetricKey(
        using: SHA256.self,
        salt: Data(),
        sharedInfo: Data(),
        outputByteCount: 32
    )
    
    return symmetricKey
}

let sharedKey1 = try deriveSymmetricKey(privateKey: privateKey, publicKey: publicKey2)

let keyData = sharedKey1.withUnsafeBytes {
    Data(Array($0))
}
let keyString = keyData.base64EncodedString()
print(keyString)

Which outputs: SeQZEg38dcfRl8+5LIwiiJXABJnOMuv3srlrIDZ0wQc=

How to see the diff between my current branch and main including committed code

  • I’m using VS code.
  • I pull from origin and update main branch.
  • I branch off it and create a new branch.
  • I do my work, and commit periodicially.
  • I want to be able to see the diff between main and my branch including all committed changes.
  • Either I want to be able to turn this on/off or have it as default diff view.

Is it possible?

I can always push my branch to origin and create a draft Pull Request to see my changes against main branch, but I want to do it in VS Code.

The reason for this is that I sometimes come back to a branch after a some time (perhaps a code review comes back), and I want to see all the changes on this branch, so I can undo them, or add new changes in, given what I’ve already changed.

I am having problems with my rest API and cors

I have hosted a html webpage with js backend that sends a post request to my spring boot server, however I keep getting the same error.

I tried to remove CORS completely in my backend but I have not succeeded. I keep getting 401 forbidden when I inspect element the page and look at the network section. I am running the webpage on a server in vs code and the java in Intellij.

Here is the error I am getting:

Access to fetch at 'http://localhost:8080/auth/login' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
login.js:37     POST http://localhost:8080/auth/login net::ERR_FAILED
loginUser @ login.js:37
onclick @ VM245 index.html:1
login.js:57 Login failed: TypeError: Failed to fetch
    at loginUser (login.js:37:5)
    at HTMLButtonElement.onclick (VM245 index.html:1:1)

Here is my javascript file:

document.addEventListener('DOMContentLoaded', function () {
    const loginForm = document.getElementById('loginForm');
    const registrationForm = document.getElementById('registrationForm');
    const addressForm = document.getElementById('addressForm');
    const switchToRegistration = document.getElementById('switchToRegistration');
    const switchToLogin = document.getElementById('switchToLogin');

    switchToRegistration.addEventListener('click', function (e) {
        e.preventDefault();
        loginForm.style.display = 'none';
        registrationForm.style.display = 'block';
    });

    switchToLogin.addEventListener('click', function (e) {
        e.preventDefault();
        registrationForm.style.display = 'none';
        loginForm.style.display = 'block';
    });

    loginForm.addEventListener('submit', function (e) {
        e.preventDefault();

        // Correctly access the username and password values from input fields
        const username = document.getElementById('loginUsername').value;
        const password = document.getElementById('loginPassword').value;

        loginUser(username, password);
    });
});

function loginUser(username, password) {
    const loginData = {
        username: username,
        password: password
    };

    fetch('http://localhost:8080/auth/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(loginData)
    })
        .then(response => response.json())
        .then(data => {
            // Assuming the authentication key is returned as 'authKey'
            const authKey = data.authKey;

            

            localStorage.setItem('authKey', authKey);

            
            window.location.href = 'index.html';
        })
        .catch(error => {
            // Handle login errors (e.g., display an error message)
            console.error('Login failed:', error);
        });
}

function registerUser() {
    
}

function submitAddress() {
    
}

Here is my web security class in my Spring boot backend:

package com.nea.ecommerceBackend.api.security;




import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import org.springframework.web.cors.CorsConfiguration;

import java.util.Arrays;


@Configuration
public class WebSecurityConfig {


    private JWTRequestFilter jwtRequestFilter;

    public WebSecurityConfig(JWTRequestFilter jwtRequestFilter) {
        this.jwtRequestFilter = jwtRequestFilter;
    }

    @Bean(name = "security")
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf((csrf) -> csrf.disable())
                .cors((cors) -> cors
                        .configurationSource(request -> {
                            CorsConfiguration config = new CorsConfiguration();
                            config.setAllowedOrigins(Arrays.asList("*")); // Allow requests from any origin
                            config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
                            return config;
                        })
                )
                .addFilterBefore(jwtRequestFilter, AuthorizationFilter.class)
                .authorizeHttpRequests((authorize) -> authorize
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // Permit HTTP OPTIONS requests
                        .requestMatchers("/product", "/auth/register", "/auth/login").permitAll()
                        .anyRequest().authenticated()
                );
        return http.build();
    }

}