Passport / node.js : Failed to serialize user into session - javascript

As a beginner I was following a tutorial to make my first website with node.js but when I try to test a login with 100% valid information I get the following error:
Error: Failed to serialize user into session
Something weird I found is that when the error pops up I go back to the previous page, in this case the login page, and a welcome message I added on /profile.hbs/ pops up as if I was in a session.
This is my passport.js
const res = require('express/lib/response');
const passport = require('passport');
const pool = require('../database');
const router = require('../routes/usuario');
const LocalStrategy = require('passport-local').Strategy;
//const helpers = require('../lib/helpers')
passport.use('local.signin', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
}, async (req, username, password, done) => {
const rows = await pool.query('SELECT * FROM userr WHERE username = ?', [username])
if (rows.length > 0) {
const user = rows[0];
const validPassword = user.password == password
if (validPassword) {
done(null, user, req.flash('success', 'Bienvenido, ' + user.username))
}else{
done(null, false, req.flash('message', 'ContraseƱa incorrecta'))
}
} else {
return done(null, false, req.flash('message', 'El usuario no existe'))
}
}));
passport.use('local.signup', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
}, async (req, username, password, done) => {
const newUser = {
username: username,
password: password
};
//newUser.password = await helpers.encryptPassword(password);
const result = await pool.query('INSERT INTO userr SET ?', [newUser])
newUser.id_user = result.insertId;
return done(null, newUser);
}));
passport.serializeUser((user, done) => {
console.log(user)
done(null, user.id_user)
});
passport.deserializeUser(async (id_user, done) => {
const rows = await pool.query('SELECT * FROM userr WHERE ID = ?', [id_user]);
done(null, rows[0]);
});
And this is my authentication.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const { route } = require('./usuario');
router.get('/signup', (req, res) => {
res.render('auth/signup')
});
router.post('/signup', passport.authenticate('local.signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true
}));
router.get('/signin', (req, res) => {
res.render('auth/signin')
});
router.post('/signin', (req, res, next) => {
passport.authenticate('local.signin',{
successRedirect: '/profile',
failureRedirect: '/signin',
failureFlash: true
})(req, res, next);
})
router.get('/profile', (req, res) => {
res.render('profile');
});
module.exports = router;
I tried to use a different route, I forced out a session (it worked with a deserialize error I had), I redid the login step with completely different variables and a different database but I still got the same response.

Related

ObjectParameterError: Parameter "filter" to findOne() must be an object, got

I try to connect my Login page with mongoose. Unfortunetly it doesn`t work.
I get the error:
ObjectParameterError: Parameter "filter" to findOne() must be an object, got 637798b57bfa9d5fbede9c30
I tried to find the solution the whole day, but I cant figure it out. Im also still learning coding and struggle to understand everything of it, but most I understand.
if(process.env.NODE_ENV !== "production") {
require("dotenv").config()
}
const express = require('express')
const app = express()
const bcrypt = require('bcrypt')
const passport = require("passport")
const initializePassport = require("./passport-config")
const flash = require("express-flash")
const session = require("express-session")
const methodOverride = require("method-override")
const mongoose = require("mongoose")
const User = require("./user")
const uri = 'abc'
async function connect(){
try{
await mongoose.connect(uri)
console.log("connected")
} catch (error){
console.error(error)
}
}
connect();
const user = User
initializePassport(
passport,
email => User.find(user => user.email === email),
_id => User.find(user => user._id === _id)
)
app.set('view-engine', 'ejs')
app.use(express.urlencoded({extended: false}))
app.use(flash())
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false, // We wont resave the session var if nothing is changed
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride("_method"))
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
const user = await User.findOne({email:email});
console.log(user);
if (user == null) {
return done(null, false, { message: 'No user with that email' })
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
})
}
module.exports = initialize
app.get('/', checkAuthenicated, (req, res)=> {
res.render('index.ejs', {name: req.body.name})
})
app.get('/login', checkNotAuthenicated, (req, res)=> {
res.render('login.ejs')
})
app.post("/login", checkNotAuthenicated, passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true
}))
app.get('/register', checkNotAuthenicated, (req, res)=> {
res.render('register.ejs')
})
app.post("/register", checkNotAuthenicated, async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
//users.push({
const user = new User({
id: Date.now().toString(),
username: req.body.name,
email: req.body.email,
password: hashedPassword
})
user.save().then(()=> console.log("User saved"))
console.log(user)
res.redirect("/login")
} catch (e){
console.log(e);
res.redirect("/register")
}
})
app.delete("/logout", (req, res) =>{
req.logOut(
res.redirect("/login")
)
})
function checkAuthenicated(req, res, next){
if (req.isAuthenticated()){
return next()
}
res.redirect("/login")
}
function checkNotAuthenicated(req, res, next){
if (req.isAuthenticated()){
return res.redirect("/")
}
next()
}
app.listen(3000)
const bcrypt = require('bcrypt')
const mongoose = require("mongoose")
const userShema = new mongoose.Schema({
id: String,
username: String,
email: String,
password: String
})
module.exports = mongoose.model("User", userShema)
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const User = require("./user")
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
const user = await User.findOne({email:email});
console.log(user);
if (user == null) {
return done(null, false, { message: 'No user with that email' })
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
passport.serializeUser((User, done) => done(null, User._id))
passport.deserializeUser(function(_id, done) {
User.findOne(_id, function (err, User) {
done(err, User);
});
});
}
module.exports = initialize
I think the problem lies somewhere in here:
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
passport.serializeUser((User, done) => done(null, User._id))
passport.deserializeUser(function(_id, done) {
User.findOne(_id, function (err, User) {
done(err, User);
});
});
But I`m not sure...
Thanks very much for your help.
You are mixing findOne and findById
findById does not need an object but the _id. As the docs (and also the method name) explain, under the hook it find by the id, so is like to do findOne({_id: id}).
From the docs:
findById(id) is almost* equivalent to findOne({ _id: id })
So the problem is you are trying to use simply the _id when the method expect an object to match the filter.
So you can use User.findOne({_id: _id}) or User.findById(_id)

