Why is my Server responding with {Auth: False}?

I’ve been having this issue for a week now. I feel like I’ve wasted so much time.

I’ll tell you the issue, then what I’ve done at the end.

Right Now I’ve got both Ends on custom Domains, with Heroku hosting.

Passport Local Logs me in

2022-02-17T06:39:06.949016+00:00 heroku[router]: at=info method=OPTIONS path="/login" host=www.thehoodconservative.com request_id=ff2dc525-7feb-4a2b-afe8-41ca7cc9610e fwd="172.58.196.240" dyno=web.1 connect=0ms service=4ms status=204 bytes=369 protocol=http
2022-02-17T06:39:07.069432+00:00 app[web.1]: Logged in

From this Code

passport.use(
  new LocalStrategy(customFields, (username, password, done) => {
    User.findOne({ username: username })
      .then((user) => {
        if (!user) {
          console.log("No user");
          return done(null, false);
        } else {
          const isValid = validPassword(password, user.hash, user.salt);
          if (isValid) {
            console.log("Logged in");

            return done(null, user);
          } else {
            console.log("Wrong Password");
            return done(null, true);
          }
        }
      })
      .catch((err) => {
        done(err);
      });
  })
);

Yet I get this Response in the console

{auth: false, msg: 'Here'}

from this code on my backend

module.exports.isAuth = (req, res, next) => {
  if (req.isAuthenticated()) {
    next();
    // res.status(200).json({ user: req.user, auth: true });
  } else {
    return res.status(401).json({ auth: false, msg: "Here" });
  }
};

I have this in my Cookie storage

deviceId    D0E8508F-7685-4C9D-AFB6-522EE27A3B93    localhost   /   Session 44  

but the session in my DB doesnt show that number, it shows.

_id
:
"g3NYIQ7usEIJ5K8ETP1S-mDZImKy4Xj7"
expires
:
2022-02-18T06:50:34.597+00:00
session
:
"{"cookie":{"originalMaxAge":86400000,"expires":"2022-02-18T06:50:34.59..."

My history of aggravation

I started with Having my BE (Backend) on heroku and FE on Netlify.

Some guy on here told me its for some reasons its better to have my FE on Heroku along with BE so I did. Still same result. After hours of fussing around and changing random things and going through SOF, I read through what I saw was issues with Heroku not being able to set Cookies, somethoing about Public Suffix list. So Through a bunch of research I came to the conclusion I need to host my BE and FE on custom domains. Which I’ve done now. Yet now its the same exact issue.

I have a feeling I need lessons on debugging Cookies, but I have no idea how to do that. When I had this local, both FE and BE, It worked.

I would love it if someone showed me a better place than Heroku to host and make this work. I dont care what I have to do to get this to work.

I’m also a newbie, this is my first full stack project, without a tutorial, so I’m not sure what I need to share and dont want to spam this with too much code, just comment what you need to see, and I’ll edit this post.

Upload byte array from axios to Node server

Background

Javascript library for Microsoft Office add-ins allows you to get raw content of the DOCX file through getFileAsync() api, which returns a slice of up to 4MB in one go. You keep calling the function using a sliding window approach till you have reed entire content. I need to upload these slices to the server and the join them back to recreate the original DOCX file.

My attempt

I’m using axios on the client-side and busboy-based express-chunked-file-upload middleware on my node server. As I call getFileAsync recursively, I get a raw array of bytes that I then convert to a Blob and append to FormData before posting it to the node server. The entire thing works and I get the slice on the server. However, the chunk that gets written to the disk on the server is much larger than the blob I uploaded, normally of the order of 3 times, so it is obviously not getting what I sent.

My suspicion is that this may have to do with stream encoding, but the node middleware does not expose any options to set encoding.

Here is the current state of code:

Client-side

public sendActiveDocument(uploadAs: string, sliceSize: number): Promise<boolean> {
  return new Promise<boolean>((resolve) => {
    Office.context.document.getFileAsync(Office.FileType.Compressed,
      { sliceSize: sliceSize },

      async (result) => {
        if (result.status == Office.AsyncResultStatus.Succeeded) {

          // Get the File object from the result.
          const myFile = result.value;
          const state = {
            file: myFile,
            filename: uploadAs,
            counter: 0,
            sliceCount: myFile.sliceCount,
            chunkSize: sliceSize
          } as getFileState;

          console.log("Getting file of " + myFile.size + " bytes");
          const hash = makeId(12)
          this.getSlice(state, hash).then(resolve(true))
        } else {
          resolve(false)
        }
      })
  })
}

