Complete express req not in apollo-server-express - express

Below you can see I have an Apollo server (using express). In lines 33-39 I use an express middleware to check an auth token and (if the token is valid) set the users _id onto the request object.
In my server constructor, I set the context to return the req, as well as the _id as the userId. I have also tried just doing ({req}) => {..req}.
No matter what I am trying, I am not getting acces to the userId in the apollo context. I've made a simple gql query resolver in Apollo to just log out the value, and it's always undefined.
Furthermore, I have a simple REST route (lines 43-49) that seem to attach the userId to every request just fine, so something isn't connecting, but I'm not sure where.
At the end of the day my goal is to receive a JWT token from a cookie sent client side, verify it, and add it the context so I can access the values in my graphQL resolvers. Any thoughts?
index.js
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const bodyParser = require('body-parser');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const db = require('./db');
const User = require('./models/User');
const typeDefs = require('./gqlSchema');
const queries = require('./resolvers/queries');
const mutations = require('./resolvers/mutations');
const resolvers = {
Mutation: mutations,
Query: queries,
}
const app = express();
const corsOptions = {
origin: process.env.FRONTEND_URL,
credentials: true,
};
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
const { token } = req.cookies;
if (token) {
const tokenData = jwt.verify(token, process.env.SECRET);
req._id = tokenData._id;
}
next();
})
//// TEMP REST LOGIN ////
const login = require('./controllers/login');
app.post('/auth/google', login);
app.post('/token', (req, res) => {
console.log('/token middlware req: ', req._id);
res.send('test token route')
})
///////////////////
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({
...req,
userId: req._id,
})
});
server.applyMiddleware({
app,
path: '/graphql',
cors: false,
});
app.listen({ port: 4000 }, () => {
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
})

Related

authenticate tp express server tunneled through ngrok

I have an express server serving react pages. I am trying to show the work to a client via a ngrok tunnel. But whenever I try to log in at the ngrok URL for my server it fails to connect back to my localhost where the express routes for auth are.
I feel like it's a simple error I'm making. The browser is trying to make a request to the express server at localhost:5000, but there is nothing at localhost on my client's network.
This is my app.js
const createError = require('http-errors');
const express = require('express');
const debug = require('debug')('app');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
require('dotenv').config()
const ensureToken = require('./middleware/ensureToken');
const path = require('path');
const app = express();
const { init } = require('./utils/cron/createCron');
const cors = require('cors')
// Routers
const authRouter = require('./routes/auth')
const botRouter = require('./routes/bot')
const proxyRouter = require('./routes/proxy');
const winstonLogger = require('./utils/log/logger');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
const whiteList = ['http://localhost:3000/', 'http://localhost:3000']
const corsOptions = {
origin: (origin, callback)=>{
if (whiteList.indexOf(origin) !== -1){
callback(null, true)
}else{
callback(new Error('Not Allowed by CORS'))
}
optionsSuccessStatus:200
}
}
// app.use(cors(corsOptions))
app.use(cors({ credentials: true, origin: true }))
app.use(express.static(path.join(__dirname, 'build')));
// Base Routes
app.use('/api/auth', authRouter);
app.use(ensureToken) //Add this before routes that need to be protected ny valid token
app.use('/api/bot', botRouter);
app.use('/api/proxy', proxyRouter);
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "../client/build/index.html"));
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(process.env.PORT, ()=>{
winstonLogger.info(`Listening on ${process.env.PORT}`)
debug(`Listening on ${process.env.PORT}`);
console.log(`Listening on ${process.env.PORT}`);
init()
})
module.exports = app;
Any help is appreciated!!

expressJS is preventing me to post a resource

I'm trying to build a mini app in express, the "database" I'm using is a local array object file, I can retrieve resources from this "database" but for some reason I'm not able to post (push) a new object to this object array. This is how the code looks like:
server.js:
const express = require('express');
const app = express();
const userRouter = require('./routes/user.js');
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.text());
app.use('/user', userRouter);
app.listen(3000, () => console.log(`listening at ${port}`));
user.js:
const express = require('express');
const BBDD = require('./BBDD.js');
const userRouter = express.Router();
userRouter.get('/:guid', (req, res, next) => {
const { guid } = req.params;
const user = BBDD.find(user => user.guid === guid);
if (!user) res.status(404).send()
res.send(user);
next();
});
userRouter.post('/', (req, res, next) => {
let user = {};
user.name = req.body.name;
user.id = req.body.id;
BBDD.push(user);
next();
});
module.exports = userRouter;
And this is my local "database" file I want to perform logical CRUD operations:
BBDD.js
const BBDD = [{
index: 0,
guid: "1",
name: "Goku"
},
{
index: 1,
guid: "2",
name: "Vegeta"
},
];
module.exports = BBDD;
this is how I try to post a new resource, and this is the error I get:
It seems to be in order, but it won't work and can't find the bug.
Remove the next and send a response .express is having trouble finding the next matching handler because there is none

