authentication flow with specific development application store issues

I’m trying to implement a authentication flow at the moment and having some issues.

https://www.canva.dev/docs/apps/authenticating-users/ is some of the documentation.

Here’s a brief recap of the flow:

  1. User is authenticated with Canva on client, gets state and token jwt

  2. User clicks on a button or link that redirects them to your identity provider’s authorization endpoint (in this case, Auth0). This request includes several query parameters such as your application’s client ID, the requested scope, and a redirect URI.

  3. The user logs in with Auth0, which then redirects the user to the redirect URI specified in step 1. This redirect includes an authorization code as a query parameter.

  4. Your server (the callback cloud function in this case) receives the authorization code from step 2.

  5. Your server sends a POST request to Auth0’s token endpoint to exchange the authorization code for an access token. This request includes your application’s client ID, client secret, the authorization code received in step 3, and the redirect URI.

  6. Your server receives the access token from Auth0.

  7. Now that your server has an access token, it can use this token to make authenticated requests on behalf of the user.

  8. Lastly, your server redirects the user back to Canva with the original state parameter and a success indicator.

I’m having some issues with resolving this flow at the moment.

Using two google cloud functions

Redirects users to AUth0 from Canva after using canva react login stuff.

`const functions = require('@google-cloud/functions-framework');
const { URL } = require('url');

functions.http('authorize', (req, res) => {
   const {
    state,
    redirect_uri,
    nonce,
    code_challenge,
    code_challenge_method,
    auth0Client,
    canva_state
  } = req.query;
  res.set('Set-Cookie', `canva_state=${canva_state}; Max-Age=${24 * 60 * 60}; HttpOnly; Path=/`);

  // dev-xxx.us.auth0.com 
  const url = new URL(`https://dev-xxx.us.auth0.com/authorize`);
  url.searchParams.append('response_type', 'code');
  url.searchParams.append('client_id', 'xxxx');
  url.searchParams.append('redirect_uri', redirect_uri);
  url.searchParams.append('state', state);
  url.searchParams.append('scope', 'openid profile email');
  url.searchParams.append('response_mode', 'query');
  url.searchParams.append('nonce', nonce);
  url.searchParams.append('code_challenge', code_challenge);
  url.searchParams.append('code_challenge_method', code_challenge_method);
  url.searchParams.append('auth0Client', auth0Client);

  console.log("req: ",req)
  res.redirect(url.toString());
  // const url = new URL(`https://${process.env.AUTH0_DOMAIN}/authorize`);
// process.env.AUTH0_CLIENT_ID
  // url.searchParams.append('redirect_uri', process.env.REDIRECT_URI);

  // res.send(`Hello ${req.query.name || req.body.name || 'World'}!`);
});`
  1. Cloud function for re-directing back to canva
`const functions = require('@google-cloud/functions-framework');
const { URL } = require('url');

functions.http('redirect', (req, res) => {
    try {
        // Redirect back to Canva with the original state and success=true
        const params = new URLSearchParams({
            success: "true",
            state: req.cookies.canva_state, // Use the state from the original request
        });

        const url = `https://www.canva.com/apps/configured?${params}`;
        res.redirect(302, url);
    
    } catch (error) {
        console.error("Error exchanging authorization code for access token: ", error);
        // Handle the error appropriately in your application
    }
});

`

This, to try and re-direct back to canva.

This is the canva setup in the image below, and the auth0

Any ideas on how to approach this?

this is the current react setup.

`import { AppUiProvider } from "@canva/app-ui-kit";
import * as React from "react";
import { createRoot } from "react-dom/client";
import App from "./app";
import "@canva/app-ui-kit/styles.css";
import { Auth0Provider } from "@auth0/auth0-react";

const root = createRoot(document.getElementById("root")!);
function render() {
  root.render(
    <AppUiProvider>
      <Auth0Provider
        domain="https://us-central1-atomic-saga-xxx.cloudfunctions.net"
        clientId="xxx"
        authorizationParams={{
          redirect_uri: window.location.origin,
          response_type: "code",
        }}
      >
        <App />
      </Auth0Provider>
    </AppUiProvider>
  );
}

render();

if (module.hot) {
  module.hot.accept("./app", render);
}`
`// App.tsx
import React, { useEffect, useState } from "react";
import LoginButton from "./components/auth/Login";
import AuthenticatedApp from "./AuthenticatedApp";
import { useAuth0 } from "@auth0/auth0-react";
import Wrapper from "./components/auth/Loading";
import { auth } from "@canva/user";
import styles from "styles/components.css";
import { Rows } from "@canva/app-ui-kit";

