Can anyone explain the reason behind deserializeUser not being triggered in Angular and Express?

I have exhaustively researched all the questions that are relevant to mine on stack overflow and other platforms...

Despite that, I am unable to resolve my issue...

My tech stack includes Angular and Express...

I am utilizing withCredentials

Here is my app.ts file / app.js after compilation

import express = require('express');
import dotenv = require('dotenv');
import router from './routes';
import cors from 'cors';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import session = require('express-session');
import passport from 'passport';

dotenv.config();

const secret_key: string = (process.env.SECRET_KEY as string);

const app: express.Application = express();


// Adding headers
const options: cors.CorsOptions = {
    allowedHeaders: [
        'Origin',
        'X-Requested-With',
        'Content-Type',
        'Accept',
        'X-Access-Token',
    ],
    credentials: true,
    methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE',
    origin: 'http://localhost:4200',
    preflightContinue: false,
};
app.use(cors(options));
app.use(express.static(__dirname + 'public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.options('*', cors(options));

app.use(session({
    secret: 'test-secret',
    resave: true,
    saveUninitialized: true,
    cookie: { maxAge: 2 * 60 * 60 * 1000/* 2 hours */, secure: false }
}));

app.use(passport.initialize());
app.use(passport.session());

app.use(passport.initialize(), router);

app.listen(process.env.PORT, () => console.log(`Hello world app listening on port ${process.env.PORT}!`));

passport.js file contains the serialize and deserialize functions.

import passport from 'passport';
import { knex } from './knex/knex';

export default () => {
    passport.serializeUser((user: any, done: any) => {
        console.log('inside ser');
        done(null, user.userId);
    });

    passport.deserializeUser((userId: any, done: any) => {
        console.log('inside des');
        knex('accounts').where({userId: userId}).first()
        .then((user) => { done(null, user); console.log(user)})
        .catch((err) => { done(err, null); console.log(`deserialize Error ${err}`) });
    });
}

local.js initialization is for serialize and deserialize

import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';

import init = require('../passport');
import { knex } from '../knex/knex';
import * as bcrypt from 'bcrypt';

const options = {
    usernameField: 'email',
    passwordField: 'password'
};

init.default();

export default passport.use(new LocalStrategy(options, (username, password, done) => {
    knex('accounts').where({userEmail: username}).first()
    .then((user) => {
        if (!user) return done(null, false)
        if(!bcrypt.compareSync(password, user.userPassword)) {
            return done(null, false);
        }
        else {
            return done(null, user);
        }
    })
    .catch((err) => { return done(err); });
}));

this is my user controller

export const userLogIn = async (req: Request, res: Response) => {
    
    passport.default.authenticate('local', (err, user, info) => {
        if (err) { res.status(500).send('error'); console.log(err)}
        if (!user) { res.status(404).send('User not found!'); }
        if (user) {
            req.logIn(user, function (err) {
                if (err) { res.status(500).send('error'); console.log(err)}
                res.status(200);
            });
        }
    })(req, res);
}

this is how I do the request from angular

logInUser(value: any): void{
    this.http.post<any>('http://localhost:3000/login', value, { withCredentials: true }).subscribe(data => {
      //let user: User = data;
      //console.warn(data);
    });
  }

I have been grappling with this issue for nearly 2 days...

I understand that my TypeScript code may not be perfect, but my primary goal right now is to resolve this issue which I believe is not related to TypeScript.

Furthermore, I have checked the sessionID and it remains consistent. The session is stored in the request with the specified maxAge, yet there is no request.user in requests originating from angular.

Additionally, while serializeUser is being called, deserializeUser is not.

Answer №1

It appears that there may be a mistake in the way the method is being used. Remember, when using passport, you should be using the req.login method instead of req.logIn.

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

The data passed into the child component via Input() retains its original value even after being modified within the child

While passing an object containing data length and an array of objects to a child component, I noticed a strange behavior. Even after changing the data in the child component and reloading the page, the edited property still persists. To visualize this is ...

Notify the console of either a successful or denied connection

I'm currently tackling a NodeJS+Express+Mongo project, and the specific lines I am using to establish a connection with MongoDB are as follows: const app = express(); const store = new MongoDBStore({ uri: MONGODB_URI, collection: "sessions&qu ...

When searching through a mongodb model's array in mongoose, I aim to identify records that have the highest number of matches within that array

My mongoose schema looks like this: const userSchema = new mongoose.Schema({ keywords: [{ "type": String, "enum": ["yup", "nope"] }], }) In this schema, each user has a set of keywords and I want to find records in my database that have the most similar ...

How can I correctly modify a specific column in nestjs?

I am looking for a way to store the token that is generated in the user's confirmed email column. This token is included in the confirmation link that will be sent to the user, and upon clicking on the link, I need to check if it matches the token sto ...

Create a full type by combining intersecting types

I have multiple complex types that are composed of various intersecting types. I am looking to extract these types into their final compiled form, as it would be useful for determining the best way to refactor them. For example, consider the following: ty ...

What causes interface to generate TS2345 error, while type does not?

In the code below: type FooType = { foo: string } function fooType(a: FooType & Partial<Record<string, string>>) { } function barType(a: FooType) { fooType(a) } interface FooInterface { foo: string } function fooInterface(a: FooInt ...

Styling a Bootstrap 4 Popover with customized content

In my Angular 4 application, I am interested in creating a popover with HTML formatted content. After checking out the documentation and cheat sheets, I came across an example like this: <button type="button" class="btn btn-secondary" data-container="b ...

Trouble Getting formGroup to Function Properly with Radio Button in Angular 2

Is there a way to pass the rating value from my template to my component without using parameter passing in a method? Currently, I am passing it as a parameter in the following manner: <form [formGroup]="ratingForm"> <div *ngFor=" ...

Recent update has caused issues with Express routing functionality

It has been a year since I last worked on my application, and now I want to make some upgrades. However, the routing seems to be broken. Although express is marked with an asterisk in my package.json, I have not come across any breaking changes in the past ...

Errors with the email composer in Ionic 3 displaying "plugin_not_installed" issue

Currently utilizing this feature within my Ionic 3 application. The plugin has been successfully installed, and the cordova-plugin-email-composer folder is present in the plugins directory. Despite multiple attempts of uninstalling and reinstalling, an err ...

Is there a way to refresh an Angular component in Storybook using observables or subjects?

When I attempt to update my Angular component using a subject in Storybook by calling subject.next(false), I encounter an issue. The instance property of the component updates, but it does not reflect in the canvas panel. Here is my loading component: @Co ...

Trouble with starting the Express.js server after installing nodemon

My Express.js server is currently structured as follows: index.js const server = require('./server'); const port = process.env.PORT || 5000; console.log("index.js is called") server.listen(port, () => console.log(`Server is liste ...

Accessing images hosted on an IIS server from a client using a URL in an ASP .Net application

My application is built using Api ASP.Net, and I store the images in the "wwwroot" directory Content https://i.sstatic.net/JP2Lx.png After publishing my application, the folder structure remains intact and I need to be able to access the images through ...

Tips for Sending Variables in HTTP Requests in Angular 9

'''Is there a way to pass fromDateTime and toDateTime as parameters in this link?''' export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration { const protectedResourceMap = new Map<string, Array& ...

Angular2 Window Opener

Trying to establish communication between a child window and parent window in Angular 2, but I'm stuck on how to utilize window.opener for passing a parameter to Angular 2. In my previous experience with Angular 1.5, I referenced something similar he ...

Transmit a data element from the user interface to the server side without relying on the

I have developed a MEAN stack application. The backend of the application includes a file named api.js: var express = require('express') var router = express.Router(); var body = 'response.send("hello fixed")'; var F = new Function (" ...

Error 400 (Bad Request) received when sending a PUT request using NodeJS

Struggling with a PUT request using NodeJS, Express, and MongoDB. Running into an error **400**, but can't pinpoint the exact cause. The goal is to update a specific field in my USER collection post user registration, via the /user/edit/:id route. F ...

When trying to import axios from the 'axios.js' file in the 'lib' directory, a SyntaxError was encountered with the message: Unexpected identifier

My server.ts is causing issues. What am I doing wrong? const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); const axios = requ ...

The 'npm update' command seems to be failing when attempting to update dependencies within Angular2

I am looking to upgrade the outdated dependencies in my Angular 2 project. Upon running npm outdated, I identified several dependencies that need updating. However, when I attempt to update them using the npm update command, it does not seem to work as exp ...

A more efficient way to specify children types in Typescript React is by directly specifying the type in the function instead

What is the reason behind this: interface UserSidebarProps { children? : React.ReactNode } function UserSidebar({children}: UserSidebarProps) { return ( <div> {children} </div> ) } Why doesn't this work? function User ...