I was researching about the hapi js API basic authentication and i'm using Hapi documentation about the authentication. I believe i did everything right but i'm getting following error saying about UnhandledPromiseRejectionWarning. Please help
index.js
'use strict';
const Bcrypt = require('bcrypt');
const Hapi = require('hapi');
const Basic = require('hapi-auth-basic');
const server = new Hapi.Server({
host: 'localhost',
port: 3000
})
const users = {
john: {
username: 'john',
password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm',
name: 'John Doe',
id: '2133d32a'
}
};
const validate = function (request, username, password, callback) {
const user = users[username];
if (!user) {
return callback(null, false);
}
Bcrypt.compare(password, user.password, (err, isValid) => {
callback(err, isValid, { id: user.id, name: user.name });
});
};
server.register(Basic, (err) => {
if (err) {
throw err;
}
server.auth.strategy('simple', 'basic', { validateFunc: validate });
server.route({
method: 'GET',
path: '/',
config: {
auth: 'simple',
handler: function (request, reply) {
reply('hello, ' + request.auth.credentials.name);
}
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log('server running at: ' + server.info.uri);
});
});
package.json
"bcrypt": "^1.0.3",
"hapi-auth-basic": "^5.0.0",
"hapi": "^17.1.0"
error
(node:1248) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError [ERR_ASSERTION]: Invalid register options "value" must be an object
(node:1248) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
If you want that code to work you will have to use a version lower than 17, i.e (16.6.2) or either look for the code updated to the hapi version you are using.
const Bcrypt = require('bcrypt');
const Hapi = require('hapi');
const users = {
john: {
username: 'john',
password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm', // 'secret'
name: 'John Doe',
id: '2133d32a'
}
};
const validate = async (request, username, password, h) => {
if (username === 'help') {
return { response: h.redirect('https://hapijs.com/help') }; // custom response
}
const user = users[username];
if (!user) {
return { credentials: null, isValid: false };
}
const isValid = await Bcrypt.compare(password, user.password);
const credentials = { id: user.id, name: user.name };
return { isValid, credentials };
};
const main = async () => {
const server = Hapi.server({ port: 4000 });
await server.register(require('hapi-auth-basic'));
server.auth.strategy('simple', 'basic', { validate });
server.auth.default('simple');
server.route({
method: 'GET',
path: '/',
handler: function (request, h) {
return 'welcome';
}
});
await server.start();
return server;
};
main()
.then((server) => console.log(`Server listening on ${server.info.uri}`))
.catch((err) => {
console.error(err);
process.exit(1);
});
Related
I have made an authentication with jwt api in node.js/express and i run it on heroku.
When a user logged in, server create a cookie via cookie-parser and send it to the client.
Below is the code from server.js
const express = require('express');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const path = require('path');
const bcrypt = require('bcrypt');
const PORT = process.env.PORT || 3000;
const serveStatic = require('serve-static');
require('dotenv').config();
const mongoose = require('mongoose');
const { User, Posts } = require(path.join(__dirname, './model.js'));
const mongoString = process.env.DATABASE_URL;
const JWT_SECRET = process.env.JWT_SECRET;
const { verifyToken, checkUser } = require(path.join(__dirname, './auth.js'));
const app = express();
//Middlewares
app.use(
cors({
credentials: true,
origin: true,
})
);
app.use(express.json());
app.use(cookieParser());
//Connect to Database
mongoose.connect(mongoString);
const db = mongoose.connection;
db.on('error', (err) => {
console.log(err);
});
db.once('connected', () => {
console.log('----Database Connected----\n');
});
//functions
const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
return jwt.sign({ id }, JWT_SECRET, {
expiresIn: maxAge,
});
};
// AUTH ROUTES
app.get('*', checkUser);
app.get('/', checkUser, (req, res) => {
res.json({ status: 'success' });
});
app.post('/api/register', async (req, res) => {
const salt = await bcrypt.genSalt();
try {
const user = await User.create(
new User({
username: req.body.username,
email: req.body.email,
city: req.body.city,
password: await bcrypt.hash(req.body.password, salt),
})
);
const token = createToken(user._id);
res.cookie('jwt', token, {
maxAge: maxAge * 1000,
secure: true,
});
res.status(201).json(user);
console.log(user);
} catch (err) {
console.log(err);
res.json(err);
}
});
app.post('/api/login', async (req, res) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email }).lean();
if (!user) {
return res.send({
status: 'error',
error: 'Invalid email',
});
}
if (await bcrypt.compare(password, user.password)) {
const token = createToken(user._id);
res.cookie('jwt', token, { secure: true, maxAge: maxAge * 1000 });
res.status(200).send({ status: 'ok', token: token });
console.log(user._id + ' logged in successfully');
return;
}
return res.send({ status: 'error', error: 'Invalid password' });
} catch (err) {
console.log(err);
}
});
app.get('/api/home', verifyToken, (req, res) => {
res.send(res.locals.user);
});
app.get('/api/logout', (req, res) => {
try {
res.cookie('jwt', '', { maxAge: 1 });
res.status(200).send({ status: 'ok' });
} catch (err) {
res.send(err);
}
});
//POSTS ROUTES
app.post('/api/posts', verifyToken, checkUser, async (req, res) => {
try {
const post = await Posts.create(
new Posts({
postBody: req.body.postBody,
city: req.body.city,
author: res.locals.user.id,
})
);
res.status(200).json(post);
console.log('====New Post=====');
} catch (err) {
res.status(400).send({ message: err.message });
}
});
app.get('/api/posts', verifyToken, async (req, res) => {
try {
const data = await Posts.find();
res.send({ user: res.locals.user, data: data });
} catch (err) {
res.json({ message: err.message });
}
});
app.get('/api/posts/:city', verifyToken, async (req, res) => {
try {
const data = await Posts.find({ city: req.params.city });
res.json(data);
res.send(res.locals.user);
} catch (err) {
res.json({ message: err.message });
}
});
//run server
app.listen(PORT, () => {
console.log(`Server running on ${PORT}...\n`);
});
Now, for front-end i use Vue.js that its running on Firebase.
Here is the script part of Login.Vue
<script>
/* eslint-disable */
import axios from 'axios';
export default {
name: 'Login',
data() {
return {
email: '',
password: '',
error: '',
};
},
methods: {
async onSubmit() {
if (!this.email || this.password.length < 6) {
this.error = 'vale kati';
return;
}
await axios
.post(
'https://thelostpet.herokuapp.com/api/login',
{
email: this.email,
password: this.password,
},
{ withCredentials: true }
)
.then((res) => {
console.log(res.data.token);
if (res.data.status == 'error') {
this.error = res.data.error;
}
if (res.data.status == 'ok') {
this.$router.push('/home');
}
})
.catch((err) => {
console.log(err);
});
},
},
};
</script>
When I try to login from Login.vue, that its ruuning on Firebase, the browser doesn't save the cookie that it created from the api.
BUT when I make a post request on https://thelostpet.herokuapp.com/api/login from postman, the cookie is saved on postman.
Thank you!
When signing in with postman everything works fine. But when i am doing an axios request i get 404 error and directly after 204 error. When i render my vue.js page i get "cannot get api/auth/signin. Also I get a message somewhere that says user not found.
What i have tried:
Frontend: I tried with adding headers to my axios request. I console logged the data and it seems perfectly fine.
Backend: Changed deprecated body parsers.
Frontend Code:
Auth store
import axios from "axios";
const state = {
token: "",
users: [],
};
const getters = {};
const actions = {
async signIn(_, payload) {
const response = await axios.post(
"http://localhost:3000/api/auth/signin",
{ payload },
{
headers: {
"Content-Type": "application/json",
},
}
);
console.log(response.data);
console.log(response.headers);
console.log(response.status);
},
};
const mutations = {};
export default {
state,
getters,
actions,
mutations,
};
This is my backend:
Controller
//signin
exports.signin = (req, res) => {
User.findOne({
username: req.body.username,
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({
accessToken: null,
message: "Invalid Password!",
});
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400, // 24 hours
});
var authorities = [];
for (let i = 0; i < user.roles.length; i++) {
authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
}
res.status(200).send({
id: user._id,
username: user.username,
email: user.email,
roles: authorities,
accessToken: token,
});
});
};
Route
module.exports = function (app) {
app.use(function (req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
app.post(
"/api/auth/signup",
[
verifySignUp.checkDuplicateUsernameOrEmail,
verifySignUp.checkRolesExisted,
],
controller.signup
);
app.post("/api/auth/signin", controller.signin);
And my server
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const Quote = require("./models/Quote");
const quoteRoute = require("./routes/quoteRoute");
const quoteController = require("../Maxico/controllers/quoteController");
const config = require("./config/config");
const verifySignup = require("./middlewares/verifySignUp");
const Role = require("./models/Role");
const app = express();
//Import routes
//const authRoute = require("./routes/auth");
var corsOptions = {
origin: "http://localhost:8080/?#/",
};
app.use(cors(corsOptions));
app.use(express.urlencoded({ extended: true }));
app.use(express.json()); //
const db = require("./models/Quote");
mongoose
.connect(
"url",
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
}
)
.then(() => {
console.log("Connected to the database!");
})
.catch((err) => {
console.log("Cannot connect to the database!", err);
process.exit();
});
app.use(express.json());
app.get("/", (req, res) => {
res.send("Welcome to homepage");
});
app.use("/quote", quoteRoute);
require("./routes/authRoute")(app);
//require("./routes/userRoute")(app);
// initial roles
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "moderator",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'moderator' to roles collection");
});
new Role({
name: "admin",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'admin' to roles collection");
});
new Role({
name: "superadmin",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'superadmin' to roles collection");
});
}
});
// set port, listen for requests
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
In my network tab the request pay load got sent like this:
{payload: {username: "jon", password: "password"}}
payload: {username: "jon", password: "password"}
But my postman only accepts this:
{username: "jon", password: "password"}
So in my action i sent like this:
const actions = {
async signIn(_, payload) {
console.log(payload);
const response = await axios.post(
"http://localhost:3000/api/auth/signin",
payload,
{
headers: {
"Content-Type": "application/json",
},
}
);
console.log(payload);
console.log(response.data);
console.log(response.headers);
console.log(response.status);
},
};
I'm trying to get my login api working inside azure function, but it keeps saying await is only valid in async function. This is an async function so I'm just super confused.
This line
const user = await db.collection('users').findOne({ email: userLoggingIn.email })
is throwing the error.
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
var MongoClient = require('mongodb').MongoClient;
module.exports = async function (context, req) {
MongoClient.connect(process.env.CosmosDBConnectionString, (err, client) => {
let userLoggingIn = ({ email, password } = req.body);
console.log("userLoggingIn");
console.log(userLoggingIn.email);
let send = response(client, context);
if (err) send(500, err.message);
console.log("DBNAME: " + process.env.dbName);
let user;
let db = client.db(process.env.dbName);
const user = await db.collection('users').findOne({ email: userLoggingIn.email })
console.log("USER");
console.log(user);
let userName= user.instagramName;
if (!user) {
send(401, { message: "Auth failed" });
}
const { username } = user;
console.log("PASSWORD");
console.log(context.req.password);
console.log(user.password);
const goodPassword = bcrypt.compareSync(context.req.password, user.password);
if (!goodPassword) {
return send(401, { message: "Auth failed" });
}
const token = jwt.sign(
{
email: user.email,
userId: user._id,
username: userName
},
"secret_this_should_be_longer",
{ expiresIn: "1h" }
);
context.res = { status: 200, token: token, expiresIn: 3600, userId: user._id, username: username};
})
}
function response(client, context) {
return function (status, body) {
context.res = {
status: status,
body: body
};
client.close();
context.done();
};
}
MongoClient.connect(process.env.CosmosDBConnectionString, (err, client) => {
on this line, the annonymous callback function receiving err and client as parameter is the function that needs to be async
MongoClient.connect(process.env.CosmosDBConnectionString, async (err, client) => {
I developing a REST API using node js and express with MongoDB.
I have developed an endpoint to insert the user into DB and works fine. Now I have added the login function with jwt and now when I run my app and try to insert my user I receive this error:
an app is listening on port 3000
(node:3650) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Expected "payload" to be a plain object.
(node:3650) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I'm using a node js version: 8.9.3 on mac
Any help, please?
# this is the code about user add:
var router = require('express').Router();
var bcrypt = require('bcryptjs');
var User = require('../models/user');
var jwt = require('jsonwebtoken');
var constants = require('../config/constants');
router.post('/',(req, res) => {
// add user --> user = { username: 'test', email: 'test#tes.com', pwd: 'Test'}
var user = new User({
username: req.body.user.username,
email : req.body.user.email,
passhash: bcrypt.hashSync(req.body.user.pwd, 10)
});
user.save().then(
(newuser) => {
var sessionToken = jwt.sign(newuser._id, constants.JWT_SECRET, {expiresIn: 60*60*24});
res.json({
user: newuser,
message: 'success',
sessionToken: sessionToken
});
},
(err) => {
res.send(500, err.message);
}
);
});
module.exports = router;
and this is the code about login:
var router = require('express').Router();
var bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');
var constants = require('../config/constants');
var User = require('../models/user');
router.post('/', (req, res) => {
User.findOne({ username: req.body.user.username}).then(
(user) => {
if(user){
bcrypt.compare(req.body.pwd, user.passhash, (err, matches) => {
if (matches) {
var sessionToken = jwt.sign(user._id, constants.JWT_SECRET, { expiresIn: 24*60*60 });
res.json({
user:user,
message: 'succesfully authed',
sessionToken: sessionToken
});
}else{
res.json({
user: {},
message: 'failed to auth',
sessionToken: ''
});
}
});
}else{
res.json({
user: {},
message: 'failed to auth',
sessionToken: ''
});
}
},
(err) => {
// could not find users
res.json(err);
}
);
});
module.exports = router;
I have tested the add user with postman and I have seen that when I receive the message posted, the user is inserted into db
If both API methods are declared in the same file, the problem can be because you are declaring twice same path + verb:
router.post('/', (req, res) => {
In my hapijs app I have few routes which require a session, uses hapi-auth-cookie plugin for auth strategy. I want to add few tests (via Lab ) for these routes.
I couldn't find any documentation on how I can setup a test (maybe via before ?) for this scenario. Any help is appreciated. Thanks in advance.
If you only need an authenticated user, just assign the user to the credentials property in tests:
var user = { ... };
server.inject({ method: 'GET', url: '/', credentials: user }, function (res) {
console.log(res.result);
});
Here is an example that demonstrates it:
var Bcrypt = require('bcrypt');
var Hapi = require('hapi');
var HapiAuthCookie = require('hapi-auth-cookie');
var server = new Hapi.Server();
server.connection({ port: 3000 });
var users = {
john: {
username: 'john',
password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm',
name: 'John Doe',
id: '2133d32a'
}
};
var validate = function (request, username, password, callback) {
var user = users[username];
if (!user) {
return callback(null, false);
}
Bcrypt.compare(password, user.password, function (err, isValid) {
callback(err, isValid, { id: user.id, name: user.name });
});
};
server.register(HapiAuthCookie, function (err) {
server.auth.strategy('session', 'cookie', {
password: 'secret',
validateFunc: validate
});
server.route({
method: 'GET',
path: '/',
config: {
auth: 'session',
handler: function (request, reply) {
reply('hello, ' + request.auth.credentials.name);
}
}
});
server.inject({ method: 'GET', url: '/', credentials: users.john }, function (res) {
console.log(res.result);
});
});
Large part of the example was taken from the Authentication Tutorial.
For my need for session during testing, I created hapi-session-inject. Usage is as follows
const server = new Hapi.Server();
const session = new Session(server);
// Callback interface
session.inject('/', (res) => {
...
});
// Promise interface
return session.inject('/').then((res) => {
...
});
Hope it helps.