How to catch email already exists error on firebase 9 - javascript

hey there i have given 2 screenshots and i cannot catch the actual error message like "EMAIL_EXISTS"...i want to show it to the user but when i console log error.message its shows me the 1st screenshot..how can i achieve that with firebase 9...im using async await..heres my code
try {
setLoading(true);
const req = await createUserWithEmailAndPassword(auth, email, password);
console.log(req)
setLoading(false);
dispatch({type: "SIGNUP", payload: req.user})
dispatch({
type: "visible",
timer: 4000,
message: "Signed Up Successfully! Login Now.",
color: "SUCCESS",
});
dispatch({ type: "login" });
return;
} catch (error) {
console.log(error.message)
dispatch({
type: "visible",
timer: 3000,
message: "Failed to Signup! Please try again",
color: "ERROR",
});
setLoading(false);
return;
}

Related

SyntaxError: Unexpected token " in JSON at position 0 at JSON.parse

I am not able to clearly Identify the bug, data is send in JSON Format still it is showing unusual error
Forgot Password Route
exports.forgotPassword = catchAsyncErrors(async (req, res, next) => {
const user = await User.findOne({ email: req.body.email });
if (!user) {
return next(new ErrorHandler("User not found", 404));
}
// Get ResetPassword Token
const resetToken = user.getResetPasswordToken();
await user.save({ validateBeforeSave: false });
const resetPasswordUrl = `${req.protocol}://${req.get(
"host"
)}/password/reset/${resetToken}`;
const message = `Your password reset token is :- \n\n ${resetPasswordUrl} \n\nIf you have not requested this email then, please ignore it.`;
try {
await sendEmail({
email: JSON.stringify(user.email),
subject: `Ecommerce Password Recovery`,
message
});
res.status(200).json({
success: true,
message: `Email sent to ${user.email} successfully`
});
} catch (error) {
user.resetPasswordToken = undefined;
user.resetPasswordExpire = undefined;
await user.save({ validateBeforeSave: false });
return next(new ErrorHandler(error.message, 500));
}
});
forgotPassword Action.js
export const forgotPassword = (email) => async(dispatch)=>{
try{
dispatch({type: FORGOT_PASSWORD_REQUEST});
const config = {headers : {"Content-Type": "application/json"}};
const {data} = await axios.post(
"/api/v1/password/forgot",
email,
config
);
dispatch({
type: FORGOT_PASSWORD_SUCCESS,
payload : data.message,
})
}catch(error) {
dispatch({
type: FORGOT_PASSWORD_FAIL,
payload: error.response.data.message,
});
}
}
As mentioned in some answers online available I have made few changes but Error is still their,
In Action.js I have written content type as "application/json".
in forgotPassword Route while sending email to function, I have used a method JSON.stringify.
Your axios.post statement sends a request whose body is an email address (i.e., plain text), but the Content-Type: application/json wrongly claims it to be JSON. That leads to the observed error.
Correct would be
const data = await axios.post(
"/api/v1/password/forgot",
{email},
config
);
(Note the absence of braces around data.)

How to pass jwt token from controller to router using NodeJS