Passport user object in request not available in getInitialProps when server is on a different port

I have my express server on a different port than my client-side nextjs project.
I know when you have a server on the same port you can use getRequestHandler with next that passes the user object to be accessible with getInitialProps in the client-side.
const express = require("express");
const next = require("next");
const app = next({ dev: true });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
// adds passport session
require("./middlewares").init(server);
const apolloServer = require("./graphql").createApolloServer();
apolloServer.applyMiddleware({ app: server });
server.all("*", (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
});
});
My passport implementation is as follows
const config = require("../config");
const session = require("express-session");
const passport = require("passport");
exports.init = (server, db) => {
require("./passport").init(passport);
const sess = {
name: "pid",
secret: config.SESSION_SECRET,
cookie: { maxAge: 2 * 60 * 60 * 1000 },
resave: false,
saveUninitialized: false,
store: db.initSessionStore(),
};
if (process.env.NODE_ENV === "production") {
server.set("trust proxy", 1);
sess.cookie.secure = true;
sess.cookie.httpOnly = true;
sess.cookie.sameSite = 'none';
sess.cookie.domain = process.env.DOMAIN;
}
server.use(session(sess));
server.use(passport.initialize());
server.use(passport.session());
};
And running the following on the express server, I can see req.user returning the user object.
app.use((req, res, next) => {
console.log(req.user);
next();
});
In a page in my nextjs app, in getInitialProps req.user is undefined
Home.getInitialProps = async (ctx) => {
const { req } = ctx;
const { user } = req;
console.log(user);
..........
};
Is there a way to either access the passport user object via SSR in nextjs or a different method to authorize and user on a page?
I do have a Github Repo with instructions on how to run the app in the README.md
Passport auth doesn't seems work across port. The solution is put a ngnix in front.
Local passport authorization on different ports

Apollo express don't have express passport session

For our portal, i integrated my express server with passport to authenticate user. Once user authenticated need to fetch details for user from our api using same session from client. passport authentication working for my portal and able to see identity provider data for user logged in. but when any GraphQL call executed from react side, Apollo servers don't have user session in its request but express had.
Followed the steps mentioned here https://www.apollographql.com/docs/apollo-server/essentials/server.html#ssl but when setting up context for ApolloServer, req don't have passport in its session.
const express = require('express');
const session = require('express-session');
const { ApolloServer } = require('apollo-server-express');
const addResolveFunctionsToSchema = require('graphql-tools').addResolveFunctionsToSchema;
const mongooseConnection = require('./src/persistence/mongooseConnection');
const MongoSession = require('connect-mongo')(session);
const config = require('config');
const mongo = config.get('mongo');
const fs = require('fs');
const https = require('https');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const configSession = config.get('session');
const configPassport = config.get('passport');
const configCommon = config.get('common');
const resolvers = require('./src/resolvers');
const schema = require('./src/schema');
const uri = `${mongo.uri}/${mongo.database}`;
const app = express();
var passport = require('passport');
const SamlStrategy = require('passport-saml').Strategy;
const authRoute = require('./routes/auth');
const apiRoute = require('./routes/userDetails');
const Helmet = require('helmet');
require('reflect-metadata');
mongooseConnection.create();
let mongoOptions = {};
const mongoSessionStore = new MongoSession({
url: `${uri}`,
mongoOptions: mongoOptions,
collection: configSession.mongo.collection
});
addResolveFunctionsToSchema(schema, resolvers);
passport.use(
new SamlStrategy(
{
entryPoint: configPassport.entry_point,
// issuer: 'passport-saml',
protocol: 'https',
callbackURL: `${configCommon.dns}/${configPassport.callback_url}`,
// cert: adfsTokenSigningCert,
identifierFormat: null,
forceAuthn: true,
signatureAlgorithm: 'sha256',
acceptedClockSkewMs: -1
},
(profile, cb) => {
cb(null, profile);
}
)
);
passport.serializeUser(function(user, done) {
done(null, userData);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
app.use(cookieParser());
app.use(
session({
secret: 'project',
secret: configSession.config.secret,
resave: false,
saveUninitialized: false,
store: mongoSessionStore,
sameSite: true,
rolling: true,
name: 'project',
cookie: {
secure: true,
domain: configCommon.cookie_domain
}
})
);
// Initialize Passport
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: false
})
);
// setting up security headers
app.use(Helmet());
app.get('/s/health-check', (req, res) => {
res.send(`I am alive!!!!`);
});
app.use('/s/api', apiRoute);
app.use('/s/auth', authRoute); // API integration
const isDev = process.env.NODE_ENV !== 'prod';
const apolloServer = new ApolloServer({
schema,
resolvers,
context: ({ req }) => {
console.log(req) //req.session don't have passport in it
return {
req
};
}
});
apolloServer.applyMiddleware({
app,
path: '/graphql'
});
apolloServer.installSubscriptionHandlers(app);
https
.createServer(
{
key: fs.readFileSync(`./keys/server.key`),
cert: fs.readFileSync(`./keys/server.crt`)
},
app
)
.listen(process.env.PORT, () => {
console.log('Express server is running on port 9091');
});
// Handle uncaughtException
process.on('uncaughtException', err => {
console.log(err.message);
process.exit(1);
});
Double check that the request is sending the session cookies. I had the same problem, and I was using Graphql Playground as the client, and it disables sending the cookies by default. You can fix it by going to the settings in the top right of the playground, and setting "request.credentials": "same-origin". After I did that I saw the passport session initialized properly.

