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/
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'm getting this error -> " Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client ".I tried to apply JSON Web Token(JWT) in my app and every time it's logging me out from app. I can't understand is it server-side error or client-side. Pls check my code
Here is the code:
// verifyJWT function
function verifyJWT(req, res, next){
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send({ message: 'Your access is unauthorized to BookPile' });
}
const token = authHeader.split(' ')[1];
jwt.verify(token, process.env.ACCESS_TOKEN_SECRECT, (err, decoded) => {
if (err) {
return res.status(403).send({ message: 'BookPile authority forbid your access' })
}
console.log('decoded', decoded);
req.decoded = decoded;
next();
})
console.log('inside verify function', authHeader);
next();
}
//API
// GET API for get token
app.post('/login' , async(req,res) => {
const user = req.body;
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn:'1d'
});
res.send({accessToken});
})
// GET API for load items of logged in user
app.get('/my_items' , verifyJWT , async(req,res) => {
// const authHeader = req.headers.authorization;
// console.log(authHeader);
const email = req.query.email;
const criteria = {email:email};
const cursor = await booksCollection.find(criteria);
const books = await cursor.toArray();
res.send(books);
})
//Client side
const getMyBooks = async () => {
const email = user.email;
const url = `http://localhost:5000/my_items?email=${email}`;
try {
const { data } = await axios.get(url, {
headers: {
authorization: `Bearer ${localStorage.getItem('accessToken')}`
}
})
setMyBooks(data);
}
catch (error) {
console.log((error.message));
if (error.response.status === 401 || error.response.status === 403) {
signOut(auth);
// navigate('/login');
}
}
}
getMyBooks();
}, [user])
//Client side login
const handleForm = async event => {
event.preventDefault();
const email = emailRef.current.value;
const password = passRef.current.value;
await signInWithEmailAndPassword(email, password);
const { data } = await axios.post('http://localhost:5000/login', { email });
// console.log(data);
localStorage.setItem('accessToken', data.accessToken);
navigate(from, { replace: true });
}
Since the verify function is executed asynchronously, the last next() call will be called immediately before the verification is done. Therefore you'll have to call either res.send() or next() inside the callback
function verifyJWT(req, res, next){
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send({ message: 'Your access is unauthorized to BookPile' });
}
const token = authHeader.split(' ')[1];
jwt.verify(token, process.env.ACCESS_TOKEN_SECRECT, (err, decoded) => {
if (err) {
return res.status(403).send({ message: 'BookPile authority forbid your access' })
}
console.log('decoded', decoded);
req.decoded = decoded;
next();
})
}
I'm trying to sign up new user, when I'm sending the post request the server register the user well, and I can see them in my data base, but I can't see the success log in my console (I can catch the error and it logs in my console).
Server side code:
var express = require("express");
const { Error } = require("mongoose");
const passport = require("passport");
var router = express.Router();
const User = require("../models/user");
const catchAsync = require("../utils/catchAsync");
router.post(
"/register",
catchAsync(async (req, res) => {
try {
const { email, username, password } = req.body;
const user = new User({ email, username });
await User.register(user, password);
} catch (e) {
throw new Error("Error signing up");
}
})
);
module.exports = router;
Client side code:
const sumbitHandler = async (data) => {
const { username, email, password } = data;
try {
await fetch("http://localhost:9000/users/register", {
method: "POST",
body: JSON.stringify({
username,
email,
password,
}),
headers: {
"Content-Type": "application/json",
},
})
.then((res) => {
if (res && !res.ok) {
throw new Error("ERROR");
}
console.log("Success");
})
.catch((e) => {
console.log(e.message);
});
} catch (e) {
console.log(e.message);
}
};
You are mixing the async/await style and the older .then() Promise-style. Choose one or the other (I strongly recommend async/await)
You are not transforming fetch's response into JSON, leaving it in Promise state.
Your server is never responding to the client! You need to add res.end(), res.send(), res.json() or something.
const sumbitHandler = async (data) => {
const { username, email, password } = data;
try {
const response = await fetch("http://localhost:9000/users/register", {...});
const serverResponse = await response.text(); // or response.json() if your servers sends JSON back
console.log("Success! serverResponse is = ", serverResponse ); // "Done!"
} catch (e) {
console.log(e.message);
}
};
Server :
...
await User.register(user, password);
res.send("Done!"); // or res.json({ status : "ok" }); etc.
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
});
}
}
Can anyone explain to me why I'm getting this error? Here's my code where I'm getting this error. I assume it's becuase of the imports/exports in my code?
emailController
const User = require("../models/User")
const jwt = require("jsonwebtoken")
const { transporter, getResetPasswordURL, resetPasswordTemplate } = require("../utils/mailer")
module.exports = {
createOneTimeTokenAndSendMail: async (req, res) => {
const email = req.params.email
try {
const user = await User.findOne({ email })
if (!user) {
return res.status(404).json({ error: "No user with that email "})
}
const hashedPassword = user.password
const createdAt = user.createdAt
const userId = user._id
const secret = hashedPassword + "-" + createdAt
const token = jwt.sign({ userId }, secret, {
expiresIn: 3600
})
const url = getResetPasswordURL(user, token)
const emailTemplate = resetPasswordTemplate(user, url)
const sendEmail = () => {
transporter.sendMail(emailTemplate, (err, info) => {
if (err) {
res.status(500).json("Error sending email")
}
console.log("email sent", info.response)
})
}
sendEmail()
} catch (error) {
res.status(500).json({ error })
}
}
}
mailer
const User = require("../models/User")
const jwt = require("jsonwebtoken")
const {
transporter,
getResetPasswordURL,
resetPasswordTemplate
} = require("../utils/mailer")
module.exports = {
createOneTimeTokenAndSendMail: async (req, res) => {
const email = req.params.email
try {
const user = await User.findOne({ email })
if (!user) {
return res.status(404).json({ error: "No user with that email " })
}
const hashedPassword = user.getPassword
const createdAt = user.createdAt
const userId = user._id
const secret = hashedPassword + "-" + createdAt
const token = jwt.sign({ userId }, secret, {
expiresIn: 3600
})
const url = getResetPasswordURL(user, token)
const emailTemplate = resetPasswordTemplate(user, url)
const sendEmail = () => {
transporter.sendMail(emailTemplate, (err, info) => {
if (err) {
res.status(500).json("Error sending email")
}
console.log("email sent", info.response)
})
}
sendEmail()
} catch (error) {
res.status(500).json({ error })
}
}
}
This is the route which is throwing the above error:
router.post("/reset-password/:email", emailController.createOneTimeTokenAndSendMail)
I have been dealing with errors like these constantly, so I'd like to clear my doubts once and for all.