React auth utils function re-rendering

This is the closest I’ve gotten regarding setting up my own auth system. I have golang graphql server I’m connecting to and a nextjs + apollo + redux-persist client that I’m starting to piece together slowly. Currently, I’m trying to pass the access token that is persisted in my store and refresh the tokens if necessary. However, I noticed that upon the refreshing of my tokens, it’s storing my session in the database twice, every time. Not when I’m authenticating on the /login page.

const time = Math.round(Date.now() / 1000)

async function getRefreshedAccessToken() {
    try {
        const authState = store.getState().auth

        const { data } = await clientAuth.mutate({
            mutation: REFRESH,
            variables: {
                input: {
                    refreshToken: authState.refresh
                }
            }
        })
        if (data && data.refreshTokens) {
            authActions.authUser(data.refreshTokens)
            return data.refreshTokens.access
        }

    } catch (error) {
        authActions.logoutUser()
        console.log(error)
        return null
    }
}

export function getAccessToken() {
    const authState = store.getState().auth
    const accessExp = authState.payload.exp <= time
    const refreshExp = authState.refreshExpires <= time

    if (
        authState &&
        authState.access &&
        authState.payload) {
        if (time + 1 * 60 <= authState.payload.exp) {
            if (time + 3 * 60 >= authState.payload.exp) {
                getRefreshedAccessToken()
            }
        } else if (accessExp == true && refreshExp == false) {
            getRefreshedAccessToken()
        } else if (accessExp == true && refreshExp == true) {
            authActions.logoutUser()
        }
        return authState.access
    } else {
        return null
    }
}

Which gets used here:

export const linkTokenHeader = setContext(async (_, { headers }) => {
  var accessToken = getAccessToken()
  return {
    headers: {
      ...headers,
      Authorization: accessToken ? `${accessToken}` : ''
    }
  }
})
export const clientAuth = new ApolloClient({
  connectToDevTools: true,
  link: linkAuth,
  cache: new InMemoryCache()
})

const options = {
  watchQuery: {
    fetchPolicy: 'cache-and-network',
    errorPolicy: 'none'
  },
  query: {
    fetchPolicy: 'cache-and-network',
    errorPolicy: 'none'
  },
  mutate: {
    errorPolicy: 'none'
  }
}

export const clientMain = new ApolloClient({
  connectToDevTools: true,
  defaultOptions: options,
  link: ApolloLink.from([linkError, linkTokenHeader, linkMain]),
  cache: new InMemoryCache()
})

As my _app.js looks like:

function MyApp({ Component, pageProps }) {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <ApolloProvider client={clientMain}>
          <Component {...pageProps} />
        </ApolloProvider>
      </PersistGate>
    </Provider>
  )
}

Then I have this hook:

