Ways to analyze users who have clicked a button

After a user registers, they are automatically taken to /proto where they can view a list of animals available for adoption. However, the challenge lies in identifying the specific user who clicked the button (as this information must be associated with the selected pet) and redirecting them to the /adminPage. Below is the code snippet from my app.js file:

//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');
var multer = require('multer');

var mongoose = require('mongoose');
 var imgModel = require('./model');

const app = express();

// Code continues...

Now, let's take a look at my /prototype.ejs file:

<%- include('partials/header') %>
<div class="row">

  <%  items.forEach(function(items){ %>
<div class="card col-lg-4 col-md-6">

  <img alt="John" style="width:100%" src="data:image/<%=items.img.contentType%>;base64,
                     <%=items.img.data.toString('base64')%>"> 
  <h6><%=items.name%></h6>
  <h6><%=items.dob%></h6>
    <h6><%=items.breed%></h6>
       <h6><%=items.details%></h6>

  <p><button>adopt</button></p>
   </div>
        <% }) %>



</div>

<%- include('partials/footer') %>

Looking at /register.ejs:

<div class="container mt-5">
  <h1>Register</h1>

  <div class="row">
    <div class="col-sm-8">
      <div class="card">
        <div class="card-body">

          <!-- Register form goes here -->

        </div>
      </div>
    </div>

  </div>
</div>

<%- include('partials/header') %>

Finally, let's discuss adminPage.ejs:


<%- include("partials/header"); -%>
<section class="colored-section" id="adminTitle">

    <div class="container-fluid">

      <!-- Nav Bar -->

      <nav class="navbar navbar-expand-lg navbar-dark">

        <a class="navbar-brand" href="">AAS</a>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarTogglerDemo02">

          <ul class="navbar-nav ml-auto">
            <li class="nav-item">
              <a class="nav-link" href="/addNew">Add new</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#pricing">Show adopted</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#cta">View All</a>
            </li>
          </ul>

        </div>
      </nav>


<%- include("partials/footer"); -%>

If you need further clarification on any specific part, feel free to ask!

Answer №1

If you're working on an app that needs user signup and authentication, consider integrating user authentication using JSON Web Tokens like this (https://www.npmjs.com/package/jsonwebtoken). With Express, creating authentication middleware is possible (https://expressjs.com/en/guide/using-middleware.html). When authenticating the user in the middleware function, insert the user object from Mongoose onto the request object passed to the route by Express. Here's a sample:

const jwt = require('jsonwebtoken')
const User = require('../models/user')

const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer ', '')
        const decoded = jwt.verify(token, 'shhh')
        const user = await User.findOne({ _id: decoded._id, 'tokens.token': token })
        
        if (user) {
            req.user = user
            req.token = token
            next()
        } else {
            throw new Error()
        }
    } catch (error) {
        res.status(401).send({ error: 'Please authenticate'})
    }
}

module.exports = auth

Remember, this is only part of the solution. You'll also need to send a valid token back to the client and store it in your User model within the login route handler. Ensure the client includes a valid token in the Authorization Header of the HTTP request sent to the server. Setting req.user = user in the example above is key, as it gives access to the user in your route handler via the req object, allowing you to identify the arriving user.

Answer №2

The issue was successfully resolved through the implementation of Passport.js.

This advanced tool allows access to key fields like req.user, providing information on the currently logged-in authorized user.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Recompiling Node.js/npm packages after copying an app

Scenario: In the setup, there is a virtual machine with internet access where the command npm install is run to install app dependencies. This results in a folder containing the app and its dependencies in node_modules. One of the app modules is mong ...

Having trouble implementing ffprobe with fluent-ffmpeg

My original plan was to utilize the ffprobe function for extracting video information. Below is the code I wrote: var FFmpeg = require('fluent-ffmpeg'); //... var convert_using_ffmpeg = function (source, target) { var tempfile = path.join(c ...

Loop through items in a list using Angular.js and display each item within an <

I am facing an issue where the model returned from the server contains html tags instead of plain text, such as b tag or i tag. When I use ng-repeat to create a list based on this model, the html is displayed as pure text. Is there a filter or directive av ...