Google OAuth Broken After Heroku Deployment

My Google OAuth Strategy works perfectly on the client side. However after deploying the project to heroku the OAuth breaks once google attempts to redirect the user back to the specified redirect route. I am getting a Request Timed out error on the '/auth/google/callback/ route which is the route google is sending the user back to after authentication. It is defined in my authRoutes (Screenshot below). I am using PassportJS and Express for my backend. My development keys have been setup correctly as have my Google OAuth routes, the error only occurs upon the redirect from Google. Any help would be much appreciated
Here is my Passport Strategy:
const GoogleStrategy = require('passport-google-oauth20').Strategy
const keys = require('../config/keys')
const passport = require('passport')
const mongoose = require('mongoose')
const User = mongoose.model('users')
// This will store a cookie containing the user ID
// in our session after login is complete
passport.serializeUser((user, done) => {
done(null, user.id);
});
// This is called during every request
// It obtains a user object from the user id we serialized earlier
// the user object is stored in req.user
passport.deserializeUser((id, done) => {
User.findById(id).then(user => {
done(null, user);
});
});
passport.use (
new GoogleStrategy({
clientID: keys.googleClientID,
clientSecret: keys.googleClientSecret,
callbackURL: '/auth/google/callback',
proxy: true
},
async (accessToken, refreshToken, profile, done) => {
const existingUser = await User.findOne({googleID: profile.id});
if(!existingUser) {
const user = await User.create({googleID: profile.id}).save()
return done(null, user)
}
done(null, existingUser)
})
)
Here are my Routes:
const passport = require('passport')
module.exports = app => {
// This handles getting authentication details
// (gmail profile) from google
app.get("/auth/google", passport.authenticate('google', {
scope: ['profile', 'email']
}))
app.get("/auth/google/callback", passport.authenticate('google'), (req, res) => {
res.redirect('/surveys')
})
app.get("/api/logout", (req, res) => {
// Provided by passport
req.logout()
res.redirect('/')
})
app.get("/api/current_user", (req, res) => {
res.send(req.user)
})
}
And my Index.js:
const express = require('express');
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const passport = require('passport');
const keys = require('./config/keys');
const bodyParser = require('body-parser')
require('./models/User');
require('./models/Survey');
require('./services/passport');
mongoose.connect(keys.mongoURI);
const app = express();
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey]
})
);
app.use(bodyParser.json())
app.use(passport.initialize());
// This middleware injects a cookie in every request
// to allow us to identify the user
app.use(passport.session());
require('./routes/authRoutes')(app);
require('./routes/billingRoutes')(app);
if(process.env.NODE_ENV == "production"){
// Express will serve up production assets
// like our main.js file or main.css file!
app.use(express.static('client/build'))
// Express will serve up the index.html file
// if it doesn't recognize the route
const path = require('path')
app.get('*', (req, res ) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}
const PORT = process.env.PORT || 5000;
app.listen(PORT);
Heroku Error:
at=error code=H12 desc="Request timeout" method=GET path="/auth/google/callback?code=4/tgDTZZu8osZZvvMGjX4qaazb46SqNukZU6kNARY7R2enmH21cX6IfkVYSVnVHIoQ_qHaUbLttS_VGiS81KYE3D0&scope=email+profile+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile" host=cryptic-citadel-17268.herokuapp.com request_id=e8eb956d-64e4-4217-b846-91c53953e0a7 fwd="193.203.134.47" dyno=web.1 connect=0ms service=30001ms status=503 bytes=0 protocol=https
It's how you connect to your DB. You've mentioned that everything is working on your localhost correctly, but your production is giving your errors, please check this bit on prod - your connection error is likely due to production DB key configuration.
passport.use (
new GoogleStrategy({
clientID: keys.googleClientID,
clientSecret: keys.googleClientSecret,
callbackURL: '/auth/google/callback',
proxy: true
},
async (accessToken, refreshToken, profile, done) => {
const existingUser = await User.findOne({googleID: profile.id});
if(!existingUser) {
const user = await User.create({googleID: profile.id}).save()
return done(null, user)
}
done(null, existingUser)
})