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.