Log in on node.js

3

I am new programming in node.js and I wanted to ask you a question: I have the following log in (which works without problem) but I'm not sure if it is the most recommendable way of doing things since I do not know if you are doing it I work in a synchronous or asynchronous way. How do I know when he's doing that in that way and when not? Thank you very much

 app.post('/Acceso', function(req, res){
    var conDB=DB();
    var UsuarioReg=req.body.Usuario;
    var ContraReg=req.body.Contra;
    conDB.query('SELECT * FROM Usuario WHERE Usuario = ? and Contra= ?',
        [UsuarioReg,ContraReg],
        function(err,rows){
            conDB.end();
        if(err)
        {
            return console.log(err);
        }
        if (!rows.length)
        {
            return res.send("Usuario y/o clave no valida");
        }
        else
        {
            console.log(rows);
            return res.send("Accedido con exito");
        }
    });
});
    
asked by F. Riggio 02.01.2017 в 17:30
source

2 answers

0

First of all, if it's a real program (it's not for practice) I recommend you use the library passport.js link for node , that is loaded of the logins in an excellent way.

If this is not the case, the best way to do it is asynchronously, because ?? ... well simply because node is not prepared to perform asynchronous functions, by making them synchronous because you are wasting time and delaying the action since will glue the requests.

Finally, in the way you are doing, you should encrypt your password with the crypto library link before saving to the db using a hash to decrypt it later, it is a very bad mistake to record password in plain text. (this process is done by passport.js)

    
answered by 02.01.2017 / 18:30
source
0
  

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
    
        
    answered by 10.02.2017 в 17:35