get logged user with NodeJS and Angular - node.js

I have some users in my app, now I want to get one user at a time when they login.
this is my node.js
router.get('/currentUser', (req, res) => {
User.findOne().then(user => {
console.log(user);
if (user) {
return res.status(200).json(user);
} else {
return res.status(404).json({
message: 'User not found'
});
}
});
});
and on my angular app I have
getCurrentUser(user: any) {
console.log(user);
return this.http.get(this.urlEnvironment + this.OneUserUrl).subscribe(data =>{
console.log(data)
});
}
the problem is it gets first user only from the database instead of the current user.
I have tried find() but it gets all those users.

Related

Performing validation on Login using nodejs and React

I'm Having a User login using the below code:
OnSubmit(e) {
const user = {
email: this.state.email,
password: this.state.password,
}
axios.post('http://localhost:5000/Users/login', user)
.then(res => {
localStorage.setItem("userData", JSON.stringify(res.data.users))
this.setState({ userData: res.data.users||{}, loggedin:true });
console.log(this.state.userData);
})
localStorage.setItem("token", "got")
}
I want to perform a Validation That If user data does not match then show an alert error else it should Redirect to Dashboard like following code:
if (this.state.loggedin) {
return <Redirect to={`/UI/Navbar/Dashboard/${this.state.userData._id}`} />
}
Here is the Backend in the Nodejs
router.route('/login').post((req,res)=>{
users.findOne({
email:req.body.email,
password:req.body.password
})
.then(users=>{
if(users){
res.json({ users })
}else{
res.json('not found')
}
})
.catch(err=>{
res.send('error:'+err)
})
})
For this you can use an async function in this way:
router.route('/login').post(async (req,res)=>{
// Get the user async
const user = await users.findOne({
email:req.body.email,
password:req.body.password
})
if(user === null) res.status(404).json('not found').end() // Check if user exists
res.json({user}) // return user
})
First you search the user asynchronously, then you check if the user exits, if it doesn't you return the 'not found', else you return the user. I also added an status code of not found, of course is not necesary

My app works perfectly locally, all routes, with no issues. But on Heroku, all employees routes are getting a 503 service unavailable

I'm using passport authentication on a local database for two kind of users, admin and employees. The whole app works well locally but on Heroku, employees cannot be signed up or signed in. It's giving me a 503 unavailable service error. Any clue?
I have tried postman and I'm getting the same reponse after 30+ seconds.
// Register
router.post('/employees/signup', (req, res) => {
console.log(req.body);
const { firstName, lastName, email, password, password2, jobType } =
req.body;
if (password.length < 6) {
throw 'Password must be at least 6 characters';
}
else {
Employee.findOne({
where: {
email
}
}).then(employee => {
if (employee) {
res.send("Email already exists!")
} else {
const encryptedPassword = bcrypt.hashSync(password, salt);
let newEmployee = {
firstName,
lastName,
email,
password: encryptedPassword,
jobType,
};
Employee.create(newEmployee)
.then(() => {
delete newEmployee.password;
res.send(newEmployee)
})
.catch(function (err) {
console.log(err);
res.json(err);
});
}
});
}
});
// Login
router.post("/employees/login", function (req, res, next) {
const { email, password } = req.body;
// generate the authenticate method and pass the req/res
passport.authenticate('employees-local', function (err, employee,
info) {
if (!email || !password) {
return
}
if (err) {
return res.status(401).json(err);
}
if (!employee) {
return res.status(401).json(info);
}
// req / res held in closure
req.logIn(employee, () => {
Employee.findOne({
where: {
email: req.body.email,
},
}).then(employee => {
const token = jwt.sign({ email: employee.email },
jwtSecret.secret, {
expiresIn: 60 * 60,
});
res.status(200).send({
authEmployee: true,
token,
message: 'user found & logged in',
employee
});
});
});
})(req, res, next);
});
//Getting all employees
router.get("/employees", (req, res) => {
Employee.findAll({}).then(function (dbEmployee) {
res.json(dbEmployee);
});
});
The problem came when some time ago I wanted to create a personal profile for the employees, so I had created a model for the employees profile. Then I had changed my mind but never deleted that model; so Sequelize kept trying to associate employees with the profiles model, therefore, the routes were not getting hit. It's been solved now by just deleting that old model, and I'm not getting that 503 anymore. Thanks a lot for your input as it helped me think from a different perspective and reach out to the problem the correct way and correct unnecessary lines of code.

How to properly pass custom errors from Backend (Express) to Frontend (Vue)