private async getSlice(state: getFileState, fileHash: string): Promise<boolean> {
  const result = await this.getSliceAsyncPromise(state.file, state.counter)

  if (result.status == Office.AsyncResultStatus.Succeeded) {

    const data = result.value.data;

    if (data) { 
      const formData = new FormData();
      formData.append("file", new Blob([data]), state.filename);

      const boundary = makeId(12);

      const start = state.counter * state.chunkSize
      const end = (state.counter + 1) * state.chunkSize
      const total = state.file.size

      return await Axios.post('/upload', formData, {
        headers: {
          "Content-Type": `multipart/form-data; boundary=${boundary}`,
          "file-chunk-id": fileHash,
          "file-chunk-size": state.chunkSize,
          "Content-Range": 'bytes ' + start + '-' + end + '/' + total,
        },
      }).then(async res => {
        if (res.status === 200) {
          state.counter++;

          if (state.counter < state.sliceCount) {
            return await this.getSlice(state, fileHash);
          }
          else {
            this.closeFile(state);
            return true
          }
        }
        else {
          return false
        }
      }).catch(err => {
        console.log(err)
        this.closeFile(state)
        return false
      })
    } else {
      return false
    }
  }
  else {
    console.log(result.status);
    return false
  }
}

private getSliceAsyncPromise(file: Office.File, sliceNumber: number): Promise<Office.AsyncResult<Office.Slice>> {
  return new Promise(function (resolve) {
    file.getSliceAsync(sliceNumber, result => resolve(result))
  })
}

Server-side

This code is totally from the npm package (link above), so I’m not supposed to change anything in here, but still for reference:

makeMiddleware = () => {
    return (req, res, next) => {
        const busboy = new Busboy({ headers: req.headers });
        busboy.on('file', (fieldName, file, filename, _0, _1) => {

            if (this.fileField !== fieldName) {  // Current field is not handled.
                return next();
            }

            const chunkSize = req.headers[this.chunkSizeHeader] || 500000;  // Default: 500Kb.
            const chunkId = req.headers[this.chunkIdHeader] || 'unique-file-id';  // If not specified, will reuse same chunk id.
            // NOTE: Using the same chunk id for multiple file uploads in parallel will corrupt the result.

            const contentRangeHeader = req.headers['content-range'];
            let contentRange;

            const errorMessage = util.format(
                'Invalid Content-Range header: %s', contentRangeHeader
            );

            try {
                contentRange = parse(contentRangeHeader);
            } catch (err) {
                return next(new Error(errorMessage));
            }

            if (!contentRange) {
                return next(new Error(errorMessage));
            }

            const part = contentRange.start / chunkSize;
            const partFilename = util.format('%i.part', part);

            const tmpDir = util.format('/tmp/%s', chunkId);
            this._makeSureDirExists(tmpDir);

            const partPath = path.join(tmpDir, partFilename);

            const writableStream = fs.createWriteStream(partPath);
            file.pipe(writableStream);

            file.on('end', () => {
                req.filePart = part;
                if (this._isLastPart(contentRange)) {
                    req.isLastPart = true;
                    this._buildOriginalFile(chunkId, chunkSize, contentRange, filename).then(() => {
                        next();
                    }).catch(_ => {
                        const errorMessage = 'Failed merging parts.';
                        next(new Error(errorMessage));
                    });
                } else {
                    req.isLastPart = false;
                    next();
                }
            });
        });

        req.pipe(busboy);
    };
}

How do i capture the href instead of the google? [closed]

sorry, really a newbie at this. how do i copy the href instead of google?

<a id="test" href="https://www.google.com">Google</a>
<button onclick="copyToClipboard('#test')">Copy to clipboard</button>

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

Supabase Not Able To pdate entire row using JSON objects

I want to update my supabase table with an object which I have got as input from the user.

I keep getting 404 Error. Is this happening cause supabase doesn’t support it yet? (RLS is disabled for now)

    const { data, error } = await supabase
      .from("company")
      .update(inputFields.values)
      .match(originalFields.values);
  };

