I am implementing a login feature, so when the user enter wrong credentials, I am passing an error 'Wrong Credentials' to the frontend, but at frontend I receive a different error message.
this is the relevant backend code
exports.loginUser = async (req, res) => {
try{
const loggedinUser = await userService.loginUser(res, req.body);
if(loggedinUser.error){
throw new Error(loggedinUser.error); //loggedinUser.error is 'Wrong credentials'
}
const tokenPayload = {
userName: loggedinUser[0].name,
email: loggedinUser[0].email
}
const token = jwt.sign(tokenPayload, keys.JWT.TOKEN_SECRET, {expiresIn: '60m'} );
const tokenData = {
token: token,
name: tokenPayload.userName,
email: tokenPayload.email
}
const redirectURL = url.format({
pathname: '/dashboard/buzz',
query: tokenData
});
res.send({redirectTo: redirectURL});
} catch(err){
console.log(err); //prints wrong credentials
res.status(400).json(err);
}
}
this is the relevant frontend code
const loginHandler = ( event ) => {
event.preventDefault();
setShowValidationMessage(true);
const loginDetails = {
email: loginForm.email.value,
password: loginForm.password.value
}
if(formIsValid){
axios.post('http://localhost:5000/login', loginDetails)
.then(res=>setRedirectURL(res.data.redirectTo))
.catch(err=>{
console.log(err.message);// prints Request failed with status code 400
});
}
}
Related
This is the error that I get:
"You have created a new client application that use…i/web/guides/gis-migration) for more information."
here are my codes on server, the statement inside console.log doesnt even show:
static async googleLogin(req, res, next) {
try {
console.log("masuk google login server")
const { id_token } = req.body
const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID)
const ticket = await client.verifyIdToken({
idToken: id_token,
audience: process.env.GOOGLE_CLIENT_ID
});
const payload = ticket.getPayload()
const email = payload.email
let password = email.toString().split('#')
password = password[0]
let user = await User.findOne({ where: { email } })
if (!user) {
let newUser = { email, password }
let createUser = await User.create(newUser)
const payload = {
id: createUser.id,
email: createUser.email
}
const access_token = generateToken(payload)
return res.status(201).json({ access_token })
} else {
const payload = {
id: user.id,
email: user.email
}
const access_token = generateToken(payload)
return res.status(200).json({ access_token })
}
} catch (err) {
console.log(err)
return next(err)
}
}
the console.log in my client also doesnt show
function onSignIn(googleUser) {
console.log("masuk client oauth")
$.ajax({
method: "POST",
url: `${baseUrl}/users/google-login`,
data: {
id_token: googleUser.getAuthResponse().id_token
}
})
.done((response) => {
console.log(response, "client response")
localStorage.setItem("access_token", response.access_token)
checkLocalStorage();
})
.fail((err) => {
console.log(err, "error client");
})
.always(() => {
authentication()
})
}
i tried deleting cache and run my app again, recreate a new project on google api (which genereated new ID). they didnt work
i cannot sign in to my app using existing google account. it loads when i clicked and asked me to wait a moment but then nothing happened.
my script.js
function onSignIn(googleUser) {
$.ajax({
url: `${baseUrl}/users/googlelogin`,
method: "POST",
data: {
access_token: googleUser.getAuthResponse().id_token,
googleToken: id_token
}
})
.done((response) => {
console.log(response, "ini response dr client")
localStorage.setItem("access_token", response.access_token)
authentication()
})
.fail((err) => {
console.log(err);
swal(
"Oops!", xhr.responseJSON.error[0], "error")
console.log(xhr.responseJSON.error[0])
})
}
my controller file:
static async googleLogin(req, res, next) {
try {
console.log("masuk google login")
const { id_token } = req.body
const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID)
const ticket = await client.verifyIdToken({
idToken: id_token,
audience: process.env.GOOGLE_CLIENT_ID
});
const payload = ticket.getPayload()
const email = payload.email
let password = email.toString().split('#')
password = password[0]
let user = await User.findOne({ where: { email } })
if (!user) {
let newUser = { email, password }
let createUser = await User.create(newUser)
const payload = {
id: createUser.id,
email: createUser.email
}
const access_token = generateToken(payload)
return res.status(201).json({ access_token })
} else {
const payload = {
id: user.id,
email: user.email
}
const access_token = generateToken(payload)
return res.status(200).json({ access_token })
}
} catch (err) {
console.log(err)
return next(err)
}
}
here are the error on console:
GET http://localhost:3000/todos 500 (Internal Server Error)
Uncaught {error: 'idpiframe_initialization_failed', details: 'You have created a new client application that use…i/web/guides/gis-migration) for more information.'}
i run my app on http://localhost:8080/client/
Ok So i am trying to display my backend error messages in the front end, so I have it setup to send the response with the error code and a message and then in my action I am setting a state in my React component which I will then use to display the error message, so far I can get to display the error code but that is no use to most users so I would like to access the message I send with the code! So I want it to say user already exists or passwords do not match rather than Error: Request failed with status code 400
my action
export const signup = (form, router, setError) => async (dispatch) => {
const changeError = (error) => {
setError(error);
};
try {
const { data } = await api.signup(form);
dispatch({ type: AUTH, data });
router.push("/");
} catch (error) {
console.log(error);
changeError(error);
}
};
my node signup
export const signup = async (req, res) => {
const { email, password, confirmPassword, firstName, lastName } = req.body;
try {
const existingUser = await user.findOne({ email });
if (existingUser)
return res.status(400).json({ message: "User already exists." });
if (password != confirmPassword)
return res.status(400).json({ message: "Passwords do not match." });
const hashedPassword = await bcrypt.hash(password, 12);
const result = await user.create({
email,
password: hashedPassword,
name: `${firstName} ${lastName}`,
});
const token = jwt.sign(
{ email: result.email, id: result._id },
process.env.JWT_KEY,
{
expiresIn: "1h",
}
);
res.status(200).json({ result, token });
} catch (error) {
res.status(500).json({ message: "Something went wrong." });
}
};
After little search on Google, if you are using Axios as your api, the path to the error message is:
error.response.data.message
else, have you tried somthing like this?
error.data.message
or
error.message
as Guy said, slightly before I found the answer myself I set the error to error.response.data.message
so now I can set my error in the front end to display the message
and yea sorry was using axios, I'll know better for next time to mention that!
export const signup = (form, router, setError) => async (dispatch) => {
const changeError = (error) => {
setError(error);
};
try {
const { data } = await api.signup(form);
dispatch({ type: AUTH, data });
router.push("/");
} catch (error) {
console.log(error);
changeError(error.response.data.message);
}
};
I'm developing a server in Node JS where there are two routes - Login and Signup.
Whenever I do signup, I am getting response as success and the data is being stored in MongoDB database successfully and then I'm getting [nodemon] app crashed - waiting for file changes before starting... in my console.
Note:- "The problem is in signup only not in login".
postSignup() will be called when a user requests for signup which is validated according to schema and inserted in database.
I'm providing the code related to signup.
signup.js
const { User } = require("../../models");
const createError = require("http-errors");
const postSignup = (req, res, next) => {
//validation
const validation = User.validate(req.body);
if (validation.error) {
const error = new Error(validation.error.message);
error.statusCode = 400;
return next(error);
}
//check Existence
const user = new User(req.body);
user
.checkExistence()
.then((result) => {
if (result.check) {
const error = new Error(result.message);
error.statusCode = 409;
return next(error);
}
user.save((err) => {
if (err) {
console.log(err);
return next(createError(500));
}
res.status(201).json({
message: "User has been Successfully Created",
});
});
})
.catch((err) => {
next(createError(500));
});
};
module.exports = {
postSignup,
};
User.js
const { dbCon } = require("../configuration");
const { userValidator, logSchema } = require("../validator");
const { hashSync, compareSync } = require("bcryptjs");
class User {
constructor(userData) {
this.userData = { ...userData };
}
save(cb) {
dbCon("users", (db) => {
try {
const hashPass = hashSync(this.userData["password"], 12);
this.userData["password"] = hashPass;
db.insertOne(this.userData);
cb();
} catch (err) {
cb(err);
}
});
}
checkExistence() {
return new Promise((resolve, reject) => {
dbCon("users", async (db) => {
try {
const user = await db.findOne({
$or: [
{ username: this.userData["username"] },
{ email: this.userData["email"] },
],
});
if (!user) {
resolve({
check: false,
});
} else if (this.userData["username"] === user.username) {
resolve({
check: true,
message: "username already exists",
});
} else if (this.userData["email"] === user.email) {
resolve({
check: true,
message: "email already exists",
});
}
} catch (err) {
reject(err);
}
});
});
}
static validate(userData) {
//console.log(userData);
return userValidator.validate(userData);
}
module.exports = User;
userValidator.js
const Joi = require("#hapi/joi");
const schema = Joi.object({
username: Joi.string().alphanum().required().min(3).max(15),
email: Joi.string().email().required(),
password: Joi.string()
.pattern(
new RegExp(
"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{8,}$"
)
)
.message(
"Password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters"
)
.required(),
first_name: Joi.string().required(),
last_name: Joi.string().required(),
});
module.exports = {
schema
};
I faced the same issue. I don't know what was the issue but I tried to change node version in mongo db connect and then used the new connect URL.
If it still doesn't work, then try to create new cluster and connect it again with new cluster.
it seems that the create method does not return any promise that then can handle
I tried different things but nothing worked
this is my routes file
const express = require("express")
const router = express.Router();
const controller = require("./controller")
router.post("/signup", controller.create);
module.exports = router;
and this is my model file
const mongoose = require('mongoose');
const User = new mongoose.Schema(
{
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
picture: {
type: String
},
password: {
type: String,
select: false
},
email: {
required: true,
type: String,
unique: true
}
},
{
timestamps: true
}
);
User.index({
firstName: 'text',
lastName: 'text',
});
module.exports = mongoose.model('User', User);
and this is the controller file
const User = require('./model');
const { hash, compareHash } = require('../lib/util');
const { createToken, findUserByToken } = require('../lib/auth');
const cookieIsSecure = process.env.ENVIRONMENT === 'production';
exports.create = async (req, res) => {
const password = await hash(req.body.password);
const rawUser = {
...req.body,
password,
};
User.create(rawUser)
.then(async user => {
return user.save();
})
.then(async user => {
const newUser = user.toObject();
res.send(newUser);
})
.catch(err => {
if (err.code === 11000) {
res.status(400).send({ message: 'A user with this email address has already registered.' });
return;
}
res.status(500).send({ message: 'An unexpected error occurred' });
});
};
it always return the 500 error "an unexpected error occurred"
which is not really specific. and i do not know what is the problem exactly. but I am sure it has something to do with the model.create() it does not return any promise.
Here you are mixing methods. create doesn't want save in it as it's implicit:
https://mongoosejs.com/docs/api.html#model_Model.create
Please try this, I've refactored your code a bit and added much easier to read and use try/catch:
const rawUser = new User({ ...req.body, password});
try {
await rawUser.save();
res.status(201).send(newUser);
} catch(err) {
if (err.code === 11000) return res.status(400).send({ message: 'A user with this email address has already registered.' });
res.status(500).send({ message: 'An unexpected error occurred' });
}
You need to use async/await like this:
exports.create = async (req, res) => {
try {
const password = await hash(req.body.password);
const rawUser = {
...req.body,
password
};
const user = await User.create(rawUser);
const newUser = user.toObject();
res.send(newUser);
} catch (err) {
console.log("ERROR: ", err);
if (err.code === 11000) {
return res.status(400).send({
message: "A user with this email address has already registered."
});
}
res.status(500).send({ message: "An unexpected error occurred" });
}
};