Get username Passport js

I am a beginner and I have simple node application that use passport js.
Everything works but I want to get username here
app.get('/', checkLogged, (req, res) => {
res.render('index', {name: username});
});
Full project here https://github.com/aruzo1/passport
Can anybody help me?
There is way to do this?
Ps. This database is temporary
app.js
if (process.env.NODE_ENV !== 'production'){
require('dotenv').config();
}
const express = require('express'),
app = express(),
port = process.env.PORT || 3000,
bcrypt = require('bcrypt'),
passport = require('passport'),
initializePassport = require('./passport-config'),
flash = require('express-flash'),
session = require('express-session'),
methodOverride = require('method-override'),
users = []
initializePassport(passport,
email => users.find(user => user.email === email),
id => users.find(user => user.id === id)
);
require('ejs');
app.set('view engine', 'ejs');
app.use(express.urlencoded({extended : false}));
app.use(flash());
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(methodOverride('_method'));
app.get('/', checkLogged, (req, res) => {
res.render('index', {name: ""});
});
app.get('/login', checkNotLogged, (req, res) => {
res.render('login', {});
});
app.get('/register', checkNotLogged, (req, res) => {
res.render('register', {});
});
app.post('/register', checkNotLogged, async (req, res) => {
try{
hashedPassword = await bcrypt.hash(req.body.password, 10);
users.push({
id: Date.now().toString(),
name: req.body.name,
email: req.body.email,
password: hashedPassword
});
res.redirect('/login')
}
catch{
res.redirect('/register')
}
});
app.post('/login', checkNotLogged, passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}));
app.delete('/logout', (req, res) => {
req.logOut()
res.redirect('/login')
});
app.listen(port, () => {
console.log('serwer wystartowal')
});
function checkLogged(req, res, next){
if (req.isAuthenticated()){
return next();
}
res.redirect('/login');
}
function checkNotLogged(req, res, next){
if (req.isAuthenticated()){
return res.redirect('/')
}
next()
}
passport-config.js
const localStrategy = require('passport-local').Strategy,
bcrypt = require('bcrypt')
function initialize(passport, getUserByEmail, getUserById){
const authentitaceUser = async (email, password, done) =>{
const user = getUserByEmail(email);
if (user == null){
return done(null, false, {message: 'no user with that email'});
};
try{
if(await bcrypt.compare(password, user.password)){
return done(null, user)
}
else{
return done(null, false, {message: 'wrong password'})
}
}
catch(e){
return done(e)
}
};
passport.use(new localStrategy({
usernameField: 'email'
}, authentitaceUser));
passport.serializeUser((user, done) => {
return done(null, user.id)
});
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
});
};
module.exports = initialize
res.render('index', {name: req.user.username })
Should do the trick, as long the authentication itself was a success and your user has a 'username' field. Otherwise, req.user.username should throw an error;
Looks like you're using persistent sessions too - you should be able to grab user info from req.user and include it in your response...
app.get('/', checkLogged, (req, res) => {
res.send(req.user);
});
In passport.js when it verifies that user is logged in then the passport.js automatically set the logged-in user info to the res object.So it means whenever user send the request then the req object already having the user info.Here is the function whichdoing this:
passport.setAuthenticatedUser=(req,res,next)=>{
if(req.isAuthenticated())
{
res.locals.user=req.user;
}
next();
}
So in your case when user logged in at that time passport automatically set the user info to every res object.So when any request is coming in that request there is already an user info is present.
So that;s why you need write:
res.render('index', {name: req.user.username })
instead of writing:
res.render('index', {name: username});