const App: React.FC = () => {
  const [isCanvaAuthenticated, setIsCanvaAuthenticated] = useState(false);
  const { isAuthenticated } = useAuth0();

  useEffect(() => {
    const checkAuthentication = async () => {
      const token = await auth.getCanvaUserToken();
      setIsCanvaAuthenticated(token ? true : false);
    };

    checkAuthentication();
  }, []);

  if (isCanvaAuthenticated) {
    return (
      <div className={styles.scrollContainer}>
        <Rows spacing="2u">
          <Wrapper>
            User is authenticated with Canva.
            {isAuthenticated ? <AuthenticatedApp /> : <LoginButton />}
          </Wrapper>
        </Rows>
      </div>
    );
  } else {
    return (
      <div className={styles.scrollContainer}>
        <Wrapper>Please authenticate with Canva first.</Wrapper>
      </div>
    );
  }
};
export default App;`
// LoginButton.tsx
import React, { FC, useState } from "react";
import { useAuth0 } from "@auth0/auth0-react";

const LoginButton: FC = () => {
  const [isAuthenticating, setIsAuthenticating] = useState(false);
  const { loginWithRedirect } = useAuth0();

  const initiateAuthenticationFlow = async () => {
    console.log("initiateAuthenticationFlow");
    setIsAuthenticating(true);
    try {
      await loginWithRedirect();
    } catch (error) {
      console.error(error);
      setIsAuthenticating(false);
    }
  };

  return (
    <button onClick={initiateAuthenticationFlow} disabled={isAuthenticating}>
      {isAuthenticating ? "Authenticating..." : "Log In"}
    </button>
  );
};

export default LoginButton;

THis is currently not working.

receiving,

Refused to frame ‘https://dev-w4zhjgbo6zvcc1xf.us.auth0.com/’ because an ancestor violates the following Content Security Policy directive: “frame-ancestors ‘none'”.

among other issues.

THanks!

Expected to see, login, and working state flow, but currently just lots of bugs.

The file cannot be uploaded from the webpack

I have entered the “type:asset/resource” code in the webpack.config.js file. But I don’t think the file is loading. When I enter F12 developer mode from a web browser, there are no files in the source. How can I get the file to load normally?

      {
        test: /.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'images/[name].[ext]'
        },
      },
      {
        test: /.obj$/i,
        type: 'asset/resource',
        generator: {
          filename: 'object/[name][ext]',
        },        
        /* options: {
          name: './object/[name].[ext]'
        }, */
      },

webpack.config.js

// Generated using webpack-cli https://github.com/webpack/webpack-cli

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const WorkboxWebpackPlugin = require("workbox-webpack-plugin");
const nodeExternals = require('webpack-node-externals');

const isProduction = process.env.NODE_ENV == "production";

const stylesHandler = MiniCssExtractPlugin.loader;

const config = {
  entry: "./src/scripts/app.js",
  devtool: false,
  output: {
    filename: "scripts/[name].js",
    path: path.resolve(__dirname, "dist"),
    publicPath: "/",
    assetModuleFilename: 'images/[name][ext]',
  },
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.json', '.css', '.scss'],
    modules: ['src', 'node_modules'] // Assuming that your files are inside the src dir
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\/]node_modules[\/]/,
          name: 'vendors',
          chunks: 'all',
        },
      },
    },
  },
  devServer: { // here's the change
    /* static: {
      directory: path.join(__dirname, "./")
    }, */
    open: true,
    host: "localhost",
    port: 9000
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html",
    }),

    new MiniCssExtractPlugin({
      filename: './styles/style.css'
    }),

    // Add your plugins here
    // Learn more about plugins from https://webpack.js.org/configuration/plugins/
  ],
  module: {
    rules: [
      {
        test: /.(js|jsx)$/i,
        loader: "babel-loader",
        options: {
          presets: [
            [
              '@babel/preset-env', {
                targets: { node: 'current' },    // Only for nodes.
                modules: 'auto',
                useBuiltIns: 'usage'
              },
            ],
            // '@babel/preset-react',         If you use React.
            // '@babel/preset-typescript'     If you use Typescript.
          ],
        },
        exclude: ['/node_modules'],
      },
      {
        test: /.css$/i,
        use: [stylesHandler, "css-loader"],
      },
      {
        test: /.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'images/[name].[ext]'
        },
      },
      {
        test: /.obj$/i,
        type: 'asset/resource',
        generator: {
          filename: 'object/[name][ext]',
        },        
        /* options: {
          name: './object/[name].[ext]'
        }, */
      },

      // Add your rules for custom modules here
      // Learn more about loaders from https://webpack.js.org/loaders/
    ],
  },
};

module.exports = {
  target: 'node',
  externals: [nodeExternals()]
}

module.exports = () => {
  if (isProduction) {
    config.mode = "production";

    config.plugins.push(new WorkboxWebpackPlugin.GenerateSW());
  } else {
    config.mode = "development";
  }
  return config;
};

app.js

import styleCSS from '../styles/style.css';
import image from '../images/image.jpg';
import monkeyObj from '../object/monkey.obj';

Ajax post , server feedback “Method Not Allowed

I’m facing Ajax post , server feedback “Method Not Allowed

(error pic) xhr ststus 422

I only see this much of error message, therefore, I couldn’t fix by myself

here is the code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script src="https://cdn.datatables.net/1.13.5/css/jquery.dataTables.min.css"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
    <script src="https://cdn.datatables.net/1.13.5/js/jquery.dataTables.min.js"></script>
</head>

<body>
    <table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>First name</th>
                <th>Last name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>First name</th>
                <th>Last name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>

    <script>
        $(document).ready(function () {
            const getToken = localStorage.getItem("token");
            const accountType = localStorage.getItem("acc_type");

            console.log("GET TOKEN", getToken);


            var table = $("#example").DataTable({
    processing: true,
    serverSide: true,
    ajax: {
        url: "http://192.168.30.03:3000/api/log/list",
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify({
            limit: 13,
            offset: 1,
            search: "",
            id: 0,
            start_id: 0,
            end_id: 0,
            event: "",
            user: "",
            message: "",
            type: "",
            start_time: "",
            end_time: "",
            order_by: "desc",
            order_column: "id"
        }),
        headers: {
            'Authorization': 'Bearer ' + getToken
        },
        success: function (response) {
            console.log("SUCCESS", response);
        },
        error: function (response) {
            console.log("ERROR", response);
        }
    },
    columns: [
        { data: "id", title: "id" },
        { data: "event", title: "event" },
        { data: "user", title: "user" },
        { data: "message", title: "message" },
        { data: "type", title: "type" },
        { data: "created_at", title: "created_at" },
    ],
});

table.draw();

        });
    </script>


ps. I’m doing with https://datatables.net/examples/data_sources/server_side, that only loading few amount of data, while viewing table

firebase security rules when writing and reading from non authenticated server

im making firebase write calls from my next js api route backend. i want to add security rules that only let you write and read in docs of your uid, but when im writing from the backend, auth is null becasue you are signed in on the frontend not the backend. What do i do? im sure this is a common problem. I have seen that you can deny all read/write in your rules and use the admin SDK in backend to do reads/writes, but all my code is already using setDoc, getDoc, etc and I don’t want to change it all

Retrieve a setCookie and processing a jQuery.Post

I am have trouble retrieve a setCookie and running a jQuery.Post with the data that is retrieved. Is marked in code //Post Issue

<script type="text/javascript">// <![CDATA[
jQuery( document ).ready(function() {
          
          checkCookie()
          });
            
          function saveForm(){
          $current_url  = window.location
          $code_em = document.getElementById("cmsEM").value
          
          $url = "/validtrackcms_2302.php?cronsafe=mRT0SmaUDzDv2tgKfJhOzowifnyPc4&current_url="+$current_url+"&code_em="+$code_em+"&name=null&phone=null&company=null";
          $urlcookie = "/validtrackcms_2302.php?cronsafe=mRT0SmaUDzDv2tgKfJhOzowifnyPc4&current_url="+$current_url+"&code_em="+$getCode_em+"&name=null&phone=null&company=null";

          jQuery.post( $url, function( data ) {
            console.log(data)
            if(data != 1){
            //show the error message
            alert("OOPS!")
            }else{
            setCookie("cmsuser",new Date().getTime(), 1)
            setCookie("pevent", "live",1)
            setCookie("page_url_live","2302",1)
            setCookie("code_em",$code_em,1)
            window.location.reload()
            {"}"}
            {"}"});
            
            }
            
            
            //cookie section
            function setCookie(cname, cvalue, exdays) {
              var d = new Date();
              d.setTime(d.getTime() + (exdays * 24 * 60 * 1000));
              var expires = "expires="+d.toUTCString();
              document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
            }
            
            function getCookie(cname) {
              var name = cname + "=";
              var ca = document.cookie.split(';');
              for(var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                  c = c.substring(1);
                }
                if (c.indexOf(name) == 0) {
                  return c.substring(name.length, c.length);
                }
              }
              return "";
            }
            
            function checkCookie() {
              var cmsuser = getCookie("cmsuser");
              var pevent = getCookie("pevent");
              var page_url_live = getCookie("page_url_live");
              var getCode_em = getCookie("code_em");
              if(pevent != "live" ){
              jQuery('#modalWin').modal({backdrop: 'static', keyboard: false})
            }else{
              jQuery('#modalWin').remove();
 //Post Issue
              jQuery.post( $urlcookie, function( data_urlc );
              console.log(data_urlc);
            }
            }
  
// ]]></script>

Project works on codepen but not on IDE

I’m trying to reverse engineer an animation from this codepen

my HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="script.js"></script>
    <canvas id="hero-lightpass"></canvas>  
</body>
</html>

My CSS

html {
height: 100vh;
}

body {
background: #000;
height: 500vh;
}

canvas {
position: fixed;
left: 50%;
top: 50%;
max-height: 100vh;
max-width: 100vw;
transform: translate(-50%, -50%);
}

h1 {
    color: white;
}

My JS:

// Canvas settings
    const canvas = document.getElementById("hero-lightpass");
    const context = canvas.getContext("2d");

    canvas.width=1158;
    canvas.height=770;

    
    // Preloading images to drastically improve performance
    const currentFrame = index => (`https://www.apple.com/105/media/us/airpods-pro/2019/1299e2f5_9206_4470_b28e_08307a42f19b/anim/sequence/large/01-hero-lightpass/${index.toString().padStart(4, '0')}.jpg`);
    const frameCount = 148; // There 148 images for that animation-sequence to load
    const images = [];

    const preloadImages = () => {
        for (let i = 1; i < frameCount; i++) {
            images[i] = new Image(); // This is functionally equivalent to document.createElement('img').
            images[i].src = currentFrame(i);
        }
    };

    preloadImages();


    // Draw the first image
    const img = new Image();
    img.src = currentFrame(1);
    img.onload = function(){
        context.drawImage(img, 0, 0);
    }


    // Scroll interactions
    const html = document.getElementsByTagName('html');
    
    window.addEventListener('scroll', () => {  
        const scrollTop = html[0].scrollTop;
        // console.log('scrollTop: ', scrollTop);
        // console.log('html.scrollHeight: ', html[0].scrollHeight);
        // console.log('window.innerHeight: ', window.innerHeight);
        const maxScrollTop = html[0].scrollHeight - window.innerHeight;
        const scrollFraction = scrollTop / maxScrollTop;
        const frameIndex = Math.min(
            frameCount - 1,
            Math.floor(scrollFraction * frameCount)
        );
        // console.log('FrameIndex', frameIndex);

        requestAnimationFrame(() => context.drawImage(images[frameIndex + 1], 0, 0));

    });

