What is the best way to use Google 0Auth - reactjs

I'm trying to use Google OAuth in my App, on the Log In page and the Sign Up page, I'm looking for the best way and the easiest! I tried Passport Js, but I'm stuck right now.
I'm using Mongoose right now and I'm signing up and in users perfectly, but now i want to add a feature where the user can sign in using his google account, I'm looking for a way where the app can get the Email the user is using for his google account and then look if the email is already registered if so redirect him to the home page and if not sign his email up, save it to database, and then redirect to the home page.
This is how my Auth.js looks like
//REGISTER
router.post("/register", async (req, res) => {
try {
//generate new password
const salt = await bcrypt.genSalt(10);
const hashedPass = await bcrypt.hash(req.body.password, salt);
//create new user
const newUser = new User ({
username: req.body.username,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: hashedPass,
repeatPassword: hashedPass,
birthday: req.body.birthday,
});
//save user and respond
const user = await newUser.save();
res.status(200).json(user);
} catch (err) {
res.status(500).json(err);
}
});
//LOGIN
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
// if(!user) return res.status(400).json("Wrong credentials!");
!user && res.status(400).json("Wrong credentials!");
const validated = await bcrypt.compare(req.body.password, user.password);
// if(!validated) return res.status(400).json("Wrong credentials!");
!validated && res.status(400).json("Wrong credentials!");
const { password, ...others } = user._doc;
return res.status(200).json(others);
} catch (err) {
return res.status(500).json(err);
}
});
PassportJs configuration I used: but didn't work
passport.use(
new GoogleStrategy(
{
clientID: "MyClientId",
clientSecret: "Myclientsecret",
callbackURL: "/api/auth/google/callback",
},
function (accessToken, refreshToken, profile, done) {
User.find(
{
social: profile.provider,
social_id: profile.id,
},
(err, user) => {
if (user.length === 0) {
const user = new User({
email: profile.email,
username: profile.displayName,
profilePic: profile.photos[0],
social: profile.provider,
social_id: profile.id,
});
const userModel = new User(data);
userModel.save();
done(null, profile);
}
if (err) {
return done(err);
}
},
);
return done(null, profile);
}
)
);
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
router.get("/login/success", (req, res) => {
if (req.user) {
res.status(200).json({
success: true,
message: "successfull",
user: req.user,
// cookies: req.cookies
});
}
});
router.get("/login/failed", (req, res) => {
res.status(401).json({
success: false,
message: "failure",
});
});
router.get("/google", passport.authenticate("google", { scope: ["profile"] }));
router.get(
"/google/callback",
passport.authenticate("google", {
successRedirect: CLIENT_URL,
failureRedirect: "/login/failed",
})
);

Related

How to retrieve user profile to the frontend | PassportJs