I am developing a basic Node app and I am facing a problem that I think is not new but I don't understand which is the proper way to solve. I need to handle those errors that are not generated by code, network or database but needed by the logic of the application. As an example I use the already registered user but the same handling will be needed in different case in the application.
I start from the method in login component:
register () {
API
.register(this.credentials)
.then(
data => {
this.user = data;
},
error => {
this.error = error;
})
.catch(error => {
this.error = error;
});
},
The API is:
register (credentials) {
return Axios
.post('/auth/register',credentials)
.then(response => {
return response.data;
})
},
The Backend is:
router.post('/auth/register',(req,res) => {
User.findOne({where:{username:req.body.username}})
.then(user => {
if (!user) {
User
.create(req.body)
.then(user => {
res.send(user);
})
} else {
throw 'Username already exists';
}
});
});
What I expect is that the error
throw 'Username already exists';
(but it can be No data found for your search) is passed back to the component that catch it and show the error instead the registerd user.
I try adding the catch after every then or using res.send({error:...}) instead of throw but in this way the component shows the error message as user object.
Use HTTP Status Codes to propagate errors through HTTP:
Backend:
router.post('/auth/register',(req,res) => {
console.log('backend register 3',req.body);
User.findOne({where:{username:req.body.username}})
.then(user => {
if (!user) {
User
.create(req.body)
.then(user => {
console.log('backend register 4',req.body);
res.send(user);
})
} else {
res.status(409).send('User already exists')
}
});
});
Fronted:
register (credentials) {
return Axios
.post('/auth/register',credentials)
.then(response => {
return response.data;
})
.catch(err => {
processError(err);
})
},

Query not working in Mongodb

I am using express.js with mongoose for signup. I use crypto for saving the user's password and am now working on the login section. However, when I post values via postman, I am getting the error "not exist" over and over again.
Here is my code:
app.post('/login', (req, res) => {
var User = require('./user.js');
User.findOne({ username: req.body.email }, function(err, user) {
if (err) {
console.log("error");
} else if (!user) {
console.log("not exist");
} else if(!user.validPassword(req.body.password)) {
console.log("not valid");
} else {
console.log("valid");
}
});
res.send("XYZ");
});

Setting a unique user nickname in node express app

I have a user profile collection in which I have the following fields:
member_id
userhandle
height
weight
I register a user with passport and generate a unique member_id for each user which is later used for getting the profile page populated and also for referrals. Following is the get profile route where user can change their details:
// Get User Profile Settings route
router.get('/profilesettings/:member_id', (req, res) => {
Profile.findOne({ member_id: req.params.member_id })
.then(profile => {
res.render('users/profilesettings', { profile: profile });
})
.catch(error => {
console.log('could not find profile');
});
});
Once this page is loaded the user can change their details and use the submit button to update their data. Following is the code for the put request:
router.put('/profilesettings/:member_id', (req, res) => {
Profile.findOne({ member_id: req.params.member_id })
.then(profile => {
profile.userhandle = req.body.userhandle;
profile.weight = req.body.weight;
profile.height = req.body.height;
profile.mobile = req.body.mobile;
profile.save()
.then(updatedProfile => {
req.flash('success_msg', 'Profile updated successfully');
res.redirect('/user/userdashboard');
})
.catch(error => {
console.log(error);
});
})
.catch(error => {
console.log('could not find record');
});
});
What I want to do is ensure that the userhandle is always unique, so if the user enters a userhandle which is already taken by someone else in the profile collections there should be an error and the form should not submit. I am totaly stumped on how to put in a logic which does the following:
1- Checks if there is a difference in the userhandle submitted and the one already stored in the collection
2- Checks if the userhandle which came in the request already exists or not
3- if not then sets the userhandle to the new value and save
4- if it does it creates and error and redirects.
Would appreciate any advise. I know it's a small thing for you pros but I am learning Node and express :-)
After you have confirmed if the member exists or not, you can do a 'count' query to check if the 'userHandle' exists or not. If the userHandle already exists you can return a 4xx status code. Otherwise, save it in the db. It would look something like this...
router.put('/profilesettings/:member_id', (req, res) => {
Profile.findOne({ member_id: req.params.member_id })
.then(profile => {
Profile.count({userhandle: req.body.userhandle})
.then(count => {
if(count != 0){
//return the error code
}
else{
//proceed with your normal flow
profile.userhandle = req.body.userhandle;
profile.weight = req.body.weight;
profile.height = req.body.height;
profile.mobile = req.body.mobile;
profile.save()
.then(updatedProfile => {
req.flash('success_msg', 'Profile updated successfully');
res.redirect('/user/userdashboard');
})
.catch(error => {
console.log(error);
});
}
}).catch(err => {
console.log(err);
});
})
.catch(error => {
console.log('could not find record');
});
});

Resources