The successful execution of $.ajax does not occur

Starting out with ajax, I wanted to create a simple add operation. Here is the code that I came up with: HTML: <!doctype html> <html> <head> <title>Add two numbers</title> <meta content="text/html;charset=utf-8" h ...

Struggling to get passport.js to verify credentials

I am in the process of developing a basic application where after the user registers, they should be directed to a login page to re-enter their credentials. Subsequently, they should be redirected to the home page. However, this flow is not occurring as ex ...

An HTML form featuring various submit buttons for accomplishing different tasks

After searching extensively, I have come across solutions that are similar but not quite right for my specific situation. Here's what currently works for me: <script type="text/javascript"> function performTask1(a, b) { window.open('intern ...

Encountering difficulties when attempting to upload a file to Google Cloud Platform using Multer in a Node.js

I am currently experimenting with uploading a single file using Multer and the "multipart/form-data" content type to a Google Cloud Storage bucket. For this task, I am utilizing "Multer.memoryStorage()" and "@google-cloud/storage" try { const docume ...

Issue with installing packages using node.js 9 and npm 5.5.1: encountering errors during installation process

After recently updating my project to node.js 9.1.0 (and bundle nom 5.5.1), I am encountering errors when trying to run the installation process. Even with verbose output in the logs, I am struggling to pinpoint where exactly the problem lies. Any assist ...

The Image component in a test within Next.js was not wrapped in an act(...) during an update

After setting up a basic NextJS app with create-next-app and integrating Jest for testing, I encountered an error message stating "An update to Image inside a test was not wrapped in act(...)". The issue seems to be related to the Image component in NextJS ...

Several jquery libraries are experiencing malfunctions

<head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $(".slidingDiv").hide(); $(".show_hide").show().click ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

Running two instances of the Express server within a single application

Currently, I am running two separate express servers within a single Node.JS application. The purpose is to have 2 distinct sockets for running 2 different services simultaneously. However, there is a limitation with Google Cloud and Heroku as they do no ...

Is the $slice feature integrated into the php driver?

Can I use the '$slice' feature with the update() and $push functions in MongoDB? I have already attempted this, both with and without casting to (object). $db->collection->update( array('_id' => new MongoId($id)), ...

Creating a basic bar graph using d3.js with an array of input data

In my dataset, I have an array of form data that includes items like 'Male', 'Female', 'Prefer Not To Say'. I want to create a simple bar chart generator using D3.js that can display the percentages or counts of each item in t ...

Managing the re-rendering in React

I am encountering a situation similar to the one found in the sandbox example. https://codesandbox.io/s/react-typescript-fs0em My goal is to have Table.tsx act as the base component, with the App component serving as a wrapper. The JSX is being returned ...

After deploying to the production server, Next.js is failing to fetch images using the image URL

Our production deployment setup includes a network of 3 linux machines, with two dedicated to deployment and one serving as an nginx proxy. For development deployment, we utilize a separate linux machine. Within our frontend (built using the nextjs framew ...

Exploring the power of Node.js and underscore.js for advanced templating capabilities

My question is quite simple. I am using Node.js with Underscore as the templating engine, all within the Expressjs framework. I am attempting to create partials similar to other programming languages: <% include('header') %> <body id ...

Discover the Location and Sign Up for Angular2+ Service

I'm currently using the Google Maps API to retrieve a user's geoLocation data, including latitude and longitude. My goal is to pass this information to a web API service in order to receive JSON output of surrounding addresses. I have implemented ...

Display information when hovering over a tag

I'm working on adding a feature where hovering over a link will display a tooltip. For reference, here is an example: https://i.stack.imgur.com/K84Wf.png Are there any alternative JavaScript libraries that offer this functionality? (ideally similar ...

npm ERROR! Failed to delete the specified tarball

While attempting to install Express and its dependencies, I encountered an error that seems to be hindering my progress. The log is too complex for me to decipher, with several warnings making it difficult to pinpoint the specific issue causing problems. ...