but it doesn’t work on my computer for some reason. It gives me the error message

“Uncaught TypeError TypeError: Cannot read properties of null (reading ‘getContext’)
at (/home/philocalyst/Desktop/test/script.js:3:32)”
in my terminal and

“Uncaught TypeError: canvas is null
file:///home/philocalyst/Desktop/test/script.js:3”
in my console

the code is an exact copy of the codepen, but with the linking of the css and javascript. I can’t figure out what I did wrong.

I tried linking the two together and reading the code and messages.

Disable current date and +31 days from the current day but Enables after the 31 days – datepicker

I’m trying to disable current and future 31 days from date.

Right now I can only get it to disable specific dates but not what I actually need. I am using below code to disable to the dates.

I would really appreciate the help if possible.

var dates = []; 
function DisableDates(date) {
    var string = jQuery.datepicker.formatDate('dd/mm/yy', date);
    return [dates.indexOf(string) == -1];
}
$(function() {
     $("#date").datepicker({
         beforeShowDay: DisableDates
     });
});

HTML assign variables to element name

Is there a way to assign variable to an Element Name so that I can access the element and change the values:


[% FOREACH field IN ['id','type','updatedt','lastcheckdt'] %]
    <div class="row col-md-3 col-sm-6">
        <dl class="details-dl">
            <label>[% field %]</label>
            <div class="details-dg">
                <dd name=[% field %] class="float-right">[% order.$field %]</dd>    
            </div>
        </dl>
    </div>
