i tried all the methods to resolve this problem but i couldn't resolved it it shows the error using twilio to generate otp and verify it.Error: username is required this error will shows i will install dotenv and all the npm packages
index.js
const express = require("express")
const app = express()
const port=4000
app.listen(port,()=>{
console.log(`Server is running at ${port}`)
})
const config=require('./config');
const client = require('twilio')(process.env.ACCOUNT_SID, process.env.AUTH_TOKEN)
// /login
// - phone number
// - channel (sms/call)
// /verify
// - phone number
// - code
app.get('/', (req, res) => {
res.status(200).send({
message: "You are on Homepage",
info: {
login: "Send verification code through /login . It contains two params i.e. phonenumber and channel(sms/call)",
verify: "Verify the recieved code through /verify . It contains two params i.e. phonenumber and code"
}
})
})
// Login Endpoint
app.get('/login', (req, res) => {
if (req.query.phonenumber) {
client
.verify
.services(process.env.SERVICE_ID)
.verifications
.create({
to: `+${req.query.phonenumber}`,
channel: req.query.channel === 'call' ? 'call' : 'sms'
})
.then(data => {
res.status(200).send({
message: "Verification is sent!!",
phonenumber: req.query.phonenumber,
data
})
})
} else {
res.status(400).send({
message: "Wrong phone number :(",
phonenumber: req.query.phonenumber,
data
})
}
})
// Verify Endpoint
app.get('/verify', (req, res) => {
if (req.query.phonenumber && (req.query.code).length === 4) {
client
.verify
.services(process.env.SERVICE_ID)
.verificationChecks
.create({
to: `+${req.query.phonenumber}`,
code: req.query.code
})
.then(data => {
if (data.status === "approved") {
res.status(200).send({
message: "User is Verified!!",
data
})
}
})
} else {
res.status(400).send({
message: "Wrong phone number or code :(",
phonenumber: req.query.phonenumber,
data
})
}
})
// listen to the server at 3000 port
app.listen(port, () => {
console.log(`Server is running at ${port}`)
})
const client and all the const variables or all the process i will shows but error occurs and i don't know the exact solution.
config.js
username is required error occurs i tried all the possibilities that i saw so kindly help me please
Related
I'm trying to generate OTP for my application but it is showing a error that Otp is not a constructor
Otp is not a constructor at (otplogin\otp\routes\index.js:18:19)
Here is my code
router.post("/", function (req, res, next) {
const number = req.body.number;
const otp = Math.floor(1000 + Math.random() * 9000);
const otpData = new Otp({
number: number,
otp: otp,
});
otpData
.save()
.then((result) => {
console.log(result);
res.status(200).json({
message: "OTP sent successfully",
});
})
.catch((err) => {
console.log(err);
res.status(500).json({
error: err,
});
});
});
i have a problem with my custom server, i'm trying to setup an api that send whatsapp messages in react as a frontend.
So, i have actually a route that send the QR to the frontend (working fine), a route that handle the authentication event (working fine) and
PROBLEM HERE:
...a route that send a message to a specific number (NOT WORK)
here my server code...what i'm doing wrong? if i launch a POST request to the endpoint on postman, i get an infinite loading (no errors).
const express = require('express')
const router = express.Router()
const fs = require('fs')
const { Client, LocalAuth } = require('whatsapp-web.js')
const authStrategy = new LocalAuth({
clientId: 'adminSession',
})
const worker = `${authStrategy.dataPath}/session-admin/Default/Service Worker`
if (fs.existsSync(worker)) {
fs.rmdirSync(worker, { recursive: true })
}
const client = new Client({
takeoverOnConflict: true,
authStrategy,
})
const sessionData = {
client: 'admin',
session: true,
qrCodeScanned: true,
}
client.on('authenticated', (session) => {
fs.writeFile(
'waSession.json',
JSON.stringify(sessionData),
'utf-8',
(err) => {
if (!err) {
console.log('Session saved on disk...')
}
}
)
})
router.get('/whatsapp/auth', async (req, res) => {
const dir = './waSession.json'
fs.readFile(dir, (err, data) => {
if (data.length === 0) {
return res.status(200).json({
message: 'You need to login first',
})
} else {
return res.status(200).json({
message: 'You are logged in.',
})
}
})
})
router.get('/whatsapp', async (req, res) => {
try {
client.on('qr', (qr) => {
res.status(200).send({
message: 'Connect whatsapp with this qr-code',
qrCode: qr,
})
})
await client.initialize()
res.status(404)
} catch (err) {
res.send(err)
}
})
router.post('/whatsapp/send', async (req, res) => {
const { phoneNumber, message } = req.body
try {
client.on('ready', async () => {
const number = phoneNumber
const text = message
const chatId = number.substring(1) + '#c.us'
await client.sendMessage(chatId, text)
})
await client.initialize()
res.json('Messaggio inviato')
} catch (err) {
res.status(404).send(err)
await client.destroy()
}
})
module.exports = router
A Client represents one authenticated WhatsApp user, and you have only one global variable client. This implies that all incoming requests will represent the same WhatsApp user, even if several different real users send requests to your server in parallel. This is probably not what you intend.
I suggest that you use express-session to associate every client with a session. Then a user needs to create a client and authenticate it only once during a session. All subsequent requests in the same session will re-use that client, and the client.on(...) and client.initialize() commands will not be repeated.
The Cookie that I am sending from http://localhost:5000/users/register , is not being set into the header of http://localhost:5000/users/register. I am able to access the cookie in the body but not in the headers.
My App.js code is
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const fileUpload = require("express-fileupload");
const cookieParser = require("cookie-parser");
const users = require("./routers/users");
const app = express();
app.use(express.json());
app.use(cookieParser());
app.use(cors());
app.use(
fileUpload({
useTempFiles: true,
})
);
// connecting to MongoDB
const mongoURL = process.env.MONGO_URL;
mongoose
.connect(mongoURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => console.log("DataBase has been connected !"))
.catch((err) => console.log("Cannot connect to database", err.message));
// routes
app.use("/users", users);
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`I am listening at ${port}`);
});
My Router's Code
const express = require("express");
const bcrypt = require("bcrypt");
const { Users, userSchema } = require("../models/user");
const jwt = require("jsonwebtoken");
const router = express.Router();
// registering
router.post("/register", async (req, res) => {
try {
const { name, email, password } = req.body;
console.log(name, email, password);
//console.log(Users);
//console.log(userSchema);
let user = await Users.findOne({ email });
if (user) return res.status(404).json({ msg: "The email already exists" });
if (password.length < 6)
return res.status(404).json({ msg: "The password is less than 6" });
// Hashing password
const newPassword = await bcrypt.hash(password, 10);
// creating a user and saving in db
user = await new Users({ name, email, password: newPassword });
await user.save();
// creating JWT token for authenticating the user
const accessToken = createAccessToken({ id: user._id });
const refreshToken = createRefreshToken({ id: user._id });
// Cookie is being sent in the headers to the listed "path"
res.cookie("refreshToken", refreshToken, {
httpOnly: true,
path: "/users/refreshtoken",
});
res.json({ accessToken });
//return res.json({ password, newPassword, user, accessToken, refreshToken });
} catch (err) {
return res.status(500).json({ msg: err.message });
}
});
router.get("/refreshtoken", (req, res) => {
try {
const rfToken = req.cookies.refreshToken;
if (!rfToken)
return res.status(400).json({ msg: "Please login or sign up" });
// verifying the token that we sent when user registered
// the token shows ig it's the registered user or not
jwt.verify(rfToken, process.env.REFRESH_TOKEN, (error, decoded) => {
if (error)
return res.status(400).json({ msg: "Please login or sign up" });
console.log(decoded);
const accessToken = createAccessToken({ id: decoded.id });
res.json({ decoded, accessToken });
});
res.json({ msg: "DS", rfToken });
} catch (error) {
return res.status(500).json({ msg: error.message });
}
});
const createAccessToken = (userID) => {
return jwt.sign(userID, process.env.ACCESS_TOKEN, { expiresIn: "1d" });
};
const createRefreshToken = (userID) => {
return jwt.sign(userID, process.env.REFRESH_TOKEN, { expiresIn: "7d" });
};
module.exports = router;
The Cookie is not being set to the header of the "/users/refreshtoken", it is being sent in the body, I can see the cookie in the body of "/users/refreshtoken" but not in the header. I don't know why.
This error is usually caused by improper asynchronous sequencing which causes you to have one or more code paths that can attempt to send multiple responses to the same incoming request.
I see an example of this in your router.get("/refreshtoken", ...) route handler. One place this problem can occur is here where it's marked:
router.get("/refreshtoken", (req, res) => {
try {
const rfToken = req.cookies.refreshToken;
if (!rfToken)
return res.status(400).json({ msg: "Please login or sign up" });
// verifying the token that we sent when user registered
// the token shows ig it's the registered user or not
jwt.verify(rfToken, process.env.REFRESH_TOKEN, (error, decoded) => {
if (error)
return res.status(400).json({ msg: "Please login or sign up" });
console.log(decoded);
const accessToken = createAccessToken({ id: decoded.id });
=====>
res.json({ decoded, accessToken });
=====>
});
=====>
res.json({ msg: "DS", rfToken });
=====>
} catch (error) {
return res.status(500).json({ msg: error.message });
}
});
This code will launch the asynchronous and non-blocking jwt.verify() function and then will immediately execute:
res.json({ msg: "DS", rfToken });
Then, some time later it will execute either:
return res.status(400).json({ msg: "Please login or sign up" });
or
const accessToken = createAccessToken({ id: decoded.id });
both of which will try to send a second response. It appears to me that your code in this route has three possible outcomes:
No token is present
Token is present, but not valid
Token is present and valid
That means you should have three non-overlapping responses. But, you have four places you send a response and they overlap, causing duplicate responses. I don't know exactly why you have the res.json({ msg: "DS", rfToken }); line of code as it is always run anytime there is a token present (whether valid or invalid). You need to fix that. Probably you should just remove that line of code entirely or replace one of the other responses with this line of code inside the jwt.verify() callback.
I am testing my application however I could not figure out how to test the authenticated endpoints with supertest, based on documentation i wrote this, but it is not working. Can someone help me how to test authenticated endpoints: this is my code:
const request = require("supertest");
const app = require("../../server/app");
let testSession = null;
beforeEach(function () {
testSession = request.agent(app);
});
test("Should add new blogs", async () => {
await testSession
.post("/api/v1/blogs")
.send({
title: "first test",
location: "ny",
position: "developer",
})
.expect(200);
});
here is the result:
expected 200 "OK", got 401 "Unauthorized"
endpoints are working but here are the controller and route:
exports.createBlog = (req, res) => {
//key comes from client
//because if other user send the request I dont wanna lock the request for other one
//we send the key with the save button in the controller menu
const lockId = req.query.lockId;
let blog;
if (!lock.isBusy(lockId)) {
lock
.acquire(lockId, async () => {
const blogData = req.body;
blog = await new Blog(blogData);
if (req.user) {
blog.userId = req.user.sub;
blog.author = req.user.name;
}
await blog.save();
})
.then(() =>
res.status(200).json({ message: "Blog is saved!", blog: blog })
)
.catch((e) => res.status(422).json({ message: e.message }));
} else {
return res.status(422).json({ message: "Blog is saving" });
}
router.post(
"/",
authService.checkJwt,
authService.checkRole("siteOwner"),
blogCtrl.createBlog
);
I am trying to make a subscription to stripe, and in order for that I need a user created first - done.
After I create the user how can i proceed automatically to make the subscription for given user?
my code so far
const stripe = require('./../constants/stripe');
const postStripeCharge = res => (stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).send({
error: stripeErr
});
}
else {
res.status(200).send({
success: stripeRes
});
}
}
const paymentApi = app => {
app.get('/', (req, res) => {
res.send({
message: 'Hello Stripe checkout server!',
timestamp: new Date().toISOString()
})
});
app.post('/', (req, res) => {
console.log('request in server', req);
// stripe.charges.create(req.body, postStripeCharge(res));
stripe.customers.create({
description: 'customer for ' + req.body.email,
source: req.body.token
}, postStripeCharge(res))
});
return app;
};
module.exports = paymentApi;
this is the code i want to call after the user is created :
stripe.subscriptions.create({
customer: req.id,
items: [{
plan: 'plan_CyQRCVcrEztYI7'
}],
}
Fixed it: it is not req.body.token but req.body.source, and then it works as it should.