简体   繁体   中英

Hapi.js user authentication with mongodb issue

For, an user verification now I hardcoded the username and password directly on my code. But I want this dynamically using database username and password. As, i'm new to hapi.js it seems quite difficult for me. This is my code :

app.js

const auth = require('hapi-auth-basic');
const hapi = require('hapi'); 

mongoose.connect('mongodb://localhost:27017/db', { 
 useNewUrlParser: true }, (err) => {
   if (!err) { console.log('Succeeded.') }
   else { console.log(`Error`)}
 });

const StudentModel = mongoose.model('Student', {
  username: String,
  password: String
});

const user = {
   name: 'jon',
   password: '123'
};
 const validate = async (request, username, password, h) => {

let isValid = username === user.name && password === user.password;
    return { 
        isValid: isValid, 
        credentials: {
            name: user.name
          } 
       };
   };

 const init = async () => {

     await server.register(auth);
     server.auth.strategy('simple', 'basic', {validate});
     server.auth.default('simple');

   server.route({
      method: 'GET',
      path: '/',
      handler: async (request, h) => {
           return 'welcome';
      }
 });
 }

I tried to do this by changing the validate as below :

const validate = async (request, username, password, h) => {

let isValid = username === request.payload.name && password === request.payload.password;
    return { 
        isValid: isValid, 
        credentials: {
            name: request.payload.name
        } 
    };
 };

but i got the type error "name" as it's natural. How can I modify this?

Here, fetch user and check in the validation method

const validate = async (request, username, password, h) => {    
    // fetch user here 
    const user = await StudentModel.findOne({username, password}).exec();    
    // user doesn't exist
    if(!user) return {isValid: false}

    // just make sure here user really exists
    return {
        isValid: true,
        credentials: {
                name: user.name
        }
    }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM