A part of authorization is handled by injecting the user information. We need an endpoint that verifies whether a user is valid. To define /api/user/auth endpoint, follow these steps:
- Define the route endpoint inside server/api/index.js:
routerAuth.get('/users/auth', User.auth);
- Define the auth function inside the user controller (server/api/user.js):
auth: (req, res) => {
if (!req.user) {
handleFailure(res, { status: 401 });
} else {
Model.users
.authUser(req.user.id)
.then(user => handleSuccess(res, { user }))
.catch(errors =>
handleFailure(res, { errors, message: errors.message, status: 401 }),
);
}
},
- Define the authUser method inside server/models/user.js:
Schema.statics.authUser = function(id) {
return new Promise((resolve, reject) => {
try {
this.findOne({ _id: id })
.then(user => {
resolve(
user.toJson({
token: generateToken({ loginKey: user.loginKey }),
}),
);
})
.catch(error => reject(error));
} catch (e) {
reject(e);
}
});
};