What is the process for adding a user to a database with Passport.js? How can I adjust current routes to ensure authentication is required?

Got a few inquiries. I established authentication in my application using the code below:

passport.use(new LocalStrategy(function(username, password, done){
    Users.findOne({ username : username},function(err,user){
        if(err) { return done(err); }
        if(!user){
            return done(null, false, { message: 'Incorrect username' });
        }

        hash( password, user.salt, function (err, hash) {
            if (err) { return done(err); }
            if (hash == user.hash) return done(null, user);
            done(null, false, { message: 'Incorrect password' });
        });
    });
}));

app.get('/admin', function (req, res){
    res.render('login.jade');
});

app.post('/admin', function (req, res){
    passport.authenticate('local', { successRedirect: '/main',
                                     failureRedirect: '/login',
                                     failureFlash: true });
});

The User data schema includes username, password, and hash.

First question - How can I manually insert a new user into the database without a sign-up page? I want to add each user myself.

Next, how do I adjust my current routes to only allow access for authenticated users? For example, I have:

app.get('/comment/:commentID', admin.renderComment);

The renderCommit above is an extensive handler function, but it should only be accessible to authenticated users. What's the best way to verify this?

Answer №1

Starting a new user should be quite simple, for example using a standalone script:

// Load necessary models and establish database connection
...
// Add a new user:
Users.create({
  username : USERNAME,
  password : HASHED_PASSWORD,
  salt     : GENERATED_SALT,
}, function(err, user) {
  if (err) {
    console.error('Error creating user:', err.message);
  } else {
    console.log('User created successfully');
  }
});

To ensure that a user is logged in before accessing specific routes, you can implement a straightforward middleware solution:

app.get('/comment/:commentID', ensureAuthenticated, admin.renderComment);

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

"React components encounter a problem where props are not defined

Trying to pass props from one component to another using react-router. When attempting to access those props in the child component, receiving error TypeError: this.props.params.appState is undefined. Sample code provided: Tracks.jsx: import { observable ...

Accessing a specific row in jqGrid is successful only on the first attempt

Okay, I must be missing something obvious here... I have a jqGrid with the ID "grid" (very creative, I know). I am adding a navigation button to the grid like this: jQuery("#grid").navButtonAdd('#pager', { caption : "Manage Files", ...

Encountered a session.socket.io error: unable to find session using the provided key: connect.sid

So, I've been struggling with an issue for the past couple of days and I can't seem to figure it out. I've searched through various resources like this GitHub issue and Stack Overflow, but I still haven't found a solution. Here's m ...

What is the correct way to use variables to reference whether an item is odd or even in an ng-repeat loop?

Is there a way to access the variables $odd and $even within ng-repeat using a variable for reference? Here is what I have attempted: <ng-repeat="item in items" ng-if="$odd">these are odd{{item}}</div> <ng-repeat="item in items" ng-if="$eve ...

What is the process for adjusting the size of a gridHelper in three.js?

import * as THREE from '/build/three.module.js'; let scene, camera, renderer, gridHelper; scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000); camera.position.set(0, 150 ...

Error occurs during server to server mutation with Apollo Client (query successful)

Currently, I am using apollo-client on my web server to interact with my graphql server (which is also apollo). While I have successfully implemented a query that retrieves data correctly, I encounter new ApolloError messages when attempting a mutation. Od ...

What is the best way to implement a unique function in an angularjs directive?

Is it possible to execute a custom function when clicking on the checkbox of a table row shown below? I am using the Angular Smart Table directive and need to be able to store the rowid or another property of the rows when the checkbox is clicked. app.dir ...

What's the best way to ensure that the theme state remains persistent when navigating, refreshing, or revisiting a page in the browser?

Is there a way to ensure that my light/dark theme settings remain persistent when users reload the page, navigate to a new page, or use the browser's back button? The current behavior is unreliable and changes unexpectedly. This is the index.js file ...

What is causing Angular to show undefined when using an object?

I'm relatively new to Angular development. I am currently working on a controller that involves validating user input for registration. svs.controller('registrationCtrl', function($scope, validatorService) { $scope.$watch("registrationFor ...

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success or fail message. Instead, I received the entire HTML page code along

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success/fail message. However, I ended up receiving the full HTML page code along with tags. Here is my AngularJS code: $http.post('ajax_Location.php',{ &apos ...

What is the most effective method for assessing a service using angular?

As a beginner in angular testing, I am eager to start creating tests for my service. However, I have encountered an issue where my service (foo) injects another service (bar) in its constructor. Should I create a mock for bar? Do I need to mock every func ...

The favicon appears broken upon opening a new tab

Usually, I use a favicon PNG file for my website. It works perfectly and I can see my favicon on the browser tab. However, when I open a PDF document in a new page from my Angular app, I notice that there is a broken icon on the browser tab. Here is how I ...

The Context API leaves me feeling lost and confused

I am currently utilizing Auth0 for user sign up. My goal is to extract the user id listed under sub:value, and then add it to my database to associate it with a user's post. To achieve this, I am attempting to utilize a Context API to retrieve the use ...

JQuery Fails to Trigger While Navigating Between Pages with React Router <Link>

When navigating from my home page to the product page, I am encountering an issue with my hamburger button. It appears as though it is clicked but does not open up the menu. However, if I refresh the page, the button works again. Strangely, after refreshin ...

Basic application - angular has not been declared

I'm currently diving into the realm of javascript and angularjs, following along with the tutorials on . After setting up a basic IntelliJ javascript project, I created two essential files: index.html <!DOCTYPE html> <html lang="en"> ...

Images are not being successfully retrieved by Express.static from the public folder

Recently, it seems that Express is having trouble pulling images from the image folder in the public directory, even though it can successfully retrieve the styles.css file located in the css folder within the same public directory. The public directory c ...

By default, the first node in Dynatree is automatically selected

I am working on a dynatree project and I'm looking to have the first node automatically selected when the dynatree opens. Although I tried setting select = tree in the json for the first element, it didn't work as expected. I would prefer not hav ...

Uploading multiple chunks with form data using Blueimp

I am looking to upload multiple files with form data in chunks. The goal is to save the form data to a database and the images to a specific folder. Currently, I am utilizing blueimp upload and you can view my code on this Fiddle. Here is the JavaScript ...

How can I detect the @mouseup event in a Vue Bootstrap slider?

I have been using a vue-bootstrap slider that comes with two actions, @change and @update. My goal is to capture the final position of the slider once the movement ends. To achieve this, I decided to test both actions. In my scenario, @change triggers ev ...

Is it possible for an object to receive notifications when a component object undergoes changes in Angular 2/4?

When working with Angular components, it's possible to pass a variable or object as @Input(). The component will be notified whenever the value of this input changes, which is pretty cool... I'm currently developing an application that features ...