export function useIsAuth() {
  const isAuth = useSelector(state => state.auth.payload)

  const syncTabLogout = event => {
    if (event.key === 'isAuth' && event.newValue === 'false') authActions.logoutUser()
  }

  useEffect(() => {
    window.addEventListener('storage', syncTabLogout)
    return () => {
      window.removeEventListener('storage', syncTabLogout)
    }
  }, [])

  useEffect(() => {
    if (!isAuth) {
      clientAuth.clearStore() 
      clientMain.clearStore()
      localStorage.setItem('isAuth', false)
    } else {
      localStorage.setItem('isAuth', true)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAuth])

  return isAuth
}

For the following page:

const PRIVATE = gql`
  query Private {
    privateInfo
  }
`

function Test() {
    const isAuth = useIsAuth()
    const { data } = useQuery(PRIVATE, { skip: !isAuth });
    const globalState = useSelector((state) => state)
    return (
        <>
            <pre>
                {JSON.stringify(globalState, null, 2)}
            </pre>

            {isAuth ? (
                <>
                    {data ? data.privateInfo : 'unauthorized'}

                    <button onClick={() => authActions.logoutUser()}>
                        Logout
                    </button>
                </>

            ) : (
                <Link href={"/login"}>
                    <button>
                        Authenticate
                    </button>
                </Link>
            )}
        </>
    );
}

I’m trying to figure out how I can appropriately go about this. Secondly, I would appreciate any comments about using GQL for my auth server and how I’m going about my client. I do not want to move forward until I better understand my current position.

Getting unexpected token error when try to script tag dynamically with dynamic script

Goal: Need to create multiple trigger functions dynamically for different id_numbers

I am trying to create a script tag with dynamic code but I am getting below errors

I am getting $window is not defined if I try to write below code

   $(document).ready(function() {
    var script1 = document.createElement('script');
        script1.setAttribute('type','text/javascript');
        
        //script1.text ="$(document).ready(function() {"+
        script1.text = "$window.ATL_JQ_PAGE_PROPS =  {"+
            "'id_number':{"+
                '"triggerFunction": function(showCollectorDialog) {'+
                    'jQuery("#submitBug-id_number").click(function(e) {'+
                        'e.preventDefault();'+
                        'showCollectorDialog();'+
                '   }); '+
            '}'+
        '}'+
            '}';
document.body.appendChild(script1);
});

And I have tried with different method than getting unexpected token ‘}’

    script1.innerHTML = "$(document).ready(function() {";
    script1.innerHTML = "$window.ATL_JQ_PAGE_PROPS =  {";
        script1.innerHTML = "'id_number' :{";
        script1.innerHTML = "'triggerFunction': function(showCollectorDialog) {";
        script1.innerHTML = "jQuery('#submitBug-id_number').click(function(e) {";
        script1.innerHTML = "e.preventDefault();";
        script1.innerHTML = "showCollectorDialog();";
        script1.innerHTML = "});";
        script1.innerHTML = "},";
        script1.innerHTML = "fieldValues: {";
        script1.innerHTML = "fullname:"+ userName+",";
        script1.innerHTML = "email: "+email+",";
        script1.innerHTML = "recordWebInfo: '1',";
        script1.innerHTML = "recordWebInfoConsent: ['1']";
        script1.innerHTML = "}";
        script1.innerHTML = "}";
        script1.innerHTML = "}";*/
        script1.innerHTML = "});";
document.body.appendChild(script1);

Please help to write a code dynamically under script tag

Points on D3.JS globe not rotating with globe

I am working with a latitute/longitude coordinate dataset. I have created a globe in d3 to create marker points for each long/lat coord. I have succesfully been able to rotate the globe but the marker points do not rotate and I am not sure how to append them to the rotation?

Thank you

Here is my code below:

