I do not know if you are doing your work synchronously or asynchronously. How can I know when a process executes asynchronously or not?
In theory, if a function uses callbacks, it is an asynchronous function. If a function returns a value, it is synchronous.
I'm not sure if it's the most recommendable way to do the login
It is the standard form that most applications use: a request to the database and an object is created in session storing the user's data and optionally, a cookie is created to store the session token.
There are several libraries for Node.js that allow you to automate this process to a great extent. One of the best known and used is PassportJS but you can also do a token-based authentication such as JWT .
Using local strategy
It's really simple. The only thing you have to do are two things:
Add a type of strategy
Create a middleware to use it
If you want a local strategy, that is, simple and direct authentication, you only need to install the package passport-local
, instantiate it and pass it a function that will be the one with the authentication.
UserRepository.js
export default class UserRepository {
login (username, password) {
const salt = Bcrypt.genSaltSync(10);
let hash = Bcrypt.hashSync(password, salt);
return new Promise((resolve, reject) => {
User
.findOne({ username, password: hash })
.then((user) => {
resolve(user);
});
}
}
}
Authentication.js
passport.use(
new LocalStrategy((username, password, done) => {
UserRepository
.login(username, password)
.then((user) => {
done(null, user);
});
});
);
Finally you need to add passport to your login path.
app.post('login', passport.authenticate('login', {
successRedirect: '/home',
failureRedirect: '/login',
failureFlash: 'Usuario o contraseña incorrecta'
});
Using JWT strategy
This type of strategy allows you to authenticate via JWT. JWT is an open standard for secure communication based on JSON ( RFC7519 ). This standard uses different algorithms to sign the information to contain, which can be HMAC
or RSA
. You can see more detailed information about JWT here
let options = {
// extrae la cabecera HTTP 'Authorization'
opts.jwtFromRequest: ExtractJwt.fromAuthHeader(),
// secreto con el cual se crea el token
opts.secretOrKey: 'secret'
}
passport.use(new JwtStrategy(opts, function(token, done) {
// intenta decodificar el token. Si tiene éxito
// devuelve true
try {
let decoded = jwt.verify(token);
done(null, true);
} catch (e) { // caso contrario, false
done(e, false);
}
}));
Now, you can put this authentication in a middleware for the routes you want. When the token has expired or is not valid, redirect to a specific page, for example login.
router
.get('/home', passport.authenticate('jwt', {
failureRedirect: '/login'
})
... otras rutas