Refreshing Google access token causes loss of oauth scope

I have a scenario where I am obtaining access/refresh tokens via oAuth consent. When the access token expires, the refreshed token returned after refresh is losing scopes previously acquired.

Summary of the interesting parts of the code look like this:


// I'm using google-auth-library
import { OAuth2Client } from "google-auth-library";

...

// I create an OAuth2Client like this. Let's assume the parameters are correct (they are)
new OAuth2Client(
  clientId,
  clientSecret,
  redirectUri
);

When obtaining consent, I generate a URL like this (this.newOAuth2Client just creates the client as described above):

// Generate a url that asks permissions for the Drive activity scope
const authorizationUrl = this.newOAuth2Client(redirectUri).generateAuthUrl({

  // 'online' (default) or 'offline' (gets refresh_token)
  access_type: 'offline',

  prompt : 'select_account',

  // Pass in the scopes array.
  scope: scopes,

  // Enable incremental authorization. Recommended as a best practice.
  include_granted_scopes: true,

  // The value to be passed to the redirect URL.
  state: state
});

When it comes time to refresh the token, it looks like this:

const client = this.newOAuth2Client(redirectUri);
client.setCredentials({ refresh_token: refresh_token });
return await client.getAccessToken();

The token returned produces a 401 error against the (Drive) API I am accessing, for requests that worked just fine prior to the refresh.

This is how I’m pulling the updated tokens from the refresh:

/** 
 * The client.getAccessToken() returns something called a GetAccessTokenResponse, 
 * which seems to be undocumented (?). Hunting and pecking...
 */
const result = client.getAccessToken();
const response = result.res;
if(response.status == 200) {
  const credentials = response.data;
  const accessToken = credentials.access_token; // <== This seems broken
  const refreshToken = credentials.refresh_token;
}

The only other piece of relevant data might be that these lost scopes were originally obtained after initial consent. In my particular case, I am first requesting these scopes:

'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'

Later, I add the following scopes:

'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.appfolder',
'https://www.googleapis.com/auth/drive.file'

After the refresh, the scopes seem to revert to only the initial set. After this subsequent grant, there is an update to the access_token (as expected) and if there is a refresh_token present I will persist it, but generally a refresh_token is not provided on this incremental grant.

Is it expected that refreshing an access token would wipe out scopes, or is there something wonky with my approach? (or perhaps my problem is elsewhere entirely?)

Custom camera sizes in regula liveness web SDK

I’m using this library @regulaforensics/vp-frontend-face-components for user’s liveness and it works good, but the size of camera is too small and I can’t handle it

enter image description here

I want to increase the camera size and also remove the shadow (juste above the abandon button)

Sortable js on change the drag element source it impact the dragged element

I am using sortable js

The issue occurs because the filterValue state you use for the search functionality applies a hidden class to the drag source items, but this hidden state affects the dropped items

for example
Example action for drag and drop and search

"use client"; 

import {WEB_FUNC,SAP_FUNC,CONTROLS} from "./options"; 
 
