my homepage wont render using my google oauth - javascript

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

Related

i cannot sign in to my app using existing google account

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/

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. app crushed

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();
})
}

fetching post request don't log success if the request succeed

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.

Issue in sending error message from backend(nodejs) to frontend(reactjs)

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
});
}
}

How to verify email by 6-digit-code in Flutter, Node JS and MongoDB?

What I am trying to achieve is the following:
I have got a register screen in which the user enters his email and a password. When "register" ist pressed, I want the user to receive an email with a random 6-digit-code which allows him to enter this code on the next page which is the verification screen and with that verify the email.
Everything is set up, but I can only find ways via a generated verification link.
The way I would like to go is:
User enters credentials (email, password)
When pressed on "register" this data is saved to the database under the users collection with an ID and an email with the code is sent.
When this is done, the code can be entered and is somehow compared to the code that is saved somewhere in the database?? Because just sending the generated code to the next screen and store it in a class variable wouldn't be the best approach of achieving this I guess.
After success the users "verified" field is set to true in the database.
I don't really know the best way of programming this.
Please do not bother me for the naming of the routes ;) It's just like that for the moment for simplicity. Because of the same reason I only send response codes of 400 when something went wrong.
Flutter (registration screen)
child: RawMaterialButton(
onPressed: () async {
setState(() => isLoading = true);
if (email.length < 6) setState(() => isLoading = false);
else if (password.length < 6) setState(() => isLoading = false);
else {
var registerRes = await _auth.registerWithEmailAndPassword(email, password);
if (registerRes == 200) {
var code = randomNumeric(6);
var sendRes = await _auth.sendCode(email, code);
if (sendRes == 200) {
Routes.sailor.navigate(
'/confirmation',
params: {
'email': email,
'password': password,
'code': code
}
);
} else {
setState(() => isLoading = false);
}
} else {
setState(() => isLoading = false);
}
}
},
...
)
Flutter (Auth class)
import 'package:http/http.dart' as http;
import 'dart:convert';
class AuthService {
Future<String> loginWithEmailAndPassword(String email, String password) async {
Map data = {
'email': email,
'password': password
};
String body = json.encode(data);
var res = await http.post(
'http://10.0.2.2:3000/api/users/login',
headers: { 'Content-Type' : 'application/json'},
body: body
);
if (res.statusCode == 200) return res.body;
return null;
}
Future<int> registerWithEmailAndPassword(String email, String password) async {
Map data = {
'email' : email,
'password': password
};
String body = json.encode(data);
var res = await http.post(
'http://10.0.2.2:3000/api/users/register',
headers: { 'Content-Type' : 'application/json'},
body: body
);
return res.statusCode;
}
Future<int> sendCode(String email, String code) async {
Map data = {
'email' : email,
'code': code
};
String body = json.encode(data);
var res = await http.post(
'http://10.0.2.2:3000/api/users/send',
headers: { 'Content-Type' : 'application/json'},
body: body
);
return res.statusCode;
}
}
Node JS (auth.js)
const router = require('express').Router();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { registerValidation, loginValidation } = require('../validation');
const User = require('../models/User');
const nodemailer = require('nodemailer');
router.post('/register', async (req, res) => {
const { error } = registerValidation(req.body);
if (error) return res.sendStatus(400);
const emailExists = await User.findOne({ email : req.body.email });
if (emailExists) return res.sendStatus(400);
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
const user = new User({
email : req.body.email,
password : hashedPassword
});
try {
const savedUser = await user.save();
} catch(err) {
res.sendStatus(400);
}
});
router.post('/send', async (req, res) => {
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_ADDRESS,
pass: process.env.EMAIL_PASSWORD
},
tls: {
rejectUnauthorized: false
}
});
const mailOptions = {
from: '"coderave" <ccoderave#gmail.com>',
to: req.body.email,
subject: 'Bestätigungscode',
text: req.body.code
};
transporter.sendMail(mailOptions, function (err, info) {
if (err) res.sendStatus(400);
else res.sendStatus(200);
});
});
module.exports = router;
Kindly use the NPM Package (two-step-auth)
Use this package in your server index.js and create a route for it, and directly pass in the variables and you can do the rest,
In your app get the data from the form and pass it to your server and then to the package and it will return you an OTP to work with,
Kindly check the full procedures with the example here
Usage
const {Auth} = require('two-step-auth');
async function login(emailId){
const res = await Auth(emailId);
// You can follw the above approach, But we recommend you to follow the one below, as the mails will be treated as important
const res = await Auth(emailId, "Company Name");
console.log(res);
console.log(res.mail);
console.log(res.OTP);
console.log(res.success);
}
const app = express();
app.get('./auth/mailId/CompanyName', async(req, res)=>{
const {emailId} = req.params;
const data = login(emailId);
})
Output
This will help you a lot taking care of the process of verification under the HOOD.

Categories