Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
Basic Authentication ComparePassword

I am currently working on a "Basic Authetntication" for Node JS. It should accept requests like the following:

POST http://localhost:8080/authenticate/
Authorization: Basic YWRtaW46MTIz

The AuthenticationService.js first reads the header and then passes the whole thing to the Userservice.js

AuthenticationService.js

async function basicAuth(req, res, next) {
    // make authenticate path public
    if (req.path === '/') {
        return next();
    }

    
    if (!req.headers.authorization || req.headers.authorization.indexOf('Basic ') === -1) {
        return res.status(401).json({ message: 'Missing Authorization Header' });
    }

    // verify auth credentials
    const base64Credentials =  req.headers.authorization.split(' ')[1];
    const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
    const [username, password] = credentials.split(':');
    console.log("AuthenticationService "+username+" "+password);
    
    const user = await userService.authenticate({ username, password });
    if (!user) {
        return res.status(401).json({ message: 'Invalid Authentication Credentials' });
    }
    req.user=user
    res.send(user)
next();
}
module.exports = {
    basicAuth
}

The user service checks if the user is found and checks if the password is valid, only then the user object is sent back to the authentication service.

UserService.js

async function authenticate({ username, password }) {
    
    
    let user = await User.findOne({userID: username})
        
     user.comparePassword(password.toString(), function(err,isMatch) {
        if (err){
            console.log("error")
            throw err;
        } 
            if(isMatch)
            {
                console.log("Password correct")
                
                
                
            }
            if(!isMatch){
                console.log("Password wrong")
                
                
            }});

if(user){
        return user; 
    }
    else{
        return null;
    } 
    
}

module.exports = {
    
    authenticate
}

The .comparePassword-Method is inside the Usermodel.js:

UserSchema.methods.comparePassword = function(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};
const User = mongoose.model("User", UserSchema);
module.exports = User;

How can I send the boolean value of isMatch in the Userservice.js outside it's scope, so I can send the userobject back to the AuthenticationService.js depending on the correct password ? How can I improve that code ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I erase the authenticate-method in Userservice.js and just call the crud-method. After that I call the compare-method and inside the if/else-block I pass a res.send.

function basicAuth(req, res, next) {
    
    if (!req.headers.authorization || req.headers.authorization.indexOf('Basic ') === -1) {
        return res.status(401).json({
            message: 'Missing Authorization Header'
        });
    }

    // verify auth credentials
    const base64Credentials = req.headers.authorization.split(' ')[1];
    const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
    const [username, password] = credentials.split(':');
    console.log("AuthenticationService " + username + " " + password);

    userService.findUserById(username, function(error, user) {

        user.comparePassword(password.toString(), function(err, isMatch) {
            if (err) {
                console.log("Fehler")
                throw err;
            }
            /*Passwort richtig*/
            if (isMatch) {

                res.send(user);

            }
            /*Passwort falsch*/
            if (!isMatch) {

                res.status(401).json({
                    message: 'Passwort und userID stimmen nicht überein.'
                });



            }
        });
    })
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda