Firebase email function not finding user - node.js

I have a contact form on my website that upon sending clicking to submit, runs a firebase function to execute the request. The issue i'm having all of a sudden is the following error (taken from the firebase logs)
Error: There is no user record corresponding to the provided identifier.
at FirebaseAuthError.FirebaseError [as constructor] (/workspace/node_modules/firebase-admin/lib/utils/error.js:42:28)
at FirebaseAuthError.PrefixedFirebaseError [as constructor] (/workspace/node_modules/firebase-admin/lib/utils/error.js:88:28)
at new FirebaseAuthError (/workspace/node_modules/firebase-admin/lib/utils/error.js:147:16)
at /workspace/node_modules/firebase-admin/lib/auth/auth-api-request.js:513:15
at /workspace/node_modules/firebase-admin/lib/auth/auth-api-request.js:1347:13
at process._tickCallback (internal/process/next_tick.js:68:7)
The function in charge of the sending is the following:
sendRequest() {
this.loading = true
return new Promise(resolve => {
const newUrl = `https://us-central1-easymediakit.cloudfunctions.net/contactForm?name=${
this.form.name
}&email=${this.form.email}&message=${encodeURI(
this.form.message
)}&uid=${this.uid}`
fetch(`${newUrl}`, {
withCredentials: true,
headers: {
'Content-Type': 'application/json'
}
})
.then(() => {})
.then(async response => {
this.loading = false
this.success = 'Your email has been sent.'
resolve(response)
})
}).catch(error => {
this.loading = false
console.log('Send error', error)
})
}
It was working and I haven't made any changes to the function that handles the email sending so I'm not sure where the issue is coming from, any guidance is greatly appreciated.
Update:
in index.js
const contactFormModule = require('./email/email-contact-form')
exports.contactForm = functions.https.onRequest((req, res) => {
return contactFormModule.handler(req, res)
the contact form:
const cors = require('cors')({ origin: true })
const domain = 'mg.epkbuilder.com'
const apiKey = 'f27b2755b05f3a366542ea538a00c6a2-d32d817f-dec22e2e'
const mailgun = require('mailgun-js')({ apiKey, domain })
const admin = require('firebase-admin')
const MailComposer = require('nodemailer/lib/mail-composer')
exports.handler = (req, res) => {
cors(req, res, async () => {
const uid = req.query.uid
const name = req.query.name
const email = req.query.email
const message = req.query.message
console.log('uid', uid)
console.log('message', `${message}`)
const user = await admin.auth().getUser(uid)
console.log('user', user)
const mailOptions = {
from: `${name} noreply#easymediakit.io`,
replyTo: `${name} ${email}`,
to: user.email,
subject: `Direct message from ${name}`,
text: `${message}`
}
let mail = new MailComposer(mailOptions).compile()
console.log('mail', mail)
return mail.build((error, message) => {
if (error) {
console.log('Email unsuccessful', error)
res.status(400).send(error)
}
const dataToSend = {
to: user.email,
message: message.toString('ascii')
}
return mailgun.messages().sendMime(dataToSend, sendError => {
if (sendError) {
console.log('Email unsuccessful', error)
res.status(400).send(error)
}
return res.send('Email successfully sent!')
})
})
})
}

The error seems to come from this line:
const user = await admin.auth().getUser(uid)
The error indicates that no user exists in Firebase Authentication for the uid value that you specified. You might want to double check the this.uid value in )}&uid=${this.uid} in your client-side code.

Related

Issue with form data send to database using axios in react js?

