I have also error with passportjs. Before errors if you know good tutorial passportjs, passport-local-mongoose with react please send me link.
I watch a video youtube and work code in [that][1] . This is github. But I want change authentication passport. In modaljs I do this:
const mongoose = require('mongoose');
const moment = require("moment");
const passportLocalMongoose = require('passport-local-mongoose');
const userSchema = mongoose.Schema({
name: {
type:String,
maxlength:50
},
email: {
type:String,
trim:true,
unique: 1
},
password: {
type: String,
minglength: 5
},
lastname: {
type:String,
maxlength: 50
},
role : {
type:Number,
default: 0
},
image: String
});
userSchema.plugin(passportLocalMongoose, {usernameField: 'email'});
const User = mongoose.model( 'User' , userSchema );
module.exports = {User};
in Userjs I do this:
const { User } = require('../models/model');
const router = require('express').Router();
const passport = require('passport');
passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser( async function(id, done) {
await User.findById(id, function(err, user) {
done(err, user);
});
});
router.get('/auth', (req, res) => {
// res.send(req.isAuthenticated)
if(req.isAuthenticated()){
res.status(200).json({
_id: req.user._id,
isAdmin: req.user.role === 0 ? false : true,
isAuth: true,
email: req.user.email,
name: req.user.name,
lastname: req.user.lastname,
role: req.user.role,
image: req.user.image,
});
}
else{
return res.json({
isAuth: false,
error: true
});
}
});
router.post('/register', async (req, res) => {
await User.register( {email: req.body.email}, req.body.password, (err,user)=>{
if(err) return res.json({ success: false, err });
else res.status(200).json({
success: true
});
});
});
router.post("/login", function (req, res) {
console.log(req.body);
passport.authenticate("local")(req, res, function () {
console.log("ok!");
res.json({
loginSuccess: false,
message: "Invalid email or password"
});
});
});
router.get('/logout', (req, res) => {
if(req.isAuthenticated){
req.logout();
res.status(200).send({
success: true
});
}
else return res.json({success: false});
});
module.exports = router;
in server.js I add passport and this:
app.use(passport.initialize());
app.use(passport.session());
When first time I start server I get this error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
But after I get nothink. only show console req.body. How find error. I am very tired with passportjs. Where I find best tutorial passportjs with plugin database in passport-local-mongoose. And How find error and fix it. Sorry my english:))
[1]: https://github.com/jaewonhimnae/boilerplate-mern-stack
Please try res.status(200).send instead of res.status(200).json
Related
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);
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",
})
);
I've seen in some videos that the username and password are sent via axios
this is:
const user_Login = (email, password) => async (dispatch) =>{
dispatch({ type: USER_LOGIN_REQUEST });
try {
const {data} = await axios( {
method: "POST",
data: {
username: email,
password: password
},
withCredentials: true,
url: "http://localhost:3001/login"
});
dispatch({ type: USER_LOGIN_SUCCESS, payload: data });
} catch (error) {
dispatch({type: USER_LOGIN_FAIL, error: error.message});
}
}
I used cors when I got the password with the username. but there is a problem I can't fix or find it. passport.serilizeUser change User id two times. and req.user cannot work.
This is backend:
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const passportLocalMongoose = require('passport-local-mongoose');
const session = require('express-session');
const app = express();
app.use(cors({
origin: "http://localhost:3000",
credentials: true
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(session({
secret: "Our little secret.",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(
'mongodb://localhost:27017/testdb'
, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const shema = new mongoose.Schema({
username: String,
password: String
});
shema.plugin(passportLocalMongoose);
const User = mongoose.model("users", shema);
// User.plugin( passportLocalMongoose );
passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
console.log("serilizeUser:", user.id);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
console.log("deserlizeUser: ", id);
User.findById(id, function(err, user) {
done(err, user);
});
});
app.post('/register', (req, res) => {
console.log(req.body);
User.register( {username: req.body.username}, req.body.password, (err,user)=>{
if(err){
console.log(err);
}
else{
res.send("User successfully registered!");
}
});
});
app.get('/', (req, res) => {
res.send(req.user);
});
app.post('/login', function(req, res){
const _user = new User({
username: req.body.username,
password: req.body.password
});
req.login( _user, function(err){
if(err){
console.log(err);
}
else{
console.log("inside: ", req.user.id);
passport.authenticate("local")(req,res,function(){
console.log("ok!");
})
}
} );
res.send(req.user.id);
});
app.get('/', (req, res) => {
res.send(req.user);
});
app.listen(3001, () => {
console.log(`Server started on port 3001`);
});
when I send username and password I get console this:
serilizeUser: 607959e213f2692264c31c3b
inside: 607959e213f2692264c31c3b
serilizeUser: 60794a8736e1df1dfc16c37c
ok!
I think error with send username and password. Please help me!
I can't solve this problem for 5 days.
req.login() establishes a login session. passport.authenticate() middleware invokes req.login() automatically. passport.serializeUser will be invoked from req.login().
Here both of them are being used. Only passport.authenticate() should be fine to create a session and authenticate it. Check the follows,
app.post("/login", function (req, res) {
passport.authenticate("local")(req, res, function () {
console.log("ok!");
res.send(req.user.id);
});
});
I checked it in my local and works as you expected !!
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.
I'm trying to add to my mongodb database through my angular 2 frontend but It doesn't seem that the post is going through. I use morgan to log all requests and it shows nothing, then I don't see anything in my database.
my api route:
// add venue
router.post('/add_venue', (req, res, next) => {
let newVenue = new Venue({
_id: req.body._id,
name: req.body.name,
street: req.body.street,
city: req.body.city,
state:req.body.state,
zipcode:req.body.zipcode,
busy:req.body.busy
});
Venue.addVenue(newVenue, (err, venue) => {
if(err){
res.json({success: false, msg:'Failed to add venue'});
} else {
res.json({success: true, msg:'User registered'});
}
});
});
router.get('/venue/:id', (req, res, next) =>{
let venueID = req.params.id;
Venue.findById(venueID, (err, user) => {
if(err) throw err;
if(!venueID){
return res.json({success: false, msg: 'Venue not found'});
}
I haven't tried the get request yet. Here my model:
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
const VenueSchema = mongoose.Schema({
_id:{
type:String,
required:true
},
name:{
type:String,
required:true
},
street:{
type:String,
required:true
},
city:{
type:String,
required:true
},
state:{
type:String,
required:true
},
zipcode:{
type:String,
required:true
},
busy:{
type:Boolean,
},
});
const Venue = module.exports = mongoose.model('Venues', VenueSchema);
module.exports.addVenue = function(newVenue, callback){
newVenue.save(callback);
}
and here's the service i'm using on the front-end. I'm getting no errors with angular 2, it's all just through the back-end.
#Injectable()
export class VenueService{
constructor(private http:Http){
}
getVenue(id){
var headers = new Headers();
return this.http.get('//ec2 instance/venues/venues'+ id)
.map(res => res.json());
}
addV
enue(newVenue){
var headers = new Headers;
headers.append('Content-Type', 'application/json');
return this.http.post('(I'm using an ec2 address)/venues/venues', newVenue, {headers:headers})
.map(res => res.json());
}}
I'm using vscode, and I'm fairly new to javascript. Is there something I missed here?
Try using following way
JS
var newVenue = {
data: 'something'
};
$http.post('http://url/data', newVenue, {
headers: headers
})
.then(res => console.log(res.data());
This way you can see what is coming response or test your rest apis/calls from Postman rest client app