REST API new users not posting to MongoDB

I am new to building REST API's, and I am trying to enter new user information into a collection called 'Users', however, when I submit the information I get Cannot POST /register
Below is my code
server.js
require('dotenv').config()
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const expressValidator = require('express-validator')
mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true , useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('Connected to Database'))
app.use(express.json())
const articlesRouter = require('./routes/articles')
app.use('/articles', articlesRouter)
const userRouter = require('./routes/users')
app.use('/register', userRouter)
app.set('view-engine', 'ejs')
app.use(express.urlencoded({ extended: false }))
app.get('/', (req, res) => {
res.render('index.ejs')
})
app.get('/login', (req, res) => {
res.render('login.ejs')
})
app.post('/login', (req, res) => {
})
app.get('/register', (req, res) => {
res.render('register.ejs')
})
app.listen(3000, () => console.log('Server Started'))
Users model
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
var userSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
password: String,
permissionLevel: Number,
created: Date},
{ collection: 'Users'});
module.exports = mongoose.model('Users', userSchema);
module.exports.createUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}
module.exports.getUserByEmail = function(email, callback){
var query = {email: email};
User.findOne(query, callback);
}
module.exports.getUserById = function(id, callback){
user.findById(id, callback);
}
module.exports.comparePassword = function(candidatePassword, hash, callback) {
bcrypt.compare(candidatePassword, hash, function(err, isMatch){
if(err) throw err;
callback(null, isMatch)
});
}
users routes
const express = require('express')
const router = express.Router()
const Users = require('../models/users')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
//Register Page - GET
router.get('/register', (req, res) => {
res.render('register.hbs', {
pageTitle: 'register'
});
});
//Login Page - GET
router.get('/login', (req, res) => {
res.render('login.hbs', {
pageTitle: 'login'
});
});
//Register - POST
router.post('/', (req, res) => {
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var password = req.body.password;
//validations
req.checkBody('firstName', 'Your First Name is Required').notEmpty();
req.checkBody('lastName', 'Your Last Name is Required').notEmpty();
req.checkBody('email', 'A valid email is required').isEmail();
req.checkBody('password', 'An Account Passowrd Is Required').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.render('register', {
errors:errors
});
} else {
var newUser = new newUser({
firstName: firstName,
lastName: lastName,
email: email,
password: password,
});
User.createUser(newUser, function(err, user) {
if(err) throw(err);
console.log(user);
});
req.flash('success_message', "You are now registered!");
res.redirect('/login');
}
});
passport.use(new LocalStrategy({
email: 'email'
},
function(email, password, done){
Users.getUserByEmail(email, function(err, Users){
if(err) throw err;
if(!Users){
return done(null, false, {message: 'Unknown Email Address'});
}
Users.comparePassword(password, user.password, function(err, ismatch){
if(err) throw err;
if(ismatch){
return done (null, user);
} else {
return done(null, false, {message: 'Invalid Passowrd'});
}
});
});
}));
passport.serializeUser(function(user, done){
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
Users.getUserByID(id, function(err, user) {
done(err, user)
});
});
router.post('/login', passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/login',
successFlash: 'Welcome',
failureFlash: 'Invalid Email or Passowrd!'
}), function(req, res) {
res.redirect('/');
});
router.get('/logout', function(req, res) {
req.logout();
req.flash('Success_message', 'You are now logged out!')
res.redirect('/');
});
module.exports = router
I suspect the conflict is between the router /register and the my 'Users' collection. I'm just unable to pinpoint what the issue could be.
Any help would be greatly appreciated
Your userRouter is mounted on /users (from your code: app.use('/users', userRouter), meaning that all the routes you declared in the router are prefixed by /users).
Try calling POST /users/register.
You're using users routes file at /users route, so when you declare /register route in users routes file it become /users/register please send your REST API request to /users/register endpoint