Sortable.mount(new MultiDrag(), new Swap()); 
export default function Home() {

  function addChildFunctions(evt:any) {
    const draggedElement = evt.item.cloneNode(); // The dragged DOM element
    
    evt.item.replaceWith(draggedElement)
    if(!draggedElement) return;
    const draggedIndex = draggedElement.getAttribute("data-el-id"); // Retrieve index
    const draggedGroup = draggedElement.getAttribute("data-group"); // Retrieve index
    const draggedData = CONTROLS.find(
      (group ) => group.id == draggedGroup && group.items.find(item=>item.id==draggedIndex)?.hasChild
    );
     
    if (draggedData ) {
      // Make the dropped element a drop container dynamically
      const childContainer = document.createElement("ul");
      childContainer.className = "dynamic-drop-area bg-blue-50 drop-area p-5";
      draggedElement.appendChild(childContainer);

      // Initialize Sortable on the new container
      Sortable.create(childContainer, {
        handle: ".drag-handle",
        group: {
          name: "shared",
          pull: "clone",
        },
        forceFallback:  true,
        animation: 200,
        sort: true,
        multiDrag: true, // Enable multi-drag
        selectedClass: "selected",
        onAdd: addChildFunctions,
      });
    }
  }
  const dragElement = useRef([]);
  const dropArea = useRef(null); // Single reference for the drop area
  const searchInput = useRef([]);
   
  useEffect(() => {
    dragElement.current.forEach((a) =>
      Sortable.create(a, {
        animation: 200,
        group: {
          name: "shared",
          pull: "clone",
          put: false,
        },
        forceFallback:  true,dragoverBubble: false,
        sort: false,
      })
    );
    if (dropArea.current) {
    Sortable.create(dropArea.current, {
      handle: ".drag-handle",
      animation: 200,
      group: {
        name: "shared",
        pull: false, // Drop area should not pull items
        put: true, // Accept items
      },
      forceFallback:  true,dragoverBubble: false,
      sort: true,
      multiDrag: true, // Enable multi-drag
      selectedClass: "selected",
    
   
    });
  }
  }, []);
  
   
  const [filterValue,setFilterValue]=useState("");
 
  return (

    <> 
      
      <div className={  "flex flex-row "}>
        <div className="basis-1/5  p-5 max-h-screen overflow-auto">
        <div className="flex items-center rounded-md bg-white pl-3 outline outline-1 -outline-offset-1 outline-gray-300 has-[input:focus-within]:outline has-[input:focus-within]:outline-2 has-[input:focus-within]:-outline-offset-2 has-[input:focus-within]:outline-indigo-600">
      
        <input type="text" name="price" id="price" onChange={()=>{
          setFilterValue(searchInput.current.value)
        }} ref={searchInput} className="block min-w-0 grow py-1.5 pl-1 pr-3 text-base text-gray-900 placeholder:text-gray-400 focus:outline focus:outline-0 sm:text-sm/6" placeholder="Search" />
     </div>
          {[...CONTROLS,...WEB_FUNC ] .map((group, index) => {
            return (
              <div className="border-b border-slate-200" key={group.id}>
                <button
                  onClick={() => toggleAccordion(index)}
                  className="w-full flex justify-between items-center py-5
          text-slate-800"
                >
                  <span>{group.group}</span>
                  <span
                    id={"icon-" + index}
                    className="text-slate-800 transition-transform duration-300"
                  >
                   -
                  </span>
                </button>
                <div
                  id={"content-" + index}
                  className="open  overflow-hidden transition-all duration-300 ease-in-out"
                >
                  
                  <div className="pb-5 text-sm text-slate-500 connect">
                    <ul ref={(el) => (dragElement.current[index] = el)}>
                      {
                        
                        group.items.map((a, i) => (
                        <li
                          className={"gap-x-6 p-2 my-2 bg-gray-50 " +  ((filterValue===""?"":  a.label.toLowerCase().includes(filterValue?.toLowerCase?.())?"":"hidden"))}
                          data-el-id={a.id}
                          data-group={group.id}
                          key={group.id+"_"+a.id}
                          data-id={group.id+"_"+a.id}
                        >
                          <div className="flex px-2  items-center drag-handle">
                            {a?.icon}
                            <span className=" px-2">{a.label}</span>
                          </div>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <ul
          className="drop-area  min-h-screen  bg-red-50 basis-4/5  p-5"
          ref={dropArea}
        ></ul>
      </div>
       

    </>
  );
}

Initial state:

  1. drag source contains items like Item 1, Item 2, and Item 3.
  2. drop area contains Item 1 (dragged from the source).
    Search action:
  3. i search for Item 2.
  4. in the source list, only Item 2 is shown, and Item 1 and Item 3 are hidden by applying the hidden class.
    Unexpected Behavior:
  5. the hidden class is also applied to Item 1 in the drop area because it shares the same DOM attributes and filtering logic.

role based access control in nextjs using authjs and database with google oauth

I have a condition where certain pages can be accessed according to their role in database

I have followed the tutorial on the Authjs site, and it seems like there is a lack of information, because there is an error in my coding

I use mongoose (mongodb), nextjs, and Google provider (OAuth)

My auth config:

import GitHub from "next-auth/providers/github"
import type { NextAuthConfig } from "next-auth"
import Google from "next-auth/providers/google"
import Credentials from "next-auth/providers/credentials"

export default {
    providers: [
        Google({
            profile(profile) {
                return { role: profile.role ?? "user", ...}
            }
        }),
    ]
} satisfies NextAuthConfig

Callbacks:

  callbacks: {
        async session({ session, token, user }) {
            // `session.user.address` is now a valid property, and will be type-checked
            // in places like `useSession().data.user` or `auth().user`
            return {
                ...session,
                user: {
                    ...session.user,
                },
            }
        },
    },

The Error:

... Expression expected.

Middleware:

// export { auth as middleware } from "@/auth";

import NextAuth from "next-auth"
import authConfig from "./libs/auth-js/auth.config"

export const { auth: middleware } = NextAuth(authConfig)

Calling dispatchEvent(clickEvent) on a textbox doesn’t work

I want to programmatically generate a click event on a textbox when a user clicks on a button. I can see that the textbox gets the event but the focus doesn’t change to the textbox.
What am I doing wrong?

function handleClick(event)
{
    let textbox = document.getElementById('text');
    let rect = textbox.getBoundingClientRect();            

    let newEvent = new MouseEvent('click', {
        clientX: rect.x + 5,
        clientY: rect.y + 5,
        x: rect.x + 5,
        y: rect.y + 5,
        pageX: rect.x + 5,
        pageY: rect.y + 5
    });

    textbox.dispatchEvent(newEvent);
}
<input type="text" id="text" onclick="console.log('clicked')" /> 

<button onclick="handleClick(event)">Click</button>

Next.js 14: ReferenceError: window is not defined when using intl-tel-input-react

I’m trying to implement a phone input component in my Next.js 14 application using the intl-tel-input library. However, I’m getting a ReferenceError: window is not defined error during server-side rendering.

Environment:

  • Next.js: 14.2.5
  • React: ^18
  • intl-tel-input: ^25.2.0
  • Node: 18

Code:

Here’s my phone input component:

'use client';

import IntlTelInput from 'intl-tel-input/react/build/IntlTelInputWithUtils.cjs';
import './PhoneInput.css';

export function PhoneInput() {
  return (
    <IntlTelInput />
  );
}

Error:

ReferenceError: window is not defined

The error occurs when trying to render the page containing this component. I understand this is likely due to Next.js’s server-side rendering trying to access the window object which isn’t available on the server, but I’ve already added the 'use client' directive to make it a client component.

What I’ve Tried

  1. Added ‘use client’ directive at the top of the file
  2. Wrapped the component with dynamic import using Next.js’s dynamic function (but wasn’t sure about the correct configuration)

How can I properly implement this phone input component in Next.js while avoiding the SSR-related window reference error?

Any help would be greatly appreciated!

Remove button focus state after click

I’m trying to remove the focus state of a button once it is clicked. The issue is once I click a button and after that instead of clicking on anywhere else if I just press ENTER the click event on that button works again.

button focus issue

Below is my code –

<style>
button { outline: none } /** Many solutions mentioned this but this is just removing the view state */
</style>
<button type="button" onclick="test()">Click</button>
<script>function test() { console.log(1) }</script>

I tried adding outline: none to the CSS but this is not removing the actual functionality of the button on focused state.

What can be the solution for this?

Browser not setting cookies with SameSite=None when interacting with Web API

When developing a React web application that interacts with a server via a Web API, I encountered an issue where the browser does not store cookies with the SameSite=None attribute.

My React application, running at https://localhost:3000, sends POST requests to an API server at https://localhost:7000. The server responds with a Set-Cookie header, attempting to set a cookie with the attributes SameSite=None; Secure. However, despite the presence of this header in the response, the browser does not store the cookie, and subsequent requests lack the necessary authentication data.

If I use the same domain, the cookies are stored.

I tried:

fetch('https://localhost:7000/api/login', {
  method: 'POST',
  credentials: 'include',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ username: 'user', password: 'password' })
})
  .then(response => {
    // Handle response
  });

aspnet:

//Cookies
cookies.Append("AccessToken", accessToken, new CookieOptions
        {
            HttpOnly = true,
            Secure = true,
            SameSite = SameSiteMode.None,
            Expires = DateTimeOffset.UtcNow.AddMinutes(15)
        });
        
        cookies.Append("RefreshToken", refreshToken, new CookieOptions
        {
            HttpOnly = true,
            Secure = true,
            SameSite = SameSiteMode.None,
            Expires = DateTimeOffset.UtcNow.AddDays(7)
        });

//Cors
 public static IServiceCollection AddAppCors(this IServiceCollection services)
    {
        return services.AddCors(options =>
        {
            options.AddPolicy(CorsPolicies.Base, policy =>
            {
                policy.WithOrigins("https://localhost:3000")
                    .AllowCredentials()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });
    }

//Program.cs

...
builder.Services.AddAppCors(); //ADD MY CORS
...
var app = builder.Build();

app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(CorsPolicies.Base); //USE MY CORS
app.UseAuthentication();
app.UseJwtSecurityStampValidation();
app.UseAuthorization();
app.MapControllers();

app.Run();

Why are different divs being created on each iteration?

I’m new to programming in javascript and I’m trying to create a 16 x 16 grid. I have coded in python and java before and neither of which really uses elements and tags like you do for web development.

screenshot

I found a tutorial but I’m trying to understand how all the divs are individually created when the reference is the same each time. Is a new location allocated in memory for each iteration of the loop? In the tutorial they also put event listeners inside the loop. Wouldn’t that not work because after the loop concludes the event listeners stop working?

Maybe this is a stupid question but I cannot understand things unless they are deeply explained.

How can I fix a gap issue that appears on a website when viewed on a phone, it appears when I hold the slide the content sideways

here is it, when in phone view

* {
    font-family: inter, sans-serif;
    margin: 0;
    padding: 0;
}

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-size: cover;
    background-position: center center;
    background: linear-gradient(135deg, #ff66a6,  #ff70fb, #9f2fed);
    color: white;
    background-attachment: fixed; 
}
.Announce-section {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    padding: 2rem 1rem;
    color: white;
    text-align: center;
}

/* Section-Specific Styling */
.Announce-section {
    background: url('announcement-design.png') no-repeat center center;
    background-size: cover;
    margin: 0; /* Remove any margin */
    padding: 20px; /* Add some padding for better spacing */
    min-height: 100vh; /* Ensure it takes full height */
    box-sizing: border-box;
}

.seccontainer {
    max-width: 1000px;
    width: 100%;
    background: rgba(255, 102, 166, 0.8); /* Same background color as .img-text */
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08); /* Same box shadow as .img-text */
    border-radius: 15px; /* Same border radius as .img-text */
    padding: 2rem;
    color: white;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}
 <?php
    include_once("connect.php");

    function getAnnouncements() {
        global $conn;

        // Query to get announcements from the database
        $query = "SELECT * FROM announcements"; 
        $result = mysqli_query($conn, $query);

        $conn->close();

        // Check if there are any announcements
        if (mysqli_num_rows($result) > 0) {
            // Loop through the announcements and output the HTML
            while ($announcement = mysqli_fetch_assoc($result)) {
                echo '<div class="card hidden">';
                
                if (!empty($announcement["filename"])) {
                    echo '<img class ="image" src="uploads/' . htmlspecialchars($announcement["filename"]) . '">'; 
                } else { 
                    echo '<img class ="image" style="display:none;">';
                }
                echo '<div class="content">';
                echo '<h2 class="title">' . htmlspecialchars($announcement["title"]) . '</h2>';
                echo '<p class="desc">' . htmlspecialchars($announcement["description"]) . '</p>';
                if (!empty($announcement["link"])) {
                    echo '<button class="action"><a href="' . htmlspecialchars($announcement["link"]) . '" target="_blank">Learn More</a></button>';
                }

    <!-- Announcement Section -->
    <section id="section1" class="Announce-section">
        <div class="seccontainer">
            <h1>ANNOUNCEMENTS</h1>
            <p>Important information and updates.</p>
            <div id="announcementList">
                <?php
                    // Call the function to display the announcements
                    getAnnouncements();
                ?>
            </div>
        </div>
    </section>

How can I fix a persistent gap or overlapping container issue on a website when viewed on a phone? I’ve already tried setting padding and margin to 0, but no matter what adjustments I make, the gap still remains. I even attempted commenting out the announcement section entirely to see if it was causing the issue, but the gap continues to appear. I’d like to completely remove this gap or overlapping container.

comparing toString() in JS with an object gives true [duplicate]

let m = {name : "mastan"};
let n = {name : "mastan"};

m == n
// this gives false because m and n are 2 different objects

JSON.stringify(m) == JSON.stringify(n)
// this gives true because stringify converted object into a string 

Meanwhile I did this and it returned true ?

'[object Object]' == {name : "mastan"}
// and
m.toString() == n

How?

How to Enable Navigation to $scope Method Definitions in AngularJS Using VS Code?

I’m working on an AngularJS project in Visual Studio Code and have encountered an issue with navigating to $scope method definitions.

Current Setup:

When I click on a method call like $scope.refreshDashboard() in my code, I want to navigate directly to its definition, such as:

    $scope.refreshDashboard = async (options) => { 
    // Method implementation 
};

This functionality works seamlessly in IntelliJ IDEA Ultimate Edition, but I haven’t found a way to achieve this in VS Code.

What I’ve Tried:

Installed AngularJS-related extensions like AngularJS Support and JavaScript IntelliSense.

Searched for VS Code extensions, but none seem to provide this functionality for $scope method calls.

Explored custom solutions like writing a VS Code extension, but I’d prefer a simpler, community-supported approach if available.

My Question:
Is there an existing VS Code extension or configuration that enables navigation to $scope method definitions in AngularJS?

If not, are there any workarounds or tools I can use to achieve this without switching back to IntelliJ IDEA?

Any help or insights would be greatly appreciated!

How to convert ñ to ñ in javascript

I have found a bunch of solutions to other characters, such as > and & but accented characters such as ñ don’t work with those solutions. For example, this function:

function encodeHTMLEntities(text) {
  return $("<textarea/>").text(text).html();
}

works great with > and & but not ñ (which i want to be converted to &ntilde;

Thanks for any help,
kevin