<!DOCTYPE html>
<html>
    <body>
        <svg></svg>
        <script src="https://d3js.org/d3.v4.min.js"></script>
        <script src="https://d3js.org/topojson.v1.min.js"></script>
        <script>
            var radius = 250;
            let locations = [];
          
            var projection = d3.geoOrthographic().scale(radius) .translate([radius, radius]).clipAngle(90);  
            var svg = d3.select("body").append("svg").attr("width", radius * 2).attr("height", radius * 2).on("mousedown", mousedown).on("mousemove", mousemove).on("mouseup", mouseup);     
            svg.append("circle") .attr("cx", radius).attr("cy", radius).attr("r", radius).style("fill", "none").style("stroke", "black");     
            var path = d3.geoPath().projection(projection);
            const markerGroup = svg.append('g');
            const center = [radius,radius];

         
            d3.queue()
                .defer(d3.json, 'https://gist.githubusercontent.com/mbostock/4090846/raw/d534aba169207548a8a3d670c9c2cc719ff05c47/world-110m.json')          
                .defer(d3.json, 'data/disdata.json')
                .await((error, worldData, locationData) => {
                    svg.selectAll(".segment")
                        .data(topojson.feature(worldData, worldData.objects.countries).features)
                        .enter().append("path")
                        .attr("class", "segment")
                        .attr("d", path)
                        .style("stroke", "#888")
                        .style("stroke-width", "1px")
                        .style("fill", (d, i) => '#e5e5e5')
                        .style("opacity", ".6")
                        locations = locationData;
                        drawMarkers();                   
                });
            

            function trackballAngles(pt) {
                var r = projection.scale();
                var c = projection.translate();
                var x = pt[0] - c[0], y = - (pt[1] - c[1]), ss = x*x + y*y;


                var z = r*r > 2 * ss ? Math.sqrt(r*r - ss) : r*r / 2 / Math.sqrt(ss);  

                var lambda = Math.atan2(x, z) * 180 / Math.PI; 
                var phi = Math.atan2(y, z) * 180 / Math.PI
                return [lambda, phi];
            }



            function composedRotation(λ, ϕ, γ, δλ, δϕ) {
                λ = Math.PI / 180 * λ;
                ϕ = Math.PI / 180 * ϕ;
                γ = Math.PI / 180 * γ;
                δλ = Math.PI / 180 * δλ;
                δϕ = Math.PI / 180 * δϕ;
                    
                var sλ = Math.sin(λ), sϕ = Math.sin(ϕ), sγ = Math.sin(γ), 
                    sδλ = Math.sin(δλ), sδϕ = Math.sin(δϕ),
                    cλ = Math.cos(λ), cϕ = Math.cos(ϕ), cγ = Math.cos(γ), 
                    cδλ = Math.cos(δλ), cδϕ = Math.cos(δϕ);

                var m00 = -sδλ * sλ * cϕ + (sγ * sλ * sϕ + cγ * cλ) * cδλ,
                        m01 = -sγ * cδλ * cϕ - sδλ * sϕ,
                            m02 = sδλ * cλ * cϕ - (sγ * sϕ * cλ - sλ * cγ) * cδλ,
                    m10 = - sδϕ * sλ * cδλ * cϕ - (sγ * sλ * sϕ + cγ * cλ) * sδλ * sδϕ - (sλ * sϕ * cγ - sγ * cλ) * cδϕ,
                        m11 = sδλ * sδϕ * sγ * cϕ - sδϕ * sϕ * cδλ + cδϕ * cγ * cϕ,
                                m12 = sδϕ * cδλ * cλ * cϕ + (sγ * sϕ * cλ - sλ * cγ) * sδλ * sδϕ + (sϕ * cγ * cλ + sγ * sλ) * cδϕ,
                    m20 = - sλ * cδλ * cδϕ * cϕ - (sγ * sλ * sϕ + cγ * cλ) * sδλ * cδϕ + (sλ * sϕ * cγ - sγ * cλ) * sδϕ,
                        m21 = sδλ * sγ * cδϕ * cϕ - sδϕ * cγ * cϕ - sϕ * cδλ * cδϕ,
                            m22 = cδλ * cδϕ * cλ * cϕ + (sγ * sϕ * cλ - sλ * cγ) * sδλ * cδϕ - (sϕ * cγ * cλ + sγ * sλ) * sδϕ;
                 
                if (m01 != 0 || m11 != 0) {
                    γ_ = Math.atan2(-m01, m11);
                    ϕ_ = Math.atan2(-m21, Math.sin(γ_) == 0 ? m11 / Math.cos(γ_) : - m01 / Math.sin(γ_));
                    λ_ = Math.atan2(-m20, m22);
                } else {
                    γ_ = Math.atan2(m10, m00) - m21 * λ;
                    ϕ_ = - m21 * Math.PI / 2;
                    λ_ = λ;       
                }
                    
                return([λ_ * 180 / Math.PI, ϕ_ * 180 / Math.PI, γ_ * 180 / Math.PI]);
            }
    
            var m0 = null,
            o0;
  
            function mousedown() {  // remember where the mouse was pressed, in canvas coords
                m0 = trackballAngles(d3.mouse(svg.node()));
                o0 = projection.rotate();
                d3.event.preventDefault();
            }

            function mousemove() {
            if (m0) {  // if mousedown
                var m1 = trackballAngles(d3.mouse(svg.node()));
            
                o1 = composedRotation(o0[0], o0[1], o0[2], m1[0] - m0[0], m1[1] - m0[1])
                

                projection.rotate(o1);
                


                svg.selectAll("path").attr("d", path);
                }
            }

            function mouseup() {
            if (m0) {
                mousemove();
                m0 = null;
            }
            }              
            
            function drawMarkers() {
                const markers = markerGroup.selectAll('circle')
                    .data(locations);
                markers
                    .enter()
                    .append('circle')
                    .merge(markers)
                    .attr('cx', d => projection([d.Longitude, d.Latitude])[0])
                    .attr('cy', d => projection([d.Longitude, d.Latitude])[1])
                    .attr('fill', d => {
                        const coordinate = [d.Longitude, d.Latitude];
                        gdistance = d3.geoDistance(coordinate, projection.invert(center));
                        return gdistance > 1.57 ? 'none' : 'steelblue';
                    })
                    .attr('r', 7);

                markerGroup.each(function () {
                    this.parentNode.appendChild(this);
                });
            }
        </script>
    </body>
