I used to get my signin token using this code:
1const { authSecret } = require('../.env');
2const jwt = require('jwt-simple');
3const bcrypt = require('bcrypt-nodejs');
4
5module.exports = app => {
6 const signin = async (req, res) => {
7 if (!req.body.email || !req.body.password) {
8 return res.status(400).send('Enter user and password ');
9 };
10
11 const user = await app.db('users')
12 .where({ email: req.body.email })
13 .first()
14
15 if (!user) return res.status(400).send('User not found!');
16
17 const isMatch = bcrypt.compareSync(req.body.password, user.password);
18 if (!isMatch) return res.status(401).send('Invalid email/password!');
19
20 const now = Math.floor(Date.now() / 1000);
21
22 const payload = {
23 id: user.id,
24 name: user.name,
25 email: user.email,
26 age: user.age,
27 city: user.city,
28 iat: now,
29 exp: now + (60 * 60 * 24 * 7)
30 };
31
32 res.json({
33 ...payload,
34 token: jwt.encode(payload, authSecret)
35 })
36 };
37
38 const validadeToken = async (req, res) => {
39 const userData = req.body || null;
40 try {
41 if (userData) {
42 const token = jwt.decode(userData.token, authSecret)
43 if(new Date(token.exp * 1000) > new Date()) {
44 req.send(true)
45 }
46 }
47 } catch (e) {
48 console.log('Inspired token');
49 };
50
51 res.send(false);
52 };
53
54 return { signin, validadeToken };
55}
56
But yesterday I tried to create a new node project with "bcrypt-nodejs": "^0.0.3" and "jwt-simple": "^0.5.6", but now I'm getting this error message when I try to login on my backend and getting the token that doesn't appear
ERROR MESSAGE:
(node:13188) UnhandledPromiseRejectionWarning: Error: Require key
at Object.jwt_encode [as encode] (F:\react_native\Expo\base\track-server\node_modules\jwt-simple\lib\jwt.js:123:11)
at signin (F:\react_native\Expo\base\track-server\api\auth.js:34:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13188) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13188) [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.
Does anyone know what I shuld do to get this signin token?
It looks like your authSecret variable is undefined, thus resulting in the Error: Require key error when you try to use it as the key during the jwt.encode(payload, authSecret) call on line 34.
As you already appear to have a .env file, I would suggest using the dovenv module here https://www.npmjs.com/package/dotenv
So assuming your .env file is in the root directory of your project. Replace your destructured import const { authSecret } = require('../.env'); with
require('dotenv').config();
const authSecret = process.env.authSecret;
(obviously replacing authSecret with whatever the environment variable defined in your .env file is). Also just FYI it is convention to make environment variable upper case and separated by underscores. e.g. AUTH_SECRET
Related
i have this simple code in my discord bot to check mc server.
const Discord = require('discord.js')
const client = new Discord.Client()
const { MessageButton, MessageButtonStyles } = require('discord-buttons')
require('discord-buttons')(client)
const db = require('quick.db')
let mineutil = require('minecraft-server-util')
client.on('ready', () => {
console.log('Started!\n---')
client.user.setPresence({
status: 'online',
activity: {
type: 'LISTENING',
name: '!help'
}
})
})
client.on('message', async (message) => {
if (message.content == 'привет') {
message.reply('привет')
}
//more code
const SERVER_ADDRESS = 'adress'
const SERVER_PORT = 25565
const STATUS_ONLINE = '**Сервер включен** - '
const STATUS_PLAYERS = '**{online}** **человек(a) онлайн!**'
const STATUS_EMPTY = '**никто не играет**'
const cacheTime = 15 * 1000; // 15 sec cache time
let data, lastUpdated = 0;
function statusCommand(message) {
getStatus().then(data => {
let status = STATUS_ONLINE;
status += data.onlinePlayers ?
STATUS_PLAYERS.replace('{online}', data.onlinePlayers) : STATUS_EMPTY;
let statuspanel = new Discord.MessageEmbed()
.setColor('2ecc71')
.setDescription(status)
send(statuspanel)
}).catch(err => {
console.error(err)
let statuserror = new Discord.MessageEmbed()
.setColor('ff0000')
.setDescription('**Сервер выключен**')
send(statuserror)
})
}
function getStatus() {
if (Date.now() < lastUpdated + cacheTime) return Promise.resolve(data);
return mineutil.status(SERVER_ADDRESS, { port: SERVER_PORT })
.then(res => {
data = res;
lastUpdated = Date.now();
return data;
})
}
if (message.content == '!server') {
statusCommand(message)
}
})
client.login(TOKEN)
And it works in Visual studio, but i just placed it on Replit and it catches this error:
(node:172) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Expected 'port' to be a 'number', got 'object'
at Object.status (/home/runner/Makak-discord-bot/node_modules/minecraft-server-util/dist/status.js:23:26)
at getStatus (/home/runner/Makak-discord-bot/index.js:210:21)
at statusCommand (/home/runner/Makak-discord-bot/index.js:192:5)
at Client.<anonymous> (/home/runner/Makak-discord-bot/index.js:219:5)
at Client.emit (events.js:314:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
(node:172) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:172) [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.
And if i change, for example { port: SERVER_PORT } to 25565, it always says that server is off, even if server online(
PS sorry for my english, and russian text in code
EDIT Just saw the question's last line about the server being reported as offline when using a number rather than an object. That actually confirms my suspicion below, as you're no longer getting an error from the SDK itself (ie, it seems to be "working," in that it's at least making the network call). I would double-check your address and port number, and ensure the server is accessible from replit.
--- Original response below ---
Difficult to say for sure without knowing the mineutil API you're using, but it looks like you may be sending more than you need to the mineutil.status() function (And if you're using this library, I'm fairly certain you are).
I'm guessing that the following line:
return mineutil.status(SERVER_ADDRESS, { port: SERVER_PORT })
which is sending an object `{port: SERVER_PORT}' as its second parameter, should just be sending the number itself. For example:
return mineutil.status(SERVER_ADDRESS, SERVER_PORT )
This is Replit server side error, it can not be repaired(
I use Node, Express, React, Mongo and Prisma to import a csv file in the database, display it on the frontend and delete all records in the db. It worked with one record and so I assumed it would work with the rest of the csv file (1000 records). But I get an error:
Invalid `prisma.movie.findMany()` invocation:
Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind: RawError { code: "unknown", message: "Command failed (CursorNotFound): cursor id 124425195753416376 not found)" } })
(node:2171) UnhandledPromiseRejectionWarning: Error:
Invalid `prisma.movie.deleteMany()` invocation:
Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind: RawError { code: "unknown", message: "Command failed (CursorNotFound): cursor id 4391617472265441923 not found)" } })
at cb (/Users/nwsursock/Sites/test-algot/backend/node_modules/#prisma/client/runtime/index.js:36378:17)
at runMicrotasks ()
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async exports.deleteRequest (/Users/nwsursock/Sites/test-algot/backend/src/controllers/movie.controller.js:49:3)
(node:2171) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
My code is rather simple. I'm using the Prisma API in REST endpoints.
const { PrismaClient } = require("#prisma/client");
const prisma = new PrismaClient();
exports.createRequest = async (req, res) => {
const movie = req.body.movie;
console.log("============> importing", movie);
const data = {
name: movie.Name,
genre: movie.Genre,
descr: movie.Description,
director: movie.Director,
actors: movie.Actors,
year: movie.Year,
runtime: Number(movie["Runtime (Minutes)"]),
rating: Number(movie.Rating),
votes: Number(movie.Votes),
revenue: Number(movie["Revenue (Millions)"]),
score: Number(movie.Metascore),
};
const result = await prisma.movie.create({ data });
console.log("============> imported", result);
res.status(201).json({ message: "Movie correctly added!" });
};
exports.readRequest = async (req, res) => {
try {
const movies = await prisma.movie.findMany();
res.status(200).json(movies);
} catch (e) {
console.log("======> Error:", e.message);
}
};
exports.deleteRequest = async (req, res) => {
await prisma.movie.deleteMany({});
res.status(202).json({ message: "Table deleted!" });
};
It's a version problem. You have to downgrade to Prisma 2.26. Above, the bug appears. https://github.com/prisma/prisma/issues/8389
I am making an app with reactjs frontend and nodejs backend api for that at someplace i getting error something like this.
But here i want to get only this message email: {message: "This email is already taken", I tried to parse this error using some online turorial but when i try them i get error from backend.
This is the error after using errorparser
(node:14208) UnhandledPromiseRejectionWarning: ReferenceError: errors is not defined
at exports.default (C:/projects/bookworm-practice/bookworm-api/src/utils/parseErrors.js:5:15)
at C:/projects/bookworm-practice/bookworm-api/src/routes/users.js:14:54
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:14208) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14208) [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.
this is my parseError function
import _ from 'lodash';
export default function () {
const result = {};
_.forEach(errors, (val, key) => {
result[key] = val.message;
});
return result;
}
this is my user function where i am using parseError
import express from 'express';
import User from '../models/User';
import parseErrors from '../utils/parseErrors';
const router = express.Router();
router.post('/', (req, res) => {
const { email, password } = req.body.user;
const user = new User({ email });
user.setPassword(password);
user.save()
.then(user => res.json({ user: user.toAuthJSON() }))
//.catch(err => res.json({ err })); // this is the default one
.catch(err => res.status(400).json({ errors: parseErrors(err.errors)
//this is after adding parseErrors funtion
}))
})
export default router;
Your parseErrors function did not includes errors as argument
import _ from 'lodash';
export default function (errors) {
const result = {};
_.forEach(errors, (val, key) => {
result[key] = val.message;
});
return result;
}
I keep getting the "UnhandledPromiseRejectionWarning: ConfigError: Missing region in config" when trying to make requests to APIs I have set up in Node.js.
I'm new to DynamoDB and after setting up most of my boilerplate code I'm using Postman to test my routes. However I keep getting the same error each time I make a post request. I've checked some solutions on existing threads, namely: Configuring region in Node.js AWS SDK but cannot get it to work.
I am currently developing the app locally and checked the database where the items are being added.
My setup is as follows:
// user_controller.js
const uuid = require('uuid');
const sanitizer = require('validator');
const bcrypt = require('bcryptjs-then');
const AWS = require('aws-sdk');
const config = require('../config/config');
const { signToken, userByEmail, userById } = require('../Helpers/Users');
const isDev = true
Then in my code block I have the following:
// user_controller.js
(...)
if (isDev) {
AWS.config.update(config.aws_local_config);
} else {
AWS.config.update(config.aws_remote_config);
}
const DB = new AWS.DynamoDB.DocumentClient();
const params = {
TableName: config.aws_table_name,
Item: {
userId: await uuid.v1(),
firstName: sanitizer.trim(firstName),
lastName: sanitizer.trim(lastName),
email: sanitizer.normalizeEmail(sanitizer.trim(email)),
password: await bcrypt.hash(password, 8),
level: 'standard',
createdAt: new Date().getTime(),
updatedAt: new Date().getTime(),
},
}
return userByEmail(params.Item.email) // Does the email already exist?
.then(user => { if (user) throw new Error('User with that email exists') })
.then(() => DB.put(params).promise()) // Add the data to the DB
.then(() => userById(params.Item.id)) // Get user data from DB
.then(user => (err, data) => {
console.log("AFTER USER CREATED")
if (err) {
res.send({
success: false,
message: 'Error: Server error'
});
} else {
console.log('data', data);
res.send({
statusCode: 201,
message: 'Success - you are now registered',
data: { token: signToken(params.Item.id), ...user },
});
}
})
(...)
Finally I am importing the config from separate file:
// config.js
module.exports = {
aws_table_name: 'usersTable',
aws_local_config: {
region: 'local',
endpoint: 'http://localhost:8000'
},
aws_remote_config: {}
}
In have already configured the aws-sdk:
AWS Access Key ID [****************foo]:
AWS Secret Access Key [****************bar]:
Default region name [local]:
Default output format [json]:
Here is the output I keep getting:
(node:4568) UnhandledPromiseRejectionWarning: ConfigError: Missing region in config
at Request.VALIDATE_REGION (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:92:45)
at Request.callListeners (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
at callNextListener (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/sequential_executor.js:96:12)
at /Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:86:9
at finish (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:350:7)
at /Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:368:9
at SharedIniFileCredentials.get (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/credentials.js:127:7)
at getAsyncCredentials (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:362:24)
at Config.getCredentials (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:382:9)
at Request.VALIDATE_CREDENTIALS (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:81:26)
(node:4568) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
(node:4568) [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.
Like I said, I've tried a lot of variations on this but to no avail. Would love some help, thanks.
I dont know if this helps, but I used none instead of local for the region and it seemed to work for me
AWS.config.update({ region: 'none' })
I have the following route for the password reset form, the form has a password and password confirmation field.
router.post('/users/reset/:token', (req, res, next) => {
if(req.body.password === req.body['password-confirm']) {
req.flash('error', 'Passwords do not match!');
res.redirect('/users/forgot');
}
User.findOne({
resetPasswordToken: req.params.token,
resetPasswordExpires: { $gt: Date.now() }
}, function(err, user) {
if(!user) {
req.flash('error', ' Password reset is invalid or has expired');
res.redirect(302, '/login');
}
const setPassword = promisify(user.setPassword, user);
setPassword(req.body.password);
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
const updatedUser = user.save();
user.save((saveError, updatedUser) => {
// Check if saveError is present here and handle appropriately
req.login(updatedUser, loginError => {
req.flash('success_msg', 'Your password has been reset successfully! You are now logged in!');
res.redirect('/dashboard' + req.user);
})
});
});
});
When I fill out the form I get the following error
Fri Jan 26 2018 11:28:55 GMT+0000 (GMT): GET /users/reset/6e2574bfa532e0d13af7fae61114308f9a683767
Mongoose: users.findOne({ resetPasswordExpires: { '$gt': new Date("Fri, 26 Jan 2018 11:28:55 GMT") }, resetPasswordToken: '6e2574bfa532e0d13af7fae61114308f
9a683767' }, { fields: {} })
Fri Jan 26 2018 11:28:55 GMT+0000 (GMT): GET /favicon.ico
Fri Jan 26 2018 11:29:02 GMT+0000 (GMT): POST /users/reset/6e2574bfa532e0d13af7fae61114308f9a683767
Mongoose: users.findOne({ resetPasswordExpires: { '$gt': new Date("Fri, 26 Jan 2018 11:29:02 GMT") }, resetPasswordToken: '6e2574bfa532e0d13af7fae61114308f
9a683767' }, { fields: {} })
Mongoose: users.update({ _id: ObjectId("5a5c6740b9e210087e098fd6") }, { '$unset': { resetPasswordExpires: 1, resetPasswordToken: 1 } })
Mongoose: users.update({ _id: ObjectId("5a5c6740b9e210087e098fd6") }, { '$unset': { resetPasswordExpires: 1, resetPasswordToken: 1 } })
(node:1451) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'apply' of undefined
at /Users/benbagley/Code/poetry-out-loud/node_modules/es6-promisify/dist/promisify.js:75:41
at new Promise (<anonymous>)
at /Users/benbagley/Code/poetry-out-loud/node_modules/es6-promisify/dist/promisify.js:54:20
at /Users/benbagley/Code/poetry-out-loud/routes/users.js:321:5
at model.Query.<anonymous> (/Users/benbagley/Code/poetry-out-loud/node_modules/mongoose/lib/model.js:4056:16)
at /Users/benbagley/Code/poetry-out-loud/node_modules/kareem/index.js:273:21
at /Users/benbagley/Code/poetry-out-loud/node_modules/kareem/index.js:131:16
at process._tickCallback (internal/process/next_tick.js:150:11)
(node:1451) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a c
atch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1451) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminat
e the Node.js process with a non-zero exit code.
Fri Jan 26 2018 11:29:02 GMT+0000 (GMT): GET /users/forgot
events.js:136
throw er; // Unhandled 'error' event
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at validateHeader (_http_outgoing.js:503:11)
at ServerResponse.setHeader (_http_outgoing.js:510:3)
at ServerResponse.header (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/response.js:767:10)
at ServerResponse.location (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/response.js:884:15)
at ServerResponse.redirect (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/response.js:922:18)
at req.login.loginError (/Users/benbagley/Code/poetry-out-loud/routes/users.js:332:13)
at /Users/benbagley/Code/poetry-out-loud/node_modules/passport/lib/http/request.js:51:48
at /Users/benbagley/Code/poetry-out-loud/node_modules/passport/lib/sessionmanager.js:16:14
at pass (/Users/benbagley/Code/poetry-out-loud/node_modules/passport/lib/authenticator.js:297:14)
at Authenticator.serializeUser (/Users/benbagley/Code/poetry-out-loud/node_modules/passport/lib/authenticator.js:299:5)
at SessionManager.logIn (/Users/benbagley/Code/poetry-out-loud/node_modules/passport/lib/sessionmanager.js:14:8)
at IncomingMessage.req.login.req.logIn (/Users/benbagley/Code/poetry-out-loud/node_modules/passport/lib/http/request.js:50:33)
at user.save (/Users/benbagley/Code/poetry-out-loud/routes/users.js:330:11)
at /Users/benbagley/Code/poetry-out-loud/node_modules/mongoose/lib/model.js:4056:16
at /Users/benbagley/Code/poetry-out-loud/node_modules/mongoose/lib/services/model/applyHooks.js:170:20
at process._tickCallback (internal/process/next_tick.js:150:11)
I'm still new to node so any refactoring tips, or fixes for this would be most appreciated, been stuck on this issue for a few days, not sure what I'm doing wrong.
Thank you.
First thing is that this error occur when node sent response of API call more than one time. Secondly, it is best practice to use return when sending response for example return res.json(<OBJECT>);
In your code you are checking the password like
req.body.password === req.body['password-confirm']
it should be like
req.body.password !== req.body['password-confirm']
that may the case that causing node to sent multiple response
You are sending response to client multiple time, that's why facing Cannot set headers after they are sent to the client error.
In your case, your are not returning (exiting) from the function execution when you should have. E.g. when password doesn't match, you are trying to redirect user to /users/forgot, but you are not returning the function there. Hence, code below if condition executes and try to send response back again.
Solution:
router.post('/users/reset/:token', (req, res, next) => {
if // some condition {
// some code
return res.redirect('/users/forgot');
}
User.findOne({
// some code
}, function(err, user) {
if(!user) {
// some code
return res.redirect(302, '/login');
}
// some code
user.save((saveError, updatedUser) => {
req.login(updatedUser, loginError => {
// some code
return res.redirect('/dashboard' + req.user);
})
});
});
});