I'm trying to log in a user using Passport Js (Google Auth), I configured Passport Js and i'm getting the user profile in my console, but I didn't know how to show the user profile in frontend, the configure for PassportJs goes like:
passport.use(
new GoogleStrategy(
{
clientID: "",
clientSecret: "",
callbackURL: "/auth/google/callback",
scope: ["profile", "email"],
},
async (accessToken, refreshToken, profile, done) => {
// find current user in UserModel
const currentUser = await User.findOne({
googleId: profile.id
});
// create new user if the database doesn't have this user
if (!currentUser) {
const newUser = await new User({
googleId: profile.id,
email: profile.emails[0].value,
displayName: profile.displayName,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
profilePic: profile.photos[0].value,
}).save();
if (newUser) {
done(null, newUser);
}
}
console.log("CURRNT USER: ", currentUser);
done(null, currentUser);
}
)
);
// serialize the user.id to save in the cookie session
// so the browser will remember the user when login
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id)
.then(user => {
done(null, user);
})
.catch(e => {
done(new Error("Failed to deserialize an user"));
});
});
And in the Auth.js route:
// when login is successful, retrieve user info
router.get("/login/success", (req, res) => {
if (req.user) {
res.status(200).json({
error: false,
message: "succesfull",
user: req.user,
cookies: req.cookies
});
} else {
res.status(403).json({ error: true, message: "Not Authorized" });
}
});
// auth with google
router.get("/google", passport.authenticate("google", ["profile", "email"]))
// redirect to home page after successfully login via google
router.get(
"/auth/google/callback",
passport.authenticate("google", {
successRedirect: "http://localhost:3000/",
failureRedirect: "/login/failed"
})
);
I'm using Context to let the app knows if the user is logged in or not.
**Login.jsx: Normal Logging Using express and Mongodb **
const handleSubmit = async (e) => {
e.preventDefault();
dispatch({ type: "LOGIN_START" });
try {
const res = await axios.post("/login", {
email: userRef.current.value,
password: passwordRef.current.value,
});
dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
} catch (err) {
dispatch({ type: "LOGIN_FAILURE" });
setError(true)
}
};
//Now I tried this code to log in a user using Google Auth but it didn't work
useEffect(() => {
fetch(`http://localhost:4000/login/success`, {
method: 'GET',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true,
},
})
dispatch({ type: "LOGIN_START" })
.then((response) => {
if (response.status === 200) return response.json();
throw new Error('failed to authenticate user');
})
.then((responseJson) => {
dispatch({ type: "LOGIN_SUCCESS", payload: responseJson.data });
})
.catch((error) => {
dispatch({ type: "LOGIN_FAILURE" });
console.error("Failed to authenticate user", error)
});
}, []);
const google = () => {
window.open("http://localhost:4000/auth/google/callback", "_self");
};
The full code is here: https://codesandbox.io/s/nervous-mountain-e5t9d4?file=/api/routes/auth.js
let me share with you the perfect code.
passportStratergy.js
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const User = require('../model/user');
const { USER_TYPES } = require('../constants/authConstant');
const googlePassportStrategy = passport => {
passport.serializeUser(function (user, cb) {
cb(null, user);
});
passport.deserializeUser(function (user, cb) {
cb(null, user);
});
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENTID,
clientSecret: process.env.GOOGLE_CLIENTSECRET,
callbackURL: process.env.GOOGLE_CALLBACKURL
}, async function (accessToken, refreshToken, profile, done) {
if (profile){
let userObj = {
'username':profile.displayName,
'ssoAuth': { 'googleId': profile.id },
'email': profile.emails !== undefined ? profile.emails[0].value : '',
'password':'',
'userType':USER_TYPES.User
};
let found = await User.findOne(User,{ 'email': userObj.email });
if (found) {
const id = found.id;
await User.updateOne(User, { _id :id }, userObj);
}
else {
await User.create(User, userObj);
}
let user = await User.findOne(User,{ 'ssoAuth.googleId':profile.id });
return done(null, user);
}
return done(null, null);
}
));
};
module.exports = { googlePassportStrategy };
auth.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const { socialLogin } = require('../services/auth');
router.get('/auth/google/error', (req, res) => {
res.loginFailed({ message:'Login Failed' });
});
router.get('/auth/google',passport.authenticate('google', {
scope: ['profile', 'email'],
session:false
}));
router.get('/auth/google/callback',
(req,res,next)=>{
passport.authenticate('google', { failureRedirect: '/auth/google/error' }, async (error, user , info) => {
if (error){
return res.send({ message:error.message });
}
if (user){
try {
//let result = await socialLogin(user.email);
// here your business logic for login user.
return res.send({
data: result.data,
message:'Login Successful'
});
} catch (error) {
return res.send({ message: error.message });
}
}
})(req,res,next);
});
module.exports = router;
index.js
const passport = require('passport');
const { googlePassportStrategy } = require('./passportStrategy');
googlePassportStrategy(passport);

PassportJS Express req.user not persisting in Heroku

