I have a CRUD API made with express.js, passport as middleware, postgresql as database. I am calling the api in my frontend using IONIC angular.
It works still fine, but when I login through the front I receive information about all users on my database, even though the query result returns only one user.
Here is the code:
You can clone the api here https://github.com/AndreAnimator/node-api-postgres and the frontend here: https://github.com/AndreAnimator/FoodStack
But you would have to recreate the env files for both of them and create a database in postgres.
Frontend:
this.clienteService.login(this.email, this.senha).subscribe({
next:(response: any)=>{
if(response) {
console.log("Tem resposta");
console.log(response);
this.router.navigate(['/home']);
const foo = document.querySelector("body");
foo.classList.add("conta");
} else {
console.log("Sem resposta");
alert('Usuario ou senha inválidos');
}
},
error:(error)=>{
alert('Usuario ou senha inválidos');
}
});
Cliente service:
login(email: string, password: string){
return this.http
.post(
`${environment.API_KEY}/login`,
{ email, password }, this.httpOptions
)
}
Passport authentication:
const authenticateUser = (email, password, done) => {
console.log(email, password);
pool.query(
`SELECT * FROM cliente WHERE email = $1`,
[email],
(err, results) => {
if (err) {
throw err;
}
console.log(results.rows);
if (results.rows.length > 0) {
const user = results.rows[0];
console.log("tem muitos resultados");
console.log(user);
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) {
console.log("deu um erro");
console.log(err);
}
if (isMatch) {
console.log("Deu match");
console.log(user);
return done(null, user);
} else {
console.log("Password is incorrect");
return done(null, false, { message: "Password is incorrect" });
}
});
} else {
console.log("No user with that email address");
return done(null, false, {
message: "No user with that email address"
});
}
}
);
};
Express routes:
initializePassport.initialize(passport);
app.use(express.json())
app.use(
express.urlencoded({
extended: true,
})
)
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
maxAge: 1000 * 60 * 60 * 24, // TTL for the session
},
})
);
app.use(cors())
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.get("/login", checkAuthenticated, (req, res) => {
// flash sets a messages variable. passport sets the error message
// console.log(req.session.flash.error);
console.log("alouu");
console.log(req.session.passport);
// res.render("login.ejs");
});