This is what inputFields.values / originalFields.values look like.
Only the first 3 values are being updated not the entire row.

inputFields = {
    "name": "Piramal Glassed", #NEW
    "email": "[email protected]", #NEW
    "contact": "98203" #NEW
    "pin": 400066, #SAME AS ORIGINAL
    "city": "Mumbai", #SAME AS ORIGINAL
    "state": "Maharashtra", #SAME AS ORIGINAL
    "country": "India", #SAME AS ORIGINAL
}

originalFields = {
    "name": "Tata Steel",
    "email": "[email protected]",
    "contact": "982031132112"
    "pin": 400066,
    "city": "Mumbai",
    "state": "Maharashtra",
    "country": "India",
}

Date-fns: Countdown to a specific date

I’m using date-fns. I need to create a countdown to the next 10th of the month.

For example, if today is 5th Feb, then the countdown should be to 10th Feb. If today is say 15th Feb, then it should count to 10th March, and so on.

How can I do this with date-fns or even with plain javascript?

logout confirmation message is not working laravel-8

I laravel I am trying to create a logout confirmation message when I click on my logout button
for this I have done this to my navebar.blade.php

<a class="dropdown-item" id="logout" href="{{ route('admin.logout') }}">
{{ __('Logout') }}
</a>

and this to my admin.blade.php but not working but it should work

<script>
        $(docoment).on("click", "#logout", function(e) {
            e.preventDefault();
            var link = $(this).attr("href");
            swal({
                    title: "Are you Want to logout?",
                    text: "",
                    icon: "warning",
                    buttons: true,
                    dragerMode: true,
                })
                .then((willDelete) => {
                    if (willDelete) {
                        window.location.href = link;
                    } else {
                        swal("Not Logout");
                    }
                });
        });
    </script>

Fetch API cannot read properties of undefined foreach [duplicate]

I’m trying to fetch data from the Nasa images API:
https://images.nasa.gov/docs/images.nasa.gov_api_docs.pdf
The issue I’m having is when I am trying to use a foreach loop on the array I get the error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘forEach’)
at (index):22:22
my code is

                const url =`https://images-api.nasa.gov/search?q=${query}`;
            fetch(url)
            .then(response => response.json())
            .then((jsonData) => {
                console.log("success");
                console.log(jsonData);
                let items = jsonData.collection['items'];
                for(let i = 0; i < items.length - 80; i++) {
                    let linksArr = items[i].links;
                    linksArr.array.forEach(el => {
                        console.log(el.href);
                        const imgHref = el.href;

                        var img = document.createElement('img');
                        img.src = imgHref;
                        console.log(img)
                        results.appendChild(img);
                    });
                }
            });

This is where I’m testing it if anyone can offer any tips or solutions I would be grateful, thank you
https://codepen.io/user843/pen/gOXobZZ

react-leaflet polygon eventHandler not working

Simple question, I am dynamically rendering Polygons using react-leaflet.

The polygons appear as expected. However, whatever i attach to eventHandlers does not work.

  const highlightFeature = (e) => {
    console.log(e);
    let layer = e.target;
    layer.setStyle({
      color: "black",
      fillColor: "black"
    });
  };

let indents = [];
  lightRailStop.features.map((feature, index) => {
    indents.push(
      <Polygon
        positions={feature.geometry.coordinates}
        clickable={true}
        color={"red"}
        stroke={false}
        fillOpacity={0.45}

        // This is not working!
        eventHandlers={{
          mouseover: highlightFeature,
          click: () => {
            console.log("marker clicked");
          }
        }}
      />
    );
  });

Why is this so, and how do i fix it?

Full fiddle:
https://codesandbox.io/s/scratchpad-without-geojson-b8jsp5

Visual list mapping library

I am wondering if there are any existing list mapping javascript library that allow the users to build two lists and then map elements from one list to another. Below is an example/mock-up of what I mean:

enter image description here

I think this is a combination of tree view components (or maybe an outliner component where every bullet is a separate block) and then a block/node connector component. There are quite a few visual node-based programming frameworks which have this type of UI.

I’ve been playing around with d3 and even svg directly to build some mock-ups, but it would be really helpful to start with some foundation and then add what is missing. Obviously, if there is something like this already, that would be even more amazing.