I am using React and Express. Only the React is hosted on heroku and I am hosting the Express server locally. With Express I am using Passportjs with MongoDB.
The problem is that React clien t works well on local deployment, however once I deploy my React App on Heroku it does not work well propertly. When using my deployed React app, I can register a user but I cannot log in a user. It does not return error and POST("/login") returns "Successfully Authenticated" back to me and when I try to access req.user using axios it returns nothing back when it should be returning the user.
React Code
const getUser = () => {
axios({
method: "GET",
withCredentials: true,
url: "http://localhost:3001/user",
})
.then((res) => {
{
console.log(res.data);
if (res.data.username != null)
setMessage("Welcome " + res.data.username);
}
})
.catch((err) => console.log(err));
};
const loginTheUser = async () => {
await axios({
method: "POST",
data: {
username: username,
password: password,
},
withCredentials: true,
url: "http://localhost:3001/login",
}).then((res) => {
if (res.data === "Successfully Authenticated") {
history.push("/");
}
console.log(res.data);
});
await getUser();
};
Express code
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
cors({
origin: [
"http://localhost:3000",
"https://my-herokuapp.com",
], // <-- location of the react app were connecting to
credentials: true,
})
);
app.use(
session({
secret: "secretcode",
resave: true,
saveUninitialized: true,
})
);
app.use(cookieParser("secretcode"));
app.use(passport.initialize());
app.use(passport.session());
require("./passportConfig")(passport);
//Login
app.post("/login", (req, res, next) => {
passport.authenticate("local", (err, user, info) => {
if (err) throw err;
if (!user) {
console.log("Unsuccessful login");
res.send("Unsuccessful login");
} else {
req.logIn(user, (err) => {
if (err) throw err;
{
console.log("Login success");
res.send("Successfully Authenticated");
}
});
}
})(req, res, next);
});
//Register
app.post("/register", (req, res) => {
User.findOne({ username: req.body.username }, async (err, doc) => {
if (err) throw err;
if (doc) res.send("User Already Exists");
if (!doc) {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const newUser = new User({
username: req.body.username,
password: hashedPassword,
});
await newUser.save();
res.send("User Created");
}
});
});
//get User
app.get("/user", (req, res) => {
res.send(req.user); // The req.user stores the entire user that has been authenticated inside of it.
});
Passport config
const User = require("./user");
const bcrypt = require("bcryptjs");
const localStrategy = require("passport-local").Strategy;
module.exports = function (passport) {
passport.use(
new localStrategy((username, password, done) => {
User.findOne({ username: username }, (err, user) => {
if (err) throw err;
if (!user) return done(null, false);
bcrypt.compare(password, user.password, (err, result) => {
if (err) throw err;
if (result === true) {
return done(null, user);
} else {
return done(null, false);
}
});
});
})
);
passport.serializeUser((user, cb) => {
cb(null, user.id);
});
passport.deserializeUser((id, cb) => {
User.findOne({ _id: id }, (err, user) => {
const userInformation = {
username: user.username,
};
cb(err, userInformation);
});
});
};

trouble integrating express with passport

I hope someone can help me out as ive spent far too long scratching my head over this issue. I have a small React, Express, MongoDb app which i want to integrate with Passport.js. However I just cannot get the passport to authenticate.
I have a controller set up for a route /login. I have a console log at the start of the file so I know that the code goes into that block. However the code doesnt enter the passport authenticate block.
const bcrypt = require('bcrypt');
const user = db.user;
const passport = require('passport');
exports.login = async (req, res, next) => {
console.log('inside login controller');
passport.authenticate('local', function (err, user, info) {
console.log('inside passport');
req.login(user, function (err) {
console.log('inside req login');
if (err) {
return res.status(400).json({ errors: err });
}
return res
.status(200)
.json({ success: `logged in ${user.id}` })
.redirect('/users/' + user);
})(req, res, next);
});
};
My server file looks like this (omitted a lot of stuff to save space but the gist is as follows):
const passport = require('./passport/setup');
const initialisePassport = require('./passport/setup');
const auth = require('./controller/user.controller');
app.use(
session({
secret: 'a_very_special_secret',
resave: false,
saveUninitialized: true,
expires: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);
app.use(cookieParser('a_very_special_secret'));
app.use(initialisePassport.initialize());
app.use(passport.session());
The last file is the passport setup file which is here:
const bcrypt = require('bcrypt');
const db = require('../models');
const User = db.user;
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
//Local strategy
passport.use(
new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
console.log('inside passport strat');
User.findOne({ email })
.then((user) => {
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: 'Wrong password' });
}
});
})
.catch((err) => {
return done(null, false, { message: err });
});
})
);
module.exports = passport;
Id love a helping hand on where im going wrong with this. So basically when i post to the route via the front end I get the message in my console that im inside the login controller but the authentication process doesnt happen.

how to remove unverfied users from the database automatically?

