I have three kind of user:
Viewer (link to sign in: auth/v/twitter)
Creator (link to sign in: auth/c/twitter)
Admin (link to sign in: auth/a/twitter)
And also I have 3 different db/collection
c_viewer
c_creator
c_admin
Where each kind of user have a different link to sign in.
Now let's take a look at the codes
var passport = require('passport')
,TwitterStrategy = require('passport-twitter').Strategy;
passport.use(new TwitterStrategy({
consumerKey: config.development.tw.consumerKey,
consumerSecret: config.development.tw.consumerSecret,
callbackURL: config.development.tw.callbackURL
},
function(token, tokenSecret, profile, done) {
process.nextTick(function(req, res) {
var query = User.findOne({ 'twId': profile.id});
query.exec(function(err, oldUser){
if(oldUser) {
done(null, oldUser);
} else {
var newUser = new User();
newUser.twId = profile.id;
newUser.twUsername = profile.username;
newUser.name = profile.displayName;
newUser.avatar = profile.photos[0].value;
-> newUser.age = req.body.creator.age; ???
newUser.save(function(err) {
if(err) throw err;
done(null, newUser);
});
};
});
});
}));
app.get('/auth/c/twitter', passport.authenticate('twitter'),
function(req, res) {
var userUrl = req.url;
// codes to pass the userUrl to TwitterStrategy
});
app.get('/auth/twitter/callback',
passportForCreator.authenticate('twitter', { successRedirect: '/dashboard', failureRedirect: '/' }));
And this is my form
<input type="text" name="creator[age]" placeholder="How old are you?">
<a id="si" class="btn" href="/auth/c/twitter">Sign in</a>
My questions:
1. Can We pass <input> data to the login process? so We can read the input data in TwitterStrategy, and save to the db
2. Can We get "c" from login url (auth/ c /twitter) and pass it to TwitterStrategy? so we can simply check in different db/collection and change the query.
The idea is to store your values before redirecting user on twitter for authentication, and re-use these values once the user came back.
OAuth2 includes the scope parameter, which perfectly suits that case. Unfortunately, TwitterStrategy is based on OAuth1. But we can tackle it !
The next trick is about when creating the user.
You should not do it when declaring strategy (because you cannot access input data), but a little later, in the last authentication callback
see here the callback arguments.
Declaring your strategy:
passport.use(new TwitterStrategy({
consumerKey: config.development.tw.consumerKey,
consumerSecret: config.development.tw.consumerSecret,
callbackURL: config.development.tw.callbackURL
}, function(token, tokenSecret, profile, done) {
// send profile for further db access
done(null, profile);
}));
When declaring your authentication url (repeat for a/twitter and v/twitter):
// declare states where it's accessible inside the clusre functions
var states={};
app.get("/auth/c/twitter", function (req, res, next) {
// save here your values: database and input
var reqId = "req"+_.uniqueId();
states[reqId] = {
database: 'c',
age: $('input[name="creator[age]"]').val()
};
// creates an unic id for this authentication and stores it.
req.session.state = reqId;
// in Oauth2, its more like : args.scope = reqId, and args as authenticate() second params
passport.authenticate('twitter')(req, res, next)
}, function() {});
Then when declaring the callback:
app.get("/auth/twitter/callback", function (req, res, next) {
var reqId = req.session.state;
// reuse your previously saved state
var state = states[reqId]
passport.authenticate('twitter', function(err, token) {
var end = function(err) {
// remove session created during authentication
req.session.destroy()
// authentication failed: you should redirect to the proper error page
if (err) {
return res.redirect("/");
}
// and eventually redirect to success url
res.redirect("/dashboard");
}
if (err) {
return end(err);
}
// now you can write into database:
var query = User.findOne({ 'twId': profile.id});
query.exec(function(err, oldUser){
if(oldUser) {
return end()
}
// here, choose the right database depending on state
var newUser = new User();
newUser.twId = profile.id;
newUser.twUsername = profile.username;
newUser.name = profile.displayName;
newUser.avatar = profile.photos[0].value;
// reuse the state variable
newUser.age = state.age
newUser.save(end);
});
})(req, res, next)
});
Related
I have a stand alone oauth2 identity provider that is working.
Now I'm developing a consumer that will authenticate users with this stand alone provider.
I'm following this tutorial about passport and Google Auth:
I'm trying to use this information to use passport-oauth2 to work as a client. I have made some changes in the code provided in the tutorial above by following the official documentation on passoprt-oauth2.
I think that I have some problem in the callback function where expressjs receive the confirmation of authentication and info about the user. I don't understand how to use this information.
Here is the code of my app.js
const express = require('express');
const app = express();
const passport = require('passport');
const OAuth2Strategy = require('passport-oauth2');
const cookieSession = require('cookie-session');
// cookieSession config
app.use(cookieSession({
maxAge:24*60*60*1000,
keys: ['secret-personalize']
}));
app.use(passport.initialize());
app.use(passport.session());
//Strategy config
passport.use(new OAuth2Strategy({
authorizationURL: 'http://localhost:3000/dialog/authorize',
tokenURL: 'http://localhost:3000/oauth/token',
clientID: 'xyz123',
clientSecret: 'ssh-password',
callbackURL: "/auth/oauth2/callback"
},
(accessToken, refreshToken, profile, done) => {
console.log(profile);
done(null, profile);
}
));
// Used to decode the received cookie and persist session
passport.deserializeUser((user, done) => {
done(null, user);
});
// Middleware to check if the User is authenticated
app.get('/auth/oauth2',
passport.authenticate('oauth2'));
function isUserAuthenticated(req, res, next){
if (req.user){
next();
} else {
res.send('you must login!');
}
}
// Routes
app.get('/', (req, res) => {
res.render('index.ejs');
});
// The middleware receives the data from AuthPRovider and runs the function on Strategy config
app.get('/auth/oauth2/callback', passport.authenticate('oauth2'), (req,res) => {
res.redirect('/secret');
});
// secret route
app.get('/secret', isUserAuthenticated, (req, res) =>{
res.send('You have reached the secret route');
});
// Logout route
app.get('/logout',(req, res) => {
req.logout();
res.redirect('/');
});
app.listen(8000, () => {
console.log('Server Started 8000');
});
and this is for views/index.ejs
<ul>
<li>Login</li>
<li>Secret</li>
<li>Logout</li></ul>
I got this error:
Error: Failed to serialize user into session
at pass (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/authenticator.js:281:19)
at Authenticator.serializeUser (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/authenticator.js:299:5)
at SessionManager.logIn (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/sessionmanager.js:14:8)
at IncomingMessage.req.login.req.logIn (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/http/request.js:50:33)
at OAuth2Strategy.strategy.success (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/middleware/authenticate.js:248:13)
at verified (/home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:177:20)
at OAuth2Strategy.passport.use.OAuth2Strategy [as _verify] (/home/user/job/NodeJS/test-consumer/second/app.js:31:5)
at /home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:193:24
at OAuth2Strategy.userProfile (/home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:275:10)
at loadIt (/home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:345:17)
Every help is welcome.
Thanks you
You need to add serializer:
passport.serializeUser(function(user, done) {
done(null, user);
});
I'm using this module now, but the profile always returns empty.
First you need to override the userProfile
This is the source code
const passport = require('passport')
// const { Strategy: GoogleStrategy } = require('passport-google-oauth20')
const { Strategy: GithubStrategy } = require('passport-github')
const { Strategy: OAuth2Strategy } = require('passport-oauth2')
const { GITHUB_CONFIG, OAUTH2_CONFIG} = require('../config')
const Profile = require('./profile')
module.exports = () => {
// Allow passport to serialize and deserialize users into sessions
passport.serializeUser((user, cb) => cb(null, user))
passport.deserializeUser((obj, cb) => cb(null, obj))
// The callback that is invoked when an OAuth provider sends back user
// information. Normally, you would save the user to the database
// in this callback and it would be customized for each provider
const callback = (accessToken, refreshToken, params, profile, cb) => {
console.log('access-token',accessToken)
console.log('refresh-token',refreshToken)
console.log('profile',profile)
console.log('params',params)
return cb(null, profile)
}
// Adding each OAuth provider's startegy to passport
// passport.use(new GoogleStrategy(GOOGLE_CONFIG, callback))
passport.use(new GithubStrategy(GITHUB_CONFIG, callback))
const DjangoStrategy = new OAuth2Strategy(OAUTH2_CONFIG, callback)
DjangoStrategy.userProfile = function(accessToken, done) {
var self = this;
this._userProfileURL = 'http://localhost:8001/accounts/profile/';
this._oauth2.get(this._userProfileURL, accessToken, function (err, body, res) {
var json;
if (err) {
if (err.data) {
try {
json = JSON.parse(err.data);
} catch (_) {}
}
if (json && json.message) {
return done(new APIError(json.message));
}
return done(new InternalOAuthError('Failed to fetch user profile', err));
}
try {
json = JSON.parse(body);
} catch (ex) {
return done(new Error('Failed to parse user profile'));
}
console.log('json', json)
var profile = Profile.parse(json);
profile.provider = 'oauth2';
profile._raw = body;
profile._json = json;
done(null, profile);
});
}
passport.use(DjangoStrategy)
}
Create a profile
profile.js
exports.parse = function(json) {
if ('string' == typeof json) {
json = JSON.parse(json);
}
var profile = {};
profile.id = String(json.id);
profile.displayName = json.name;
profile.username = json.username;
profile.email = json.email;
return profile;
};
You can also check clone my source code
https://github.com/faisallarai/nodejs-oauth-server.git
So, I got everything to work, up until the routing doesn't seem to be getting the data I'm sending into the user. But, if console.log inside of passport, it spits out the correct information. So here is my passport code, which works for the most part:
const LocalStrategy = require('passport-local').Strategy;
const db = require('mongodb');
const bcrypt = require('bcryptjs');
const config = require('./config');
module.exports = async (passport) => {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// used to serialize the user for the session
passport.serializeUser((user, done) => {
done(null, user._id);
});
// used to deserialize the user
passport.deserializeUser(async(id, done) => {
let userData = await userDb().findOne({ '_id': id});
done(null, userData);
});
// Local Strategy login
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passReqToCallback: true,
}, async (req, username, password, done) => {
console.log('Pulled up: ' + username);
let userDb = await usersDb();
let userData = await userDb.findOne({ 'email': username})
// Check if user exists
if (userData === null) {
console.log('User doesn\'t exist');
return Promise.reject('Email or password incorrect.');
} else {
// if user exists check password
let passCheck = await bcrypt.compareSync(password, userData.password);
if (passCheck) {
console.log('Password Correct');
return done(null, userData);
} else {
// if password is wrong
console.log('Password incorrect');
return Promise.reject('Email or password incorrect.');
}
}
}));
// DB collection
async function usersDb() {
const client = await db.MongoClient.connect(
config.database,
{
useNewUrlParser: true
}
);
return client.db('kog').collection('users');
}
};
heres the login route:
router.post('/login',
passport.authenticate('local-login', {
successRedirect: '/game',
failureRedirect: '/',
}), (req, res) => {
});
But my issues lies here:
// Get game route
app.get('/game', async (req, res) => {
if (req.user) {
res.render('game');
} else {
console.log('Forced redirect');
res.redirect('/');
}
});
Thought of another block that may be of an issue:
app.get('*', async (req, res, next) => {
res.locals.user = await req.user || null;
next();
});
No matter what I do I seem to not be able to get the routing check to pull up the user data. I am not sure where I am going wrong here, as it works all up to that point. I will successfully "login" but will result in be being forcefully redirected to '/' even if everything as worked correctly.
I am fairly certain it is the fact I probably am not handling the async/await stuff correctly, but I'm not sure where I am having problems.
I think you are missing :
passport.authenticate('local')
Which triggers your passport.js file localStrategy. Not sure how you got the passport file running to check to do the console.
For more, refer: http://www.passportjs.org/docs/authenticate/
I try to authentificate on a /login route with passport, I give an email, and a password (already stored in the database -email + hashed password with bcrypt). However, when I try to authentificate, my code never go into the passport.use...
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const db = require("../config/database");
/* Route methods */
exports.login = (req, res) => {
const email = req.body.email;
const password = req.body.password;
console.log("It will be displayed");
passport.use(
new LocalStrategy(function(email, password, done) {
console.log("It won't");
db.User.findOne({ email: email }, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: "Incorrect email." });
}
if (!bcrypt.compareSync(password, user.dataValues.password)) {
return done(null, false, { message: "Incorrect password." });
}
return done(null, user);
});
})
);
};
Furthermore, I create an API, and I'm wondering how authentificate someone (with session) with a REST API. Do I have to send on a endpoint the email and the password, then I create a session ? Thank you if you have any ressources.
This happens because you have only declared the actual Strategy but you'll need to create a separate route where you will authenticate the user using this local strategy with passport.authenticate.
Take a look at the example app I've created: https://github.com/BCooperA/express-authentication-starter-api
In config/passport.js I've created the actual Strategy:
const passport = require('passport')
, mongoose = require('mongoose')
, User = mongoose.model('User')
, LocalStrategy = require('passport-local').Strategy;
/**
|--------------------------------------------------------------------------
| Local authentication strategy (email, password)
|--------------------------------------------------------------------------
*/
passport.use(new LocalStrategy({ usernameField: 'user[email]', passwordField: 'user[password]' },
function(email, password, done) {
User.findOne({email: email}, function (err, user) {
if(err)
return done(err);
// incorrect credentials
if (!user || !user.validPassword(password) || user.password === '') {
return done(null, false, { errors: [{ msg: "Incorrect credentials" }] });
}
// inactive account
if(user.activation_token !== '' || user.active === 0) {
// account is not activated
return done(null, false, { errors: [{ msg: "Inactive account" }] });
}
// all good
return done(null, user);
});
}));
In addition, I've also created a separate POST route for signing in users locally where I'm using passport.authenticate.
In routes/auth.routes.js:
const router = require('express').Router()
, mongoose = require('mongoose')
, User = mongoose.model('User')
, passport = require('passport');
/**
|--------------------------------------------------------------------------
| Local Authentication
|--------------------------------------------------------------------------
| Authenticates user using Local Strategy by Passport
*/
router.post('/signin', function(req, res, next) {
if(req.body.user.email === '' || req.body.user.password === '')
// overrides passports own error handler
return res.status(422).json({errors: [{ msg: 'Missing credentials'}]});
passport.authenticate('local', { session: false }, function(err, user, info) {
if(err)
return next(err);
if(user) {
// generate JSON web token to user
user.token = user.generateJWT();
// return user object
return res.status(200).json({ user: user.toAuthJSON() });
} else {
// return any errors
return res.status(422).json(info);
}
})(req, res, next);
});
module.exports = router;
I downloaded one sample project from internet. Below there are some fragments of the code:
On the routes file I have the following (just a fragment):
var authController = require('./controllers/authController'),
var passport = require('passport');
var authLoginFacebook =
passport.authenticate(
'facebook',
{
session: false,
scope: ['public_profile', 'email']
}
);
var checkJwt = function(req, res, next) {
passport.authenticate(
'jwt',
{session: false },
function (err, user, info) {
next();
}
)(req, res, next);
}
module.exports = function(app) {
// ...
app.get(
'/api/auth/login/facebook/callback',
checkJwt,
authLoginFacebook,
authController.login
);
// ...
}
On the passport file I have the following (just a fragment):
var User = require('../models/user');
var credentials = require('./credentials');
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var LocalStrategy = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
module.exports = function(passport) {
passport.use(
new JwtStrategy({
secretOrKey: credentials.secret,
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('JWT'),
},
function(payload, done) {
User.findById(
payload._id,
function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
}
);
}
)
);
var fbStrategy = credentials.facebook;
fbStrategy.passReqToCallback = true;
passport.use(new FacebookStrategy(fbStrategy,
function(req, token, refreshToken, profile, done) {
// asynchronous
process.nextTick(function() {
// check if the user is already logged in
if (!req.user) {
User.findOne({
'facebook.id': profile.id
}, function(err, user) {
if (err)
return done(err);
if (user) {
// if there is a user id already but no token (user was linked at one point and then removed)
if (!user.facebook.token) {
user.facebook.token = token;
user.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
user.facebook.email = (profile.emails[0].value || '').toLowerCase();
user.save(function(err) {
if (err)
return done(err);
return done(null, user);
});
}
return done(null, user); // user found, return that user
} else {
// if there is no user, create them
var newUser = new User();
newUser.facebook.id = profile.id;
newUser.facebook.token = token;
newUser.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
newUser.facebook.email = (profile.emails[0].value || '').toLowerCase();
newUser.save(function(err) {
if (err)
return done(err);
return done(null, newUser);
});
}
});
} else {
// user already exists and is logged in, we have to link accounts
var user = req.user; // pull the user out of the session
user.facebook.id = profile.id;
user.facebook.token = token;
user.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
user.facebook.email = (profile.emails[0].value || '').toLowerCase();
user.save(function(err) {
if (err)
return done(err);
return done(null, user);
});
}
});
})
);
// ...
};
I have few questions here:
why on: passport.authenticate('jwt', ... are passed these arguments: (req, res, next) and on passport.authenticate('facebook', ... don't while they are used in the same line one next to other?
app.get(
'/api/auth/login/facebook/callback',
checkJwt,
authLoginFacebook,
authController.login
);
If I remove those arguments, then the web page keeps loading indefinitely.
why inside: passport.use(new FacebookStrategy is defined: req.user? where was declared the field: user for the object req?
Thanks!
*Edit: this is a function invoking another function...which is required because of the callback using next(). The facebook function doesn't have that.
In other words, when you invoke passport.authenticate, the return value is actually going to be a function expecting the parameters req, res, next. Normally you don't need to wrap it, because it just works. However, in this case there is a callback function being passed in as an argument, and that callback function needs access to the next parameter. So you have to wrap the whole thing to gain access to that next parameter.
*Note: the wrapped function isn't actually returning anything to/through the wrapping function. passport.authenticate() returns a function, and then this return function is self-invoked with the parameter group that follows. But this second self-invoked function result isn't captured as a variable or returned or anything.
The reason is that the important thing is either sending a response using the res parameter or allowing express to continue to the next layer of middleware/etc by calling the next() callback parameter. It's all happening asynchronously, and flow is directed using the callbacks.
var checkJwt = function(req, res, next) {
passport.authenticate(
'jwt',
{session: false },
function (err, user, info) {
next();
}
)(req, res, next);
}
the req.user would be a user from a previous login, which i believe passport.js normally stores using the express-session package.
I'm building a Node application in which the users must register or login, then when they drag and drop some elements (the front end is all working) I store on the database their action with their corresponding userId.
My understanding is that once they are registered/logged in, I can use the req.user to access their id and correctly store their actions, however it isn't working.
Here is the section of my server.js file that deals with Passport. Also, I'm using Sequelize as an ORM, but everything dealing with the database works perfect without the req.user part.
app.use(cookieParser());
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
/****** Passport functions ******/
passport.serializeUser(function (user, done) {
console.log('serialized');
done(null, user.idUser);
});
passport.deserializeUser(function (id, done) {
console.log("start of deserialize");
db.user.findOne( { where : { idUser : id } } ).success(function (user) {
console.log("deserialize");
console.log(user);
done(null, user);
}).error(function (err) {
done(err, null);
});
});
//Facebook
passport.use(new FacebookStrategy({
//Information stored on config/auth.js
clientID: configAuth.facebookAuth.clientID,
clientSecret: configAuth.facebookAuth.clientSecret,
callbackURL: configAuth.facebookAuth.callbackURL,
profileFields: ['id', 'emails', 'displayName', 'name', 'gender']
}, function (accessToken, refreshToken, profile, done) {
//Using next tick to take advantage of async properties
process.nextTick(function () {
db.user.findOne( { where : { idUser : profile.id } }).then(function (user, err) {
if(err) {
return done(err);
}
if(user) {
return done(null, user);
} else {
//Create the user
db.user.create({
idUser : profile.id,
token : accessToken,
nameUser : profile.displayName,
email : profile.emails[0].value,
sex : profile.gender
});
//Find the user (therefore checking if it was indeed created) and return it
db.user.findOne( { where : { idUser : profile.id } }).then(function (user, err) {
if(user) {
return done(null, user);
} else {
return done(err);
}
});
}
});
});
}));
/* FACEBOOK STRATEGY */
// Redirect the user to Facebook for authentication. When complete,
// Facebook will redirect the user back to the application at
// /auth/facebook/callback//
app.get('/auth/facebook', passport.authenticate('facebook', { scope : ['email']}));
/* FACEBOOK STRATEGY */
// Facebook will redirect the user to this URL after approval. Finish the
// authentication process by attempting to obtain an access token. If
// access was granted, the user will be logged in. Otherwise,
// authentication has failed.
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/' }),
function (req, res) {
// Successful authentication, redirect home.
res.redirect('../../app.html');
});
app.get('/', function (req, res) {
res.redirect('/');
});
app.get('/app', isLoggedIn, function (req, res) {
res.redirect('app.html');
});
app.post('/meal', function (req, res) {
//Testing Logs
/*console.log(req.body.foodId);
console.log(req.body.quantity);
console.log(req.body.period);
console.log(req.body);
*/
//Check whether or not this is the first food a user drops on the diet
var dietId = -1;
db.diet.findOne( { where : { userIdUser : req.user.idUser } } ).then(function (diet, err) {
if(err) {
return done(err);
}
if(diet) {
dietId = diet.idDiet;
} else {
db.diet.create( { userIdUser : req.user.idUser }).then(function (diet) {
dietId = diet.idDiet;
});
}
});
db.meal.create({
foodId : req.body.foodId,
quantity : req.body.quantity,
period : req.body.period
}).then(function (meal) {
console.log(meal.mealId);
res.json({ mealId : meal.mealId});
});
});
From what I read on the documentation for Passport, the deserializeUser function that I implemented should be called whenever I use req.user, however, with my console.logs(), I found out that serializeUser is called after logging in, therefore it is storing my session, but deserializeUser is never called! Ever.
Any idea on how to get around this? Any help is appreciated, thank you!
You need the express session middleware before calling passport.session(). Read the passportjs configuration section on documentation for more info.
Make sure to set cookieParser and express-session middlewares, before setting passport.session middleware:
const cookieParser = require('cookie-parser')
const session = require('express-session')
app.use(cookieParser());
app.use(session({ secret: 'secret' }));
app.use(passport.initialize());
app.use(passport.session());
To test if passport session is working or not, use:
console.log(req.session.passport.user)
(put in on a middleware for example)
In my case, i was using LocalStrategy and i was thinking i can protect and endpoint with simple username and password as form parameters, and i though passport will only use form parameters when it can't find user in session. but it was wrong assumption. in passport localStrategy, you should have separate endpoints for login and protected endpoint.
So Make sure you're using right middlewares for each endpoints. in my case:
wrong:
Protected endpoint:
app.get('/onlyformembers', passport.authenticate('local'), (req, res) => {
res.send({"res": "private content here!"})
})
correct :
Login:
app.post('/login', passport.authenticate('local'), (req, res) => {
res.send('ok')
})
Protected endpoint:
var auth = function (req, res, next) {
if (req.isAuthenticated())
return next();
res.status(401).json("not authenticated!");
}
app.get('/onlyformembers', auth, (req, res) => {
res.send({"res": "private content here!"})
})