Hello developers the question is simple,
I have generated a jwt token in my Login function using the jwt.sign(), and I have Model/Controller/Router Architecture,
so the question is : How can I pass the generated token from the Login controller function to the router.
I've tried many times to assign the token to a const variable to send it throw an object and send it to the router files, but when I go out from the jwt.sign() function it shows me that is undefined.
PS : I'am just using NodeJS and fastify in the backend and send http request with Postman am not using any framework in the front-end
There is some code than can help you to understand my situation :
UserRouter.js: (Login route) :
{
method: "POST",
url: "/api/login",
handler: (req, res) => {
UserController.login(req.body.email, req.body.password)
.then(result => {
//res.header("Access-Control-Allow-Origin", URL);
if (result.statusCode == 200) {
res.send({
status: 200,
error: null,
response: result.Message
//token: result.token
});
} else if (result.statusCode == 401) {
res.send(
JSON.stringify({
status: 401,
error: null,
response: result.Message
})
);
}
})
.catch(err => {
//res.header("Access-Control-Allow-Origin", URL);
res.send(JSON.stringify({ status: 300, error: err, response: null }));
});
}
}
User Controller :
exports.login = async (user_email, password) => {
try {
console.log("Login into API");
const email = user_email.toLowerCase();
const user = await User.findOne({ email });
if (user) {
console.log(" Hashed Passwd ", user.password);
console.log("User Passwd", password);
let result = await bcrypt.compareSync(password, user.password);
if (result) {
// Tryed also with const = await jwt.sign()
jwt.sign({ user }, "secretkey", (err, token) => {
if (err) throw err;
console.log("The Token is", token);
});
return {
Message: "Login success",
statusCode: 200
//token: token
};
} else {
return { Message: "Incorrect password", statusCode: 401 };
}
} else {
return { Message: "ERROR" };
}
} catch (err) {
throw boom.boomify(err);
}
};
if you look at the package readme, you'll find jwt.sign returns nothing when a callback is provided.
So what you should do is:
const token = jwt.sign({ user }, "secretkey");
That would make the library work synchronously and return the token.

Error using Axios, but correct response in Postman

I'm having a problem using Axios with my backend. It's probably a very simple fix as I'm new to this.
Postman: The correct response is received for both valid and invalid credentials.
Axios: The correct response is received for valid crendentials, but the axios method's catch block is run when invalid credentials are entered.
authController.js:
exports.login = (req, res, next) => {
const email = req.body.email;
const pass = req.body.password;
let loadedUser;
User.findOne({ where: { email: email } })
.then(user => {
if(!user) {
const error = new Error('Incorrect username or password');
error.statusCode = 401;
throw error;
} else {
loadedUser = user;
return bcrypt.compare(pass, user.password);
}
})
.then(isEqual => {
if(!isEqual) {
const error = new Error('Incorrect username or password');
error.statusCode = 401;
throw error;
} else {
const token = jwt.sign(
{
email: loadedUser.email,
userId: loadedUser.id
},
process.env.JWT_SECRET,
{ expiresIn: '1hr' }
);
res.status(200).json({ token: token, userId: loadedUser.id });
}
})
.catch(err => {
if (!err.statusCode)
err.statusCode = 500;
next(err);
});
};
The error handler in app.js. It seems to log the error correctly when incorrect credentials are entered, even with axios:
app.use((error, req, res, next) => {
const status = error.statusCode || 500;
const message = error.message;
const data = error.data || 'No Data';
console.log(status, message, data);
res.status(status).json({message: message, data: data});
});
But then the axios catch block runs, so instead of receiving the json message, I get the following error
login(email, password) {
const headers = {
'Content-Type': 'application/json'
};
const data = JSON.stringify({
email: email,
password: password
});
axios.post('http://127.0.0.1:8080/auth/login', data, { headers })
.then(res => console.log(res))
.catch(err => console.log(err));
}
The error in the console for invalid credentials:
Clicking the link highlighted opens a new page stating: "Cannot GET /auth/login", but I'm obviously making a post request, & I've added post to the form (just in case)
Any ideas what I could be missing?
Thanks
Actually your code works fine but Axios will reject the promise of the call if you have the status 401. If you have a status between 200 to 300 it will resolve the promise.
There two ways to deal with this.
Check status in the catch block.
axios.post('http://127.0.0.1:8080/auth/login', data, {
headers
})
.then(res => console.log(res))
.catch(err => {
if (err.response.status === 401) {
//Auth failed
//Call reentry function
return;
}
return console.log(err)
});
or change the validateStatus option;
axios.post('http://127.0.0.1:8080/auth/login', data, {
headers,
validateStatus: function (status) {
return status >= 200 && status < 300 || (status === 401);
},
})
.then(res => console.log(res))
.catch(err => return console.log(err));