I am making a social networking site with MERN Stack. Firstly, the users could simply sign up with email and password but that meant anyone can use any random email and possibly spam the DB. So I turned to this video https://www.youtube.com/watch?v=76tKpVbjhu8 and implemented it to ask for email verification.
Now the problem is even if a user registers and didn't verify his account another user can't create an account with the same email as it says user already exists. This means if some prankster registered an account with:
name: John Doe
email: johndoe#gmail.com
password: 123456
And couldn't verify his account, if someday the real johndoe comes and tries to register an account, he won't be able to register it as it already exists.
Is there anyway for the user to be automatically deleted if it failed to verify his account during the set time.
Here's my User Schema
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
],
profile: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Profile'
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
isVerified: {
type: Boolean,
default: false
},
date: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
Register route
// #route POST api/users
// #desc REgister a user
// #access Public
router.post(
'/',
[
check('name', 'Please add name')
.not()
.isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
'Please enter a password with 6 or more characters'
).isLength({ min: 6 })
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, password } = req.body;
try {
let user = await User.findOne({ email });
if (user) {
return res.status(400).json({ msg: 'User already exists' });
}
user = new User({
name,
email,
password
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
const payload = {
user: {
id: user.id
}
};
let profile = new Profile({
user: user.id
});
await profile.save();
user.profile = profile.id;
await user.save();
jwt.sign(
payload,
config.get('jwtSecret'),
{
expiresIn: 36000
},
(err, token) => {
if (err) throw err;
const url = `http://localhost:3000/confirmation/${token}`;
transporter.sendMail({
to: user.email,
subject: 'Confirm Email',
html: `Please click this link to confirm your email for signing up for MERN Blog ${url}`
});
res.json({
msg:
'Thanks for signing up! An email has been sent to your email for verification. Go ahead and verify your account'
});
}
);
} catch (err) {
console.log(err.message);
res.status(500).send('Server Error');
}
}
);
module.exports = router;
Confirmation route
router.post('/confirmation', async (req, res) => {
const token = req.body.token;
//Check if not token
if (!token) {
return res.status(401).json({ msg: 'No token, authorization denied' });
}
try {
const decoded = jwt.verify(token, config.get('jwtSecret'));
const user = await User.findByIdAndUpdate(decoded.user.id, {
isVerified: true
});
const payload = {
user: {
id: user.id
}
};
jwt.sign(
payload,
config.get('jwtSecret'),
{
expiresIn: 36000
},
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
res.status(401).json({ msg: 'Token is not valid' });
}
});
I think the best way of doing this would be to check the accounts creation date/time, if it has been over X amount of days/weeks && the email is not verified, then dispatch a delete action.

create password and access with password only

Trying to make an admin panel where the admin user can create passwords for the access page. You'll need the password to access the login/register page. I've been trying to make this with json web tokens. I've used the MEAN-stack for this:
access Schema
var accessSchema = new mongoose.Schema({
password: String
});
create jwt
function createAccessToken(password) {
var payload = {
sub: password._id,
iat: moment().unix(),
exp: moment().add(7, 'days').unix()
};
return jwt.encode(payload, config.ACCESSCODE_TOKEN_SECRET);
}
Login and signup
app.post('/auth/loginaccess', function (req, res) {
Access.findOne({ password: req.body.password }, function (err, access) {
if (!access) {
return res.status(401).send({ message: 'Invalid password' });
}
access.comparePassword(req.body.password, function (err, isMatch) {
if (!isMatch) {
return res.status(401).send({ message: 'Invalid password' });
}
res.send({ tokenauth: createAccessToken(access) });
});
});
getPasswords();
});
app.post('/auth/signupaccess', function (req, res) {
Access.findOne({ password: req.body.password }, function (err, existingPw) {
if (existingPw) {
return res.status(409).send({ message: 'Password is already taken' });
}
var access = new Access({
password: req.body.password
});
access.save(function (err, result) {
if (err) {
res.status(500).send({ message: err.message });
}
res.send({ tokenauth: createAccessToken(result) });
});
});
});
ComparePassword and save schema
accessSchema.pre('save', function (next) {
var access = this;
bcrypt.genSalt(10, function (err, salt) {
bcrypt.hash(access.password, salt, function (err, hash) {
access.password = hash;
next();
});
});
});
accessSchema.methods.comparePassword = function (password, done) {
bcrypt.compare(password, this.password, function (err, isMatch) {
done(err, isMatch);
});
};
the creation of the password works and is correctly encrypted and inserted into the database. But when I try to login it throws the 401 error inside app.post('/auth/loginaccess').
Why is this happening?
And any tips to improve this is highly appreciated.

Resources