[% END %] 

I can format the datetime for updatedt:

let dt_formatted = convertDateFormat("[% order.updatedt %]");
$( "[name='updatedt']" ).val(dt_formatted);

Unfortunate assigning [ % field %] to name does not assign any value to name:

<dd name=[% field %] class="float-right">[% order.$field %]</dd>    

How do I make it move at the same slope in javascript(or jquery)?

I have a question.

I want to make an animation where .img2 pass through the background(.wrap) at the same slope.

code link

// when start button clicked
$('.img2').animate({
  top: '', // ??
  left: '', // ??
}, 1000)

This is an example picture.

enter image description here

An example code set .wrap width: 300px, height: 300px, but It can be change to other width and height in work.

I’am confused that how can I set top and left.
(I’m not good at math..).

Make Like button in react.js

I wan’t to make the only selected button change not all in the same time when i clicke on it

I’ve created this function which contains a Boolean state and the toggle it

 const [like, setLike] = useState(false);
 
  const handleLike=()=>{
    setLike(!like)
    console.log(like);
  }

and called it here iside the map

 return (
    <Grid container spacing={1} px="4%" width='100%' >
      {CardData.map((e, idx) => (
          <Box
            sx={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              padding: 0,
              border: "1px solid #e0e0e07a",
              position: "relative",
              borderRadius: "1.5rem",
              width: "94%",
              boxShadow: "5px 5px 46px -46px #000000",
            }}
            mb={5}
            key={idx}
          >
            <Box width='100%' >
              
              <Box position="absolute" top=".4rem" right=".8rem">
                <IconButton
                  aria-label="fingerprint"
                  color="default"
                  sx={{
                    zIndex: "4",
                    bgcolor: "#4b4d4eb2",
                    width: "2rem",
                    padding: "4px",
                  }}
                  onClick={(e)=>handleLike(e)}
                >
                {like?<FavoriteIcon sx={{ width: ".8em", color: "#fff" }} />: <FavoriteBorderIcon sx={{ width: ".8em", color: "#fff" }} />}
                  
                  
                </IconButton>
              </Box>
              </Box>
            </Box>
</Grid>

Run one request after another in JEST

I’m doing a test using Jest and I’ve passed all of them. The problem is that at the end I want to delete all the test data I inserted into de database with afterAll. I want this to be in order. First, delete the file, then the folder, and at the end the user (the foreign keys give problems). I haven’t been able to find a way to this in that order. I tried with then() but didn’t work. Here’s the code:

afterAll(async () => {
  const findTestFileReq = await api.post('/files/find/').send({ name: 'Test' });
  const testFile = findTestFileReq.body.data[0].id;
  await api.delete(`/files/delete/${testFile}`);

  const findTestFolderReq = await api.post('/folders/find/').send({ path: '/' });
  const testFolder = findTestFolderReq.body.data[0].id;
  await api.delete(`/folders/delete/${testFolder}`);

  const findTestUserReq = await api.post('/users/find/').send({ username: 'TestName' });
  const testUser = findTestUserReq.body.data[0].id;
  await api.delete(`/users/delete/${testUser}`);
});

why formdata is alwase empty ? fullstack problem

iam trying to use it to send img to multer in node to upload the img
but alwase get me a null

i tryed to restart the whole project but nothing

here front part :

`const addPostsHundler = (e)=>{
  e.preventDefault();

  const form = new FormData().append('file',file);

  
  
  

  axios.post('http://localhost:5000/Upload', {form :form , inputs : input ,userID : data.user_id}) 
  .then(res => {
    
    console.log(res)
  })
  .catch(err => console.log(err)) 
  
}`

and back part :

`const multer = require('multer')

let fileName;`your text`

const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../client/public/upload')
},
filename: function (req, file, cb) {
 fileName = file.originalname
cb(null, fileName )
}
})

app.post('/Upload',upload.single('file'),(req,res)=>{

res.status(200).json({message : 'img stored' , img : fileName})
 })`

animationpresense in Next.js 13

could someone please tell me how to convert this code into Next.js 13? I am attempting to create a page animation using Framermotion, but I am struggling to figure out the process in Next 13.

 `// _app.js

     import { AnimatePresence } from 'framer-motion'

     function MyApp({ Component, pageProps, router }) {
     return (
        <AnimatePresence mode="wait" initial={false}>
      <Component {...pageProps} key={router.asPath} />
       </AnimatePresence>
      );
       } 

My Discord bot just doesn’t send any messages and there’s no problem in the code

It’s not the first time, the bot just doesn’t respond to commands even with the complete code.

I already added functions to show an error in the console, but the bot simply receives the command and doesn’t run it.

For technical purposes, I’m using Repl.it, Node.js, Discord.js v14.

I’m developing code for a Discord Bot that creates a ticket with buttons, that is, when executing a command the bot should send the message with the buttons and when selecting the buttons the user should have created a ticket channel.

In short, that was just it, as I already knew that my js bots commonly don’t work, I didn’t make a complex code.