bcrypt.compare cannot set response headers in nextjs

I can't seem to get the correct response headers when my code enters bcrypt.compare. I thought it was a cors issue at first but I still get the correct response if I entered the wrong and "user does not exist" is displayed.
Here's my api server side code in express
router.post("/api/signIn", (req, res) => {
const { user, password } = req.body;
const queryString = "SELECT * FROM users WHERE user_id = ?";
db.query(queryString, [user])
.then(result => {
if (result.length > 0) {
const hash = result[0].password;
//here bcrypt.compare works server side or with cURL but won't set the response headers in the browser
bcrypt
.compare(password, hash)
.then(same => {
if (same === true) {
console.log("correct password");
res.status(200).json({
code: 200,
message: "correct password"
});
} else {
res.status(401).json({
code: 401,
message: "incorrect password"
});
}
})
.catch(err => console.log(err));
} else {
//this one works though and i can get the response in the browser so it can't be a cors issue
console.log("user does not exist");
res.status(200).json({
code: 401,
message: "User does not exist"
});
}
})
.catch(err => {
console.log("error" + err.message);
});
});
and this is the test function i use in react
const signIn = () => {
fetch("http://localhost:5000/api/signIn", {
method: "POST",
body: JSON.stringify({
user: userName,
password: password
}),
headers: {
"Content-Type": "application/json"
},
})
.then(res => res.json())
.then(response => alert(response.code + response.message))
.catch(err => alert(err));
};
so if i entered the wrong username that is not in the database, the alert function would show (code401User does not exist) but if i entered the correct user bcrypt.compare() doesn't seem to set the response for both correct and incorrect passwords and i would get (TypeError: failed to fetch). testing the api in cURL works though.
Got it, I forgot to put event.preventDefault() on the fetch function.

jsonResponse from api success but doesn't work

I'm using .then(jsonResponse => after a fetch function, i stringfied it and logged it into the console to see if the api returns the confirmation key as "success", even though it returns as success the statement:
if (jsonResponse.confirmation === "success") {
this.props.navigation.navigate("main");
}
Is not working, it doesn't navigate to the 'main' screen, does anyone know how to fix this? I've been searching the forum for an answer but couldn't find, here's how the code is organized:
register() {
fetch(config.baseUrl + "signup", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(this.state.credenciais)
}) //all of this works, since it connects to the api and registers the user with its credentials
.then(response => response.json())
.then(jsonResponse => {
console.log(JSON.stringify(jsonResponse)) //this returns as success
console.log(response) // returns as undefined
if (jsonResponse.confirmation === "success") {
this.props.navigation.navigate("main");
} else {
throw new Error({
message: "Algo ocorreu de errado, por favor tente novamente"
});
}
})
.catch(err => {
console.log(err.message);
});
}
I commented the parts where I couldn't figure it out, and in the api I have as the route:
router.post("/signup", function(req, res) {
console.log(req.body);
turbo
.createUser(req.body)
.then(data => {
res.json({
confirmation: "success",
data: data
});
})
.catch(err => {
res.json({
confirmation: "fail",
message: err.message
});
});
});
As you can see, I have confirmation: success if everything goes right, the code above works and registers the user but doesn't navigate to the 'main' screen, does anyone know what is wrong with my code?
Edit: As asked below here's the console.log(JSON.stringify(jsonResponse))
{"confirmation":"success","data":{"firstName":"","lastName":"","email":"testestes#aol.com","username":"","bio":"","image":"","timestamp":"2018-11-03T16:16:00.855Z","stripe":{},"schema":"user","id":"5bddc9c050edeb001431cb2e"}}
Also, the register() is called in a TouchableOpacity:
<TouchableOpacity
onPress={() => {
this.register();
}}
>

Categories