Cannot save more than one user to MongoDB

I am using nodeJS with the expressJS server framework. This issue is regarding passportJS not saving more than 1 user to MongoDB.
Firstly, I set up email registration with passport-local and got that to work fine. Secondly, I set up passport-facebook which essentially broke my email registration somehow. Each registration (email & facebook) now only log in just 1 user, I have to keep deleting the user from mongodb to register again. When there is 1 user in the database and I try to register another - I receive the error below.
process.nextTick(function() { throw err; });
^
TypeError: Cannot read property '1' of null at model.mongodbErrorHandler (/Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose-mongodb-errors/lib/plugin.js:19:49)
at next (/Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose/node_modules/kareem/index.js:145:14)
at Kareem.execPost (/Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose/node_modules/kareem/index.js:193:3)
at /Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose/lib/model.js:219:35
at /Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose/lib/model.js:152:9
at /Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose/node_modules/mongodb/lib/collection.js:524:20
at /Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose/node_modules/mongodb/lib/collection.js:658:14
at handleCallback (/Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose/node_modules/mongodb/lib/utils.js:95:56)
at /Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:465:9
at handleCallback (/Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose/node_modules/mongodb/lib/utils.js:95:56)
at resultHandler (/Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:413:5)
at /Users/tlr/Dropbox/Websites/app-one/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:455:18
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
I think the issue may lie around the User Schema because each Strategy saves different user information. Thus, local & facebook may not be marrying up properly in the database which causes an error? Correct me if I'm wrong.
The main files to look at are my userSchema (User.js), my routes file (index.js) where I include my FB Strategy and module imports, and my controller files (userController.js, authController.js) where I export my modules and functions.
User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
const md5 = require('md5');
const validator = require('validator');
const mongodbErrorHandler = require('mongoose-mongodb-errors');
const passportLocalMongoose = require('passport-local-mongoose');
const userSchema = new Schema({
name: {
type: String,
required: 'Please supply a name',
trim: true,
},
email: {
type: String,
unique: true,
lowercase: true,
trim: true,
required: 'Please supply an email address',
validate: [validator.isEmail, 'Invalid Email Address']
},
id: String,
token: String
});
userSchema.plugin(passportLocalMongoose, { usernameField: 'email' });
userSchema.plugin(mongodbErrorHandler);
module.exports = mongoose.model('User', userSchema);
index.js
const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const User = mongoose.model('User');
const authIDs = require('../../oauth');
const authController = require('../controllers/authController');
const userController = require('../controllers/userController');
const FacebookStrategy = require('passport-facebook').Strategy;
const router = express.Router();
passport.use(new FacebookStrategy({
clientID: authIDs.facebook.clientID,
clientSecret: authIDs.facebook.clientSecret,
callbackURL: authIDs.facebook.callbackURL,
profileFields: ['id', 'emails', 'name'],
passReqToCallback : true
},
function(req, accessToken, refreshToken, profile, done) {
const newUser = new User();
newUser.id = profile.id;
newUser.token = accessToken;
newUser.name = profile.name.givenName;
newUser.email = profile.emails[0].value;
process.nextTick( function() {
User.findOne({id: profile.id}, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
newUser.save().then( user => {
done( null, user );
} ).catch( err => {
done( err );
} );
} else {
return done(null, user);
}
});
});
}
));
router.get( '/login', userController.loginForm);
router.post( '/login', authController.login);
router.get( '/register', userController.registerForm);
router.post( '/register',
userController.validateRegister,
userController.register,
authController.login
);
router.get('/auth/facebook', authController.fbauth);
router.get('/auth/facebook/callback', authController.fbcallback);
router.get( '/logout', authController.logout);
router.get('/', (req, res) => {
res.render('home');
});
module.exports = router;
userController.js
const mongoose = require('mongoose');
const User = mongoose.model('User');
const promisify = require('es6-promisify');
exports.loginForm = (req, res) => {
res.render('login')
};
exports.registerForm = (req, res) => {
res.render('register')
};
exports.validateRegister = (req, res, next) => {
// express validator methods below
req.sanitizeBody('name');
req.checkBody('name', 'You must supply a name!').notEmpty();
req.checkBody('email', 'That email is not valid!').isEmail();
req.sanitizeBody('email').normalizeEmail({
remove_dots: false,
remove_extension: false,
gmail_remove_subaddress: false
});
req.checkBody('password', 'Password cannot be blank!').notEmpty();
req.checkBody('password-confirm', 'Confirmed password cannot be blank!').notEmpty();
req.checkBody('password-confirm', 'Oops! Your passwords do not match').equals(req.body.password);
const errors = req.validationErrors();
if (errors) {
req.flash('error', errors.map(err => err.msg));
res.render('register', { body: req.body, flashes: req.flash() });
return;
}
next();
};
exports.register = async (req, res, next) => {
const user = new User({ name: req.body.name, email: req.body.email});
const register = promisify(User.register, User);
await register(user, req.body.password);
next();
};
authController.js
const passport = require('passport');
const mongoose = require('mongoose');
const User = mongoose.model('User');
exports.login = passport.authenticate('local', {
failureRedirect: '/login',
failureFlash: 'Failed Login!',
successRedirect: '/',
successFlash: 'You are now logged in!'
});
exports.fbauth = passport.authenticate('facebook', {scope: ['email']});
exports.fbcallback = passport.authenticate('facebook', {
failureRedirect: '/login',
failureFlash: 'Failed Login!',
successRedirect: '/',
successFlash: 'You are now logged in!'
});
exports.logout = (req, res, next) => {
req.logout();
req.flash('success', 'You successfully logged out!');
res.redirect('/login')
};
Any suggestions on a fix would be suuuuuuuuper duuuuuuper highly appreciated.
OH MY GOD after hours of trying, like most problems solved in coding, this one was terribly embarrassing.
Because I'm using the code as mentioned in the question above, you can see I'm implementing both a local email registration as well as a passport-facebook authentication. So... What was causing that confusing error was the following code was like this:
passport.serializeUser(User.serializeUser(), function(user, done) {
done(null, user.id);
});
passport.deserializeUser(User.deserializeUser(), function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
instead of simply being like this:
passport.serializeUser(User.serializeUser(), function(user, done) {
done(null, user);
});
passport.deserializeUser(User.deserializeUser(), function(user, done) {
done(null, user);
});

Response from a failed login contains a cookie

In login.js, I am testing that a user will fail to login if unregistered credentials are sent in the request. The response to such a failed request should not contain a cookie, but after running my code the response DOES contain a cookie, along with a response status of 400.
Why is this happening???
login.js
const request = require('supertest')
const express = require('express')
const app = express()
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const expressSession = require('express-session')
const mongoose = require('mongoose')
const url = "mongodb://user1:password1#ds155091.mlab.com:55091/redditmock"
mongoose.connect(url)
//Configuring local authentication
passport.use(new LocalStrategy(
(username, password, done) => {
User.findOne({username: username}, (err, user) => {
if (err) return done(err)
if (!user) {
return done(null, false, {message: 'Incorrect username.'});
}
if (user.password !== password) {
return done(null, false, { message: 'Incorrect password.' })
}
return done(null, user)
})
}
))
//Configuring app to have sessions
passport.serializeUser((user, done) => {
done(null, user._id)
})
passport.deserializeUser((id, done) => {
User.findById(id, function(err, user) {
done(err, user)
})
})
app.use(expressSession({secret: 'aSecretKey'}))
app.use(passport.initialize())
app.use(passport.session())
app.post('/api/login', passport.authenticate('local'), (req, res) => res.end())
const server = app.listen(3000)
request(server)
.post('/api/login')
.type('form')
.send({username: "sasd"})
.send({password: "sdfa"})
.then((res) => {
cookie = res.header['set-cookie'][0]
console.log(res.status)
console.log(cookie)
})
User.js
const mongoose = require('mongoose')
const schema = new mongoose.Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
})
module.exports = mongoose.model('User', schema)

Categories

Resources