Hello everyone I have an issue I am doing login and registration form using react and node and mongodb at one point I am stuck at registration please let me know the solution.
Now first start with back end
This my controller file
const users = require('../models/users');
var bcrypt = require('bcryptjs');
const userList = async (req,res) =>{
let data = await users.find();
res.json(data);
}
const userAdd = async (req,res)=>{
let {name,email,password,cpassword} = req.body;
let data = new users({name,email,password,cpassword});
let response = await data.save();
let myToken = await data.getAuthToken();
res.status(200).json({message: 'User added sucessfully', token:myToken});
}
const userLogin = async (req,res)=>{
if(!req.body.email || !req.body.password){
res.status(301).json({message: 'error',message:"Please enter email and password"});
}
let user = await users.findOne({email: req.body.email});
var responseType = {
message: "ok"
}
if(user){
var match = await bcrypt.compare(req.body.password, user.password)
if(match){
let myToken = await user.getAuthToken();
responseType.message = 'login sucessfully';
responseType.token = myToken;
}else
{
responseType.message = 'Invalid Password';
}
}else{
responseType.message = 'Invalid Email ID';
}
console.log(user);
res.status(200).json({message: 'ok', data: responseType});
}
module.exports = {
userList,
userAdd,
userLogin
};
Now come to Front-End part
This is my registration form
const Register = () => {
const [inputField, setInputField] = useState({
name: '',
email: '',
password: '',
cpassword: ''
})
const inputHandler = (e) =>{
setInputField({...inputField, [e.target.name] : e.target.value})
}
const submitButton = async () =>{
if(validForm()){
let url = 'http://localhost:8080/users/add'
let options={
method: "post",
url: url,
headers:{
},
data: inputField
}
try{
let response = await axios(options)
console.log("res",response);
if(response.status == 200){
toast.success("Added Sucessfully");
}
}
catch(e){
toast.error("Something went wrong..!");
}
}else{
toast.error("Form Invalid..!");
}
}
Data is not store in MongoDB database.
Thanks in advance.

TypeError: botGuilds.find is not a function

This code is for an express website for my discord bot I need it to catch the mutual guilds but it's giving this error:
TypeError: botGuilds.find is not a function
at C:\Users\não te interessa\Desktop\projetos\bot\backend\utils\utils.js:3:56
at Array.filter (<anonymous>)
at Proxy.methods.<computed> (C:\Users\não te interessa\Desktop\projetos\bot\backend\node_modules\mongoose\lib\types\array\methods\index.js:956:24)
at getMutualGuilds (C:\Users\não te interessa\Desktop\projetos\bot\backend\utils\utils.js:3:28)
at C:\Users\não te interessa\Desktop\projetos\bot\backend\routes\discord.js:11:28
at processTicksAndRejections (node:internal/process/task_queues:96:5)
which uses getMutualGuilds:
const router = require("express").Router()
const { getBotGuilds } = require("../utils/api")
const { getMutualGuilds } = require("../utils/utils")
const User = require('../database/schemas/Users')
router.get('/guilds', async (req, res) => {
const guilds = await getBotGuilds();
const user = await User.findOne({ discordId: req.user.discordId });
if (user) {
const userGuilds = user.get('guilds');
const mutualguilds = await getMutualGuilds(userGuilds, guilds);
res.send(mutualguilds);
}
});
module.exports = router
getMutualGuilds code:
function getMutualGuilds(userGuilds, botGuilds) {
return userGuilds.filter((guild) => botGuilds.find((botGuild) => (botGuild.id === guild.id) && (guild.permissions & 0x20) === 0x20))
}
module.exports = { getMutualGuilds }
code of botGuilds:
const fetch = require("node-fetch")
const TOKEN = "token of my bot";
async function getBotGuilds() {
const response = await fetch('http://discord.com/api/v8/users/#me/guilds', {
method: 'GET',
headers:{
Authorization: `Bot ${TOKEN}`
}
})
return response.json()
}
module.exports = { getBotGuilds }

I get undefined when reading my response but there is a response in React.js

I can't figure it out, the answer comes in the network table but when I want to console.log it, this will display undefined. Do you have any idea why? I attach the pictures and the code.
Here is a image with my codes and response
Here is the code - first one is where I send the response. As I said, it's going well on network tab, I get a 200 status.
export const getAccountStatus = async (req, res) => {
const user = await User.findById(req.user._id).exec();
const account = await stripe.accounts.retrieve(user.stripe_account_id);
// console.log("user account retrieve", account);
const updatedUser = await User.findByIdAndUpdate(
user._id,
{
stripe_seller: account
},
{ new: true }
)
.select("-password")
.exec();
console.log(updatedUser);
res.send(updatedUser);
};
Here is the page where i want to console.log it:
const StripeCallback = ({ history }) => {
const { auth } = useSelector(state => ({ ...state }));
const dispatch = useDispatch();
useEffect(() => {
if (auth && auth.token) accountStatus();
}, [auth]);
const accountStatus = async () => {
try {
const res = await getAccountStatus(auth.token);
console.log(res);
} catch (err) {
console.log(err);
}
};
return <div>test</div>;
};
Ang here is the Axios.post (which is working well as I know):
export const getAccountStatus = async token => {
await axios.post(
`${process.env.REACT_APP_API}/get-account-status`,
{},
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
};
Thank you!
getAccountStatus doesn't have a return statement, so res in const res = await getAccountStatus(auth.token); will always be undefined.
export const getAccountStatus = async token => {
return axios.post( // <----- added return
`${process.env.REACT_APP_API}/get-account-status`,
{},
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
};

when trying to test my hapijs application "register" [1]: -- missing --

I am using hapijs v17.2.3 . Also I am very new to hapi .I am trying to test my code using Lab a simple test utility for Node.js and code assertion library.
my test.js file is :
'use strict';
var path = require('path');
var dotEnvPath = path.resolve('./.env');
require('dotenv').config({ path: dotEnvPath });
const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const describe = lab.describe;
const it = lab.it;
const expect = Code.expect;
const Joi = require('joi');
const Hapi = require('hapi');
const app = require('../app');
const server = new Hapi.Server();
const getServer = async () => {
const server = new Hapi.Server();
// server.connection();
return server.register(app)
.then(() => server);
};
lab.experiment('signup testing in "/signup"', () => {
lab.test('Return true if the user can successfully signup', (done, flags) => {
const signUpData = {
method: 'POST',
url: '/signup',
payload: {
name: 'vulcan',
password: 'vulcan#123',
email: 'vulcan#gmail.com',
username: 'vulcan123',
dob: '12-08-1994'
}
};
getServer()
.then((server) => server.inject(signUpData))
.then((response) => {
flags.note(`demo test note`);
if (response) {
console.log(response.statusCode);
Code.expect(response.statusCode).to.equal(201);
Code.expect(payload).to.contain(['name', 'password', 'email', 'username', 'dob']);
}
done();
});
});
});
lab.experiment('1) login test ', () => {
lab.test('login has successfully done', (done) => {
const loginData = {
method: 'POST',
url: '/login',
payload: {
email: 'wrong email',
login_password: 'wrong password',
}
};
getServer()
.then((server) => {
server.inject(loginData)
})
.then((response) => {
Code.expect(response.statusCode).to.equal(200);
done();
});
});
});
my test command is : lab --assert code --coverage -t 100
my signup controller is :
exports.postForm = {
description: 'Submit the signup page',
tags: ['api'],
notes: 'accepts name password verify and email',
auth: {
mode: 'try',
strategy: 'session'
},
validate: {
payload: {
name: Joi.string().required(),
password: Joi.string().min(4).max(20).required(),
verify: Joi.string().required(),
email: Joi.string().email().required(),
username: Joi.string().min(3).max(20).required(),
referredBy: Joi.any(),
dob: Joi.date().required().label('Date of Birth')
},
failAction: (request, h, error) => {
console.log('Validation Failed');
request.yar.flash('error', error.details[0].message.replace(/['"]+/g, ''));
return h.redirect('/signup').takeover();
}
},
handler: async (request, h) => {
try {
var user = {
name: request.payload.name,
password: request.payload.password,
email: request.payload.email,
username: request.payload.username.toLowerCase(),
referralName: request.payload.username + '#gg',
emailConfirmationToken: uuidv1(),
dob: request.payload.dob,
tnc: true
};
let data = await signupHelper.signUpUser(user, request);
if (data.statusCode === 201) {
if (request.payload.referredBy) {
let configureReferral = await signupHelper.configureReferral(request.payload.referredBy, data.userId);
if (configureReferral.statusCode === 200) {
request.yar.flash('success', 'Account created, Please Login');
return h.redirect('/login');
}
}
request.yar.flash('success', 'Account created, Please Login');
return h.redirect('/login');
} else {
request.yar.flash('error', data.message);
return h.redirect('/signup');
}
} catch (error) {
logger.error(error);
return h.redirect('/signup');
}
}
};
my login control :
exports.login = {
description: 'Post to the login page',
notes: 'Accepts two paramters email and password which got validation',
tags: ['api'],
auth: {
mode: 'try',
strategy: 'session'
},
plugins: {
crumb: {
key: 'crumb',
source: 'payload',
},
'hapi-auth-cookie': {
redirectTo: false
}
},
validate: {
payload: {
email: Joi.string().min(3).email().required(),
login_password: Joi.string().min(4).required()
},
failAction: (request, h, error) => {
request.yar.flash('error', error.details[0].message.replace(/['"]+/g, ''));
return h.redirect('/login').takeover();
}
},
handler: async (request, h) => {
try {
const next = request.query.next ? request.query.next : '/dashboard';
if (request.auth.isAuthenticated) {
return h.redirect(next);
}
let resultData = await loginHelper.findByCredentials(request.payload.email, request.payload.login_password);
if (resultData.statusCode === 200) {
request.cookieAuth.set(resultData.user);
return h.redirect(next);
} else {
request.yar.flash('error', resultData.message);
return h.redirect('/login');
}
} catch (error) {
logger.error(error);
request.yar.flash('error', error.message);
return h.redirect('/login');
}
}
};
this is the error when I run the test:
Socket server start initiated
Socket server started
Server started at https://127.0.0.1:8000
signup testing in "/signup"
✔ 1) Return true if the user can successfully signup (3615 ms)
1) login test
✖ 2) login has successfully done
(node:9708) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Invalid plugin options {
"plugin": {
"sock": {
"init": function (server, options) {\n
..........
..........
},
"register" [1]: -- missing --
}
}
[1] "register" is required
at new AssertionError (internal/errors.js:102:11)
at Object.exports.assert (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/node_modules/hoek/lib/index.js:517:11)
at Object.exports.apply (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/config.js:22:10)
at internals.Server.register (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/server.js:410:31)
at getServer (/home/jeslin/projects/hapi/gamergully/test/tests-signup.js:23:19)
at lab.test (/home/jeslin/projects/hapi/gamergully/test/tests-signup.js:115:9)
at Immediate.setImmediate [as _onImmediate] (/home/jeslin/projects/hapi/gamergully/node_modules/lab/lib/runner.js:628:31)
at runCallback (timers.js:810:20)
at tryOnImmediate (timers.js:768:5)
at processImmediate [as _immediateCallback] (timers.js:745:5)
(node:8764) 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: 6)
(node:8764) [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.
Mongo Database connected
when I run only one test case, it wont return any error. If I run more
than one this error is showing
I have done this by following this link
This could be related to your server instance creation. In one test you are trying to create more than one server instance with the same configuration. That might be the problem I think. When I create tests, I am using lab.before and lab.beforeEach methods to create instances.
Here is a real-world test case from one of my projects.
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const describe = lab.describe;
const it = lab.it;
const before = lab.before;
const after = lab.after;
const expect = require('code').expect;
// ..... other stufff
describe('Test Routes', () => {
let server;
before(async () => {
server = new Hapi.Server();
await server.register(app)
});
after(async () => {
await server.stop();
});
it('It should obtain valid response', async () => {
const qs = querystring.stringify(queryParams);
const res = await server.inject({
url: `/s?${qs}`,
method: 'get',
headers: {
"Cookie": "user=aighaeshaighaPopaGoochee8ahlei8x"
}
});
expect(res.statusCode).to.equal(200);
expect(res.result.userid).to.exist();
expect(res.result.status).to.equal(true);
// handle play action
const res2 = await server.inject({
url: `/b?id=${res.result.userid}`,
method: 'get'
});
expect(res2.statusCode).to.equal(200);
expect(res2.result.status).to.equal(true);
});
//
it('It should reject invalid request', async () => {
const res = await server.inject({
url: `/a?a=b&id=iChah3Ahgaaj2eiHieVeem6uw2xaiD5g`,
method: 'get'
});
expect(res.statusCode).to.equal(200);
expect(res.result.status).to.equal(false);
expect(res.result.message).to.equal("Invalid information");
});
// ... goes on
});
Just pay attention to before and after calls. I am creating only one instance of server then using it along side my test cases or use beforeEach and afterEach to isolate your instances, it's your choice.

Getting Error: Uncaught (in promise): Response with status: 404 Not Found for URL:

I am making a request to endpoint written in koa.js and I am new to this framework.
API return 404 response.
Route file looks like below:
const collabRepo = require("../repo/collab/collab-repo")
const notificationRepo = require("../repo/collab/notification-repo")
const rest = require("restling")
const jwt = require("jsonwebtoken")
const CONFIG = require("config")
const SECRET = CONFIG.get("auth.jwt.secret")
const JWT_COOKIE_NAME = CONFIG.get("auth.jwt.cookie.name")
const TOKENTIME = CONFIG.get("auth.jwt.ttl")
const FEED_API_BASE = CONFIG.get("urls.activityFeedApi")
const FEED_API_VERSION = "v1"
const FEED_API = FEED_API_BASE + "/" + FEED_API_VERSION
const logger = require("winston")
const { jwtAuth } = require("../auth")
const PROTECTED_ROUTES = [
"/collab/follow",
"/collab/unfollow",
"/collab/follower/list",
"/collab/follower/public/list",
"/collab/following/list",
"/collab/following/public/list",
"/collab/following/count",
"/collab/following",
"/collab/notify",
"/collab/discover/people",
"/collab/discover/expression"
]
async function followFeed(toFollowId, userObject, follow) {
const args = {
data: {
follow: {
class: "user",
id: toFollowId
}
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Cookie": JWT_COOKIE_NAME + "=" + jwt.sign(userObject, SECRET, {
expiresIn: TOKENTIME
})
}
}
if (follow) {
return rest.post(FEED_API + '/follow', args)
}
return rest.post(FEED_API + '/unfollow', args)
}
when I log rest.post(FEED_API + '/follow', args) I get:
Promise { _bitField: 0, _fulfillmentHandler0: undefined,
_rejectionHandler0: undefined, _progressHandler0: undefined, _promise0: undefined, _receiver0: undefined, _settledValue: undefined } Unhandled rejection Error: Cannot POST
http://localhost/activity-feed/api/v1/follow
at Request. (\node_modules\restling\restling.js:26:21)
at Request.emit (events.js:180:13)
at Request._fireSuccess (\node_modules\restler\lib\restler.js:223:12)
at \node_modules\restler\lib\restler.js:161:20
at IncomingMessage.auto (\node_modules\restler\lib\restler.js:402:7)
at Request._encode (\node_modules\restler\lib\restler.js:198:29)
at \node_modules\restler\lib\restler.js:157:16
at Request._decode (\node_modules\restler\lib\restler.js:173:7)
at IncomingMessage. (\node_modules\restler\lib\restler.js:150:14)
at IncomingMessage.emit (events.js:185:15)
at endReadableNT (_stream_readable.js:1106:12)
at process._tickCallback (internal/process/next_tick.js:178:19)
module.exports = (router) => {
// Protect the marked routes
PROTECTED_ROUTES.forEach(url => {
router.use(url, jwtAuth)
})
// router.use("/collab", jwtAuth)
router.post("/collab/follow", async function (ctx) {
try {
const resp = await followFeed(ctx.request.body.followee_id, ctx.state.user, true)
return collabRepo.follow(ctx.state.user.id, ctx.request.body.followee_type, ctx.request.body.followee_id)
.then(data => {
ctx.body = {
data: data,
feed_data: resp.data
}
})
} catch (error) {
return error
}
}),
} // end of the module
I have removed extra code which is not relevant to this question.
Functions called within route:
Function followFeed
async function followFeed(toFollowId, userObject, follow) {
const args = {
data: {
follow: {
class: "user",
id: toFollowId
}
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Cookie": JWT_COOKIE_NAME + "=" + jwt.sign(userObject, SECRET, {
expiresIn: TOKENTIME
})
}
}
if (follow) {
return rest.post(FEED_API + '/follow', args)
}
return rest.post(FEED_API + '/unfollow', args)
}
Function follow
follow: function(user_id, followee_type, followee_id) {
return db("follower").returning("followee_id").insert({ "user_id": user_id, "followee_id": followee_id, "followee_type": followee_type })
.then(data => {
return data[0]
})
},
Can someone help me and tell me what is wrong with my code?
I am signed in and session has JWT, route exist then why I am getting 404?
What is wrong with code at backend?
In browser console I get:
Error: Uncaught (in promise): Response with status: 404 Not Found for
URL
This is what I get when I print console.log(rest.post(FEED_API + '/follow', args))
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_progressHandler0: undefined,
_promise0: undefined,
_receiver0: undefined,
_settledValue: undefined }
Unhandled rejection Error: Cannot POST http://localhost/activity-feed/api/v1/follow
at Request.<anonymous> (projectpath\node_modules\restling\restling.js:26:21)
Update
Below is activity feed route:
router.post("/v1/follow", function(ctx) {
const user = ctx.state.user
const request = ctx.request.body
return feedRepo.followUserFeed(user.id, request.follow)
.then(result => {
ctx.body = result
})
.catch(error => {
ctx.error = error
})
})
Function called inside this route
followUserFeed: async function(id, feed) {
const userFeed = new GSFlatFeed(LOOKUP.FEEDS.USER, id)
const feedToFollow = new GSFlatFeed(feed.class, feed.id)
const res = await StreamProvider.followFeed(userFeed, feedToFollow)
return res
},
app.js of activity-feed/api
const Koa = require("koa")
const Router = require("koa-router")
const body = require("koa-body")
const cors = require("kcors")
const passport = require("koa-passport")
const logger = require("winston")
var JwtStrategy = require("passport-jwt").Strategy
const CONFIG = require("config")
const SECRET = CONFIG.get("auth.jwt.secret")
const JWT_COOKIE_NAME = CONFIG.get("auth.jwt.cookie.name")
const allRoutes = require("./server/routes/all-routes")
const app = new Koa()
const router = new Router()
const jwtAuth = passport.authenticate(["jwt"], { session: false })
passport.use(new JwtStrategy({
secretOrKey: SECRET,
jwtFromRequest: function(req) {
var token = null
if (req && req.cookies) {
token = req.cookies.get(JWT_COOKIE_NAME)
}
return token
}
},
function(jwt_payload, done) {
done(null, jwt_payload)
}))
router.use("/v1/*", jwtAuth)
allRoutes(router)
app.use(async(ctx, next) => {
try {
await next()
} catch (err) {
logger.error(err)
ctx.throw(err.status || 500, err.message)
}
})
app.use(cors())
app.use(passport.initialize())
app.use(body())
app
.use(router.routes())
.use(router.allowedMethods())
module.exports = app
Any help would be highly appreciated!
While registering the routes you have missed the FEED_API (base url).
PROTECTED_ROUTES.forEach(url => {
router.use(url, jwtAuth)
})
So your url actually looks like http://localhost/collab/follow instead of http://localhost/activity-feed/api/v1/follow
Instead, you should register your routes like,
// Protect the marked routes
module.exports = (router) => {
// Protect the marked routes
PROTECTED_ROUTES.forEach(url => {
router.use(FEED_API + url, jwtAuth)
})
// router.use("/collab", jwtAuth)
router.post(FEED_API + "/collab/follow", async function (ctx) {
Now you can POST to /collab/follow as http://localhost/activity-feed/api/v1/collab/follow

Resources