2015-10-17 71 views
1

我創造了這個簡單的插件:獲取驗證錯誤與HapiJS

import bcrypt from 'bcrypt'; 
import Joi from 'joi'; 

import DynamoDBClient from '../lib/DynamoDBClient'; 

exports.register = (server, options, next) => { 
    server.auth.strategy('simple', 'basic', { 
    validateFunc: (request, email, password, callback) => { 
     DynamoDBClient.findUserByEmail(email) 
     .then(user => { 
      if (!user) { 
      return callback(null, false); 
      } 

      bcrypt.compare(password, user.password, (err, isValid) => { 
      return callback(err, isValid, { id: user.id }); 
      }); 
     }); 
    } 
    }); 

    server.route({ 
    method: 'POST', 
    path: '/api/login', 
    config: { 
     auth: 'simple', 
     validate: { 
     payload: { 
      email: Joi.string().required(), 
      password: Joi.string().required() 
     } 
     } 
    }, 
    handler: (request, reply) => reply(request.auth.credentials.id) 
    }); 

    next(); 
}; 

exports.register.attributes = { 
    name: 'login', 
}; 

,並裝載清單在這裏:

import Glue from 'glue'; 

const manifest = { 
    server: {}, 
    connections: [ 
    { 
     port: process.env.PORT || 3001, 
     labels: ['api'] 
    } 
    ], 
    plugins: { 
    'hapi-auth-basic': {}, 
    './api/signup': {}, 
    './api/login': {}, 
    './api/products': {}, 
    } 
}; 

const options = { 
    relativeTo: __dirname 
}; 

Glue.compose(manifest, options, (err, server) => { 
    if (err) { 
    throw err; 
    } 

    server.start(() => console.log(`Listening to ${server.info.uri}`)); 
}); 

,但我得到這個錯誤

{ 
    "statusCode": 401, 
    "error": "Unauthorized", 
    "message": "Missing authentication" 
} 

當我嘗試登錄傳遞帶有電子郵件和密碼的POST請求作爲body params。

回答

1

我認爲你的/api/login路由不應該受到身份驗證方案的保護,否則你將不得不通過身份驗證進行身份驗證。雞和雞蛋的問題...你所有的其他路線應該是。

換句話說,不應該保護登錄(和註銷?)路線。

+0

有道理,但如果我不保護該源,我應該保護哪些源?從那裏刪除auth禁用身份驗證和憑證對象爲空 – Mazzy

+0

我認爲您應該保護其餘的API。我從來沒有寫過自己的策略:大多數情況下我使用hapi-auth-cookie和我自己的驗證功能。這裏有一個最近的教程https://medium.com/@poeticninja/authentication-and-authorization-with-hapi-5529b5ecc8ec可能會幫助你。總之,如果你想自己做,我認爲你需要在/ api/login中完成身份驗證時以某種方式設置會話,然後在其他路由中檢查該會話。 – tgo