</html>

Is there a way to add a drawing component inside video player in react

I was thinking of having a button which calls a drawing component so I can draw on top of the video player component.

const VideoPlayer = ({selectedVideo}) => {
    
    return(
        <div className="App">
       <video key = {selectedVideo} width="950" height="500" controls>
         <source 
         key= {selectedVideo}
         src={selectedVideo} 
         type="video/mp4" />
         </video>
   </div>
    );
};

export default VideoPlayer;

I was thinking of writing something similar to this:
I want to draw (using html5 canvas) inside video in react but with the ability to having drawing enabled or disabled with a button press and that it stays within the boundaries of the video player. How do you suggest I go about doing this?

Connecting the frontend (HTML,CSS,JS) to the backend (Express)

So there’s a few things I’m confused about with connecting a frontend to a backend part of a website, and I can’t seem to find anything online about it.

  • Say you have a backend API, which if you had a endpoint which deletes a user, for if they want their account deleted, then what’s stopping an attacker from just pinging the end point with a user ID and then it’ll delete the user? I’ve heard that you can use like a password or something similar to stop fake attacks, but what’s stopping somebody from just looking through the source code to find the code that is sent along with the request? Do you just use a user ID that would be hard to guess? But if so, why couldn’t they just brute force user ID’s?

  • Should the backend be run on the same domain as the frontend? Should you just have to use https://example.com:3000, or should you have to use the ip of the server and send data to https://000.000.000.00:3000?

Any help would be appreciated. I don’t know that much about full stack development since I’m just now starting to learn, however what people say seems to be a really insecure way of doing it.

Why does my JavaScript code work in a code tester but not in my browser? [duplicate]

My code seems to work on this website and other code testers but when i manually use it in my google chrome browser it does not seem to work? Is there something i need to change on my browser for it to work? My google chrome is even all freshly updated and everything. The html and CSS show up just fine when I open it up from visual studio code onto my browser. It is properly tagged as well. Just dont know why it works on here but not on my computer.

const form = document.querySelector('#contact-form');
const fields = form.querySelectorAll('input[name]');

const checkFields = () => {
    fields.forEach((field) => {
        if (!field.checkValidity()) {
            field.style.backgroundColor = 'pink';
            return;
        }
        field.style.backgroundColor = '';
    });
}

window.addEventListener('DOMContentLoaded', load () => {
    checkFields();
    form.addEventListener('input', checkFields);

    form.addEventListener('submit', (e) => {
        e.preventDefault();

        if (!form.checkValidity()) return alert('Form invalid. Please fix errors.');

        alert('Form submitted successfully!');
        form.reset();
    });
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../normalize.css" rel="stylesheet">
<link href="../styles.css" rel="stylesheet">
<script src="contact-us.js"></script>
<title>Contact Us</title>
</head>
<body>
    <header>
        <section>
            <h1>Play2Learn Logo</h1>
            <nav>
                <ul id="nav">
                    <li><a href="index.html">Home</a></li>
                    <li><a href="about.html">About</a></li>
                    <li><a href="contact-us.html">Contact Us</a></li>
                    <li class="contains"><a>Games</a>
                        <ul class="menu">
                            <li><a href="anagram-hunt.html">Anagram Hunt</a></li>
                            <li><a href="math-facts.html">Math Facts</a></li>
                        </ul>
                    </li>
                    <li><a href="login.html">Login</a></li>
                </ul>
            </nav>
        </section>
    <hr>
    <main>
        <h1>Contact Us</h1>
        <form id="contact-form" method="post" novalidate onSubmit="test()">
            <div>
            <label for="emailfield">Email:</label>
            <input type="email" name="emailfield" id="emailfield" required>
            </div>
            <div>
            <label for="subjectfield">Subject:</label>
            <input type="subject" name="subjectfield" id="subjectfield" required>
            </div>
            <div>
            <label for="messagefield">Message:</label>
            <input type="message" name="messagefield" id="messagefield" required minlength="5" maxlength="65">
            </div>
            <div>
            <button>Submit</button>
            </div>
        </form>
    </main>
</body>
<hr>
<footer>&copy; 2022 Play2Learn</footer>
    <address>
        <a href="contact-us.html">
        <img src="images/email.png" alt="email-icon"></a>
        <a href="https://instagram.com">
        <img src="images/instagram.png" alt="instagram-icon"></a>
        <a href="https://twitter.com">
        <img src="images/twitter-icon.png" alt="twitter-icon"></a>
        <a href="https://facebook.com">
        <img src="images/facebook-icon.png" alt="facebook-icon"></a>
    </address>
</section>
</html>

Optimal way to check out rows in PostgreSQL by multiple scalable worker processes

I have a very large table with 100,000’s of rows with a key and a timestamp.

I currently use batch of AWS servers that are using NodeJS and PG to query for the oldest last_updated timestamp, perform the function, and then update the row with the NOW().

My issue is I am trying to find a way scale with more processes and optimize my row checkouts. I started with each process selecting 1000 at a time and each one having a multiple of 1000 for OFFSET, doing the operation, and then updating

I started to read about SELECT using FOR UPDATE and SKIP LOCK but seems like this could have some performance impacts? Also can’t find a clear way to do the SELECT/UPDATE in the same query or do I keep doing single updates at a time similar to this post but seems like this may not be good for larger operations like this?

implementing an UPDATE on SELECT in Postgres

Has anyone approached this type of setup? I also have been debating do I need to build my own middleware that manages a pool of work items and then the workers use that table to select/delete?

How stop multiple projects in vscode with the launch.json

I have in my launch.JSON a configuration that allows me to start two different API projects at the same time (Web API One and Web API Two), both are components of the same project, everything works fine on start, but if I need to stop the APIs I need to stop each of them individually, theirs a way to create a config file to stop both projects at the same time?

Observation: I use only two projects in this code example, but in reality, I have six APIs and other projects like services and front-end projects.

Most C# projects, Windows Services and Web APIs, but I want to include JavaScript front-end projects in the future.

My launch.JSON:

// Components for start menu in vscode debug mode
{
    "version": "0.2.0",
    "compounds": 
    [
        {
            "name": "Web API",
            "configurations": 
            [
                "Web API One",
                "Web API Two"
            ]
        }
    ],

// Configuration of each project
    "configurations": 
    [
        {
            "name": "Web API One",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "buildWEBAPI",
            "program": "${workspaceFolder}/WEBAPI/PATH",
            "args": 
            [
                "--force"
            ],
            "cwd": "${workspaceFolder}/01.Application/WEBAPI",
            "stopAtEntry": false,
            "env": 
            {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        },
        {
            "name": "Web API Two",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "buildWEBAPI",
            "program": "${workspaceFolder}/WEBAPI/PATH",
            "args": 
            [
                "--force"
            ],
            "cwd": "${workspaceFolder}/01.Application//WEBAPI/",
            "stopAtEntry": false,
            "env": 
            {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        }
    ]
}

Javascript function return logic [duplicate]

I came across this function code in a javascript library and not really sure how the return works.

    function(t, e, r) {
     return 2 === arguments.length && "function" == typeof e &&   (r = e,e =null)  ,   Cn(t, e, n, r)
    }

Is it equivalent to the following if statement?

    
     if(2 === arguments.length && "function" == typeof e) 
          (r = e,e = null)  ,  return  Cn(t, e, n, r)
    

Building SOAP request from WSDL in Node.js

I need to extract the request parameters from my local wsdl file in run time the same way SoapUI does when you create a new request in a soap project.

I have already tried a lot of libraries on npm to read wsdl file but no one seems to work the way i need to. Also i’m using strong-soap to create a client and call the methods, but at the moment my requeriment is to generate the request from the wsdl file. Idk if maybe another soap library can generate these parameters. Any suggestions may help me, thank you in advance!!

My alert does not pop up when I click submit. What am i doing wrong?

I want my alert to pop up when the form does not validate. It should pop up an alert message when it is valid but does not. I am at a loss. I have been working on fixing this for 4 hours now with no success. I appreciate your time to look at it. I must be doing something wrong. No matter what i do it wont create a pop up alert even though the form is invalid when i press submit.

This is my HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../normalize.css" rel="stylesheet">
<link href="../styles.css" rel="stylesheet">
<script src="../play2learn/contact-us.js"></script>
<title>Contact Us</title>
</head>
<body>
    <header>
        <section>
            <h1>Play2Learn Logo</h1>
            <nav>
                <ul id="nav">
                    <li><a href="index.html">Home</a></li>
                    <li><a href="about.html">About</a></li>
                    <li><a href="contact-us.html">Contact Us</a></li>
                    <li class="contains"><a>Games</a>
                        <ul class="menu">
                            <li><a href="anagram-hunt.html">Anagram Hunt</a></li>
                            <li><a href="math-facts.html">Math Facts</a></li>
                        </ul>
                    </li>
                    <li><a href="login.html">Login</a></li>
                </ul>
            </nav>
        </section>
    <hr>
    <main>
        <h1>Contact Us</h1>
        <form id="contact-form" method="post" novalidate>
            <div>
            <label for="emailfield">Email:</label>
            <input type="email" name="emailfield" id="emailfield" required>
            </div>
            <div>
            <label for="subjectfield">Subject:</label>
            <input type="subject" name="subjectfield" id="subjectfield" required>
            </div>
            <div>
            <label for="messagefield">Message:</label>
            <input type="message" name="messagefield" id="messagefield" required minlength="5" maxlength="65">
            </div>
            <div>
            <button>Submit</button>
            </div>
        </form>
    </main>
</body>
<hr>
<footer>&copy; 2022 Play2Learn</footer>
    <address>
        <a href="contact-us.html">
        <img src="images/email.png" alt="email-icon"></a>
        <a href="https://instagram.com">
        <img src="images/instagram.png" alt="instagram-icon"></a>
        <a href="https://twitter.com">
        <img src="images/twitter-icon.png" alt="twitter-icon"></a>
        <a href="https://facebook.com">
        <img src="images/facebook-icon.png" alt="facebook-icon"></a>
    </address>
</section>
</html>

This is my javaScript:
function checkField(field) {
    if (!field.checkValidity()) {
        field.style.backgroundColor = 'pink';
    } else {
        field.style.backgroundColor = '';
    }   
}
window.addEventListener('load', function(e) {
    const form = document.getElementById('contact-form');
    const emailField = form.emailfield;
    const subjectField = form.subjectfield;
    const message = form.messagefield;

    emailField.addEventListener('input', function(e) {
    checkField(emailField);
    });
    subjectField.addEventListener('input', function(e) {
    checkField(subjectField);
    });
    messageField.addEventListener('input', function(e){
    checkField(messageField)
    });
    form.addEventListener('Submit', function(e){
    checkField(emailField);
    checkField(subjectField);
    checkField(messageField);
    
    if(!form.checkValidity()) {
        e.preventDefault();
        alert('Please fix form errors.');
    } else {
        alert('Form Submitted');
     }
   });   
});