Any suggestions or examples would be greatly appreciated.

OLX clone load more

I am working in OLX India clone in which I have created a Load More button. But the problem is that when I see the result, initially some of the items are not being hidden in the Load More button. So when I click on the Load More button, even when I have provided functionality to it using Javascript, it is not actually working, its effect is not being shown on my OLX clone. But CSS is working fine.
Javascript:

$( document ).ready(function () {
  $(".moreBox").slice(0, 3).show();
    if ($(".blogBox:hidden").length != 0) {
      $("#loadMore").show();
    }   
    $("#loadMore").on('click', function (e) {
      e.preventDefault();
      $(".moreBox:hidden").slice(0, 6).slideDown();
      if ($(".moreBox:hidden").length == 0) {
        $("#loadMore").fadeOut('slow');
      }
    });
  });

enter image description here

Why in the nested loops await not wait?

In the nested loops I have async await. For me it is important that on each iteration loop will wait until await will be finished/data received and the start next iteration.
Also this method used in the another loop.

const _sampleFilters = async (
  pageName,
  details,
  available,
) => {
  for (const filterName of Object.keys(details)) {
    for (const filterValue of Object.keys(details[filterName])) {
      const data = (await fetchDetails(
        pageName
      ));

      details[filterName][filterValue].allDetails = cloneDeep(
        getProcessedData(
          data.map(data => data.value),
          available,
          pageName,
        ),
      );
    }
  }
};
for (const item of items) {
   _sampleFilters();
}

Basic Node Commands Not Working After Updating NodeJS

I’ve attempted to update my node version by deleting nodejs file from ProgramFilesx86 folder and using the windows installer to install the latest file. When I go to try and initialize a node project or npx create-react-app it gives me the following:

TypeError: Class extends value undefined is not a constructor or null
    at Object.<anonymous> (C:UsersMickellAppDataRoamingnvmv13.8.0node_modulesnpmnode_modulessocks-proxy-agentdistagent.js:114:44)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1151:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)     
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (C:UsersMickellAppDataRoamingnvmv13.8.0node_modulesnpmnode_modulessocks-proxy-agentdistindex.js:5:33)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1151:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)     
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (C:UsersMickellAppDataRoamingnvmv13.8.0node_modulesnpmnode_modulesmake-fetch-happenlibagent.js:169:25)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
Could not determine Node.js install directory

What am I doing wrong?

In Hackerrank tests, how to build a JavaScript Queue quickly and efficiently

Like many CS college students, I actively apply to jobs and get Hackerrank assessments from companies. My question is regarding JavaScript Queue. When taking Hackerrank tests, one has a limited amount of time, and implementing a fancy Queue class is not the best option. Using shift() and unshift()on Array is a quick fix, but I worry this would become too slow with certain test cases.

LeetCode on the other hand, provides the JavaScript environment with 2 packages from NPM to assist with data structures, datastructures-js/priority-queue and datastructures-js/queue. So when I practice on Leetcode, I can do const aQueue = new Queue(); but this would not work in Hackerrank, which is what most companies use for recruiting. Is there a way to import the same package in Hackerrank? I’ve tried const { Queue } = require('@datastructures-js/queue'); but no good.

If Hackerrank doesn’t let me import these, what’s a quick way to make JS Queue other than using shift() and unshift()

JEST Test Get Value From Oracle Database

Hello Guys I want to tested with JEST but i have an problem when i want to get query result with console log but always have undefined result the condition is i just select 1 column but when i’m trying to test the connection test pass but only not showing the query result here’s my code

export {};
const chai = require('chai');
const sinon = require('sinon');
const oracledb = require('oracledb');
import config  from '../utils/dbconfig.js';

const expect = chai.expect;

sinon.stub(oracledb, 'getConnection').resolves({
  execute: function() {},
  close: function() {}
});

describe('Parent', () => {
  describe('child', () => {
    it('should work', async () => {
      let conn;
      const sql= `select * from table1 where id=0040101347001`;

      try {
        conn = await oracledb.getConnection(config);
        var result:string = await conn.execute(sql);
        console.log("Leads: "+ result);

      } catch (err) {
        console.error(err);
      } finally {
        if (conn) {
          try {
            await conn.close();
          } catch (err) {
            console.error(err);
          }
        }
      }
    },60000);
  });
});