Rest API to connect (authorize) google for logged in user - express

I'm working in an application which uses a REST api using the MEAN stack and Passport JS to manage the authentication.
The authentication, we use JTW tokens for the communication between the backend and frontend. The token is generated based on local username and passwords.
Now I want to 'add' (authorize) the user's google account to the profile to use with google calendar API. (using this-> https://github.com/wanasit/google-calendar)
I've already have managed to send the user to the google authorization page, and get the token back from it. The problem is that when the user gets redirected to the page, it looses the JWT token where I check the user for the request.
Is there any other way to get the current logged in user, or to pass some custom callback authorization header/param when calling the authorize method?
auth.js:
var googleParams = {
clientID: config.auth.google.clientID,
clientSecret: config.auth.google.clientSecret,
callbackURL: config.auth.google.callbackURL
}
var googleStrategy = new GoogleStrategy(googleParams, function (token, refreshToken, profile, done) {
profile.token = token;
return done(null, profile);
});
routes:
rotas.get(
'/google',
auth.authenticate(), // will check the current user
auth.isLoggedIn, // make sure the user is really logged in
auth.authorize('google', { scope: googleScope, passReqToCallback: true }) // redirects to google to get the token
);
rotas.get('/callback/google',
auth.authorize('google', { scope: googleScope, passReqToCallback: true })
auth.authRedirect()
);
the auth.authRedirect() function above is the closest solution I've found. It's a Express middleware wich redirects the user to a known route in the frontend where the user IS authenticated... but then I would not be able to fetch all his Google profile and information i need...

You have to be sure the app.use(session) its been called before any route.
...
app.use(session({
secret: 'secret'
}))
app.use(passport.initialize())
app.use(passport.session())
...
rotas.get(
'/google',
auth.authenticate(), // will check the current user
auth.isLoggedIn, // make sure the user is really logged in
auth.authorize('google', { scope: googleScope, passReqToCallback: true }) // redirects to google to get the token
);
rotas.get('/callback/google',
auth.authorize('google', { scope: googleScope, passReqToCallback: true })
auth.authRedirect()
);
Your req.user won't be undefined in this case.
If it doen't work right way, I can put my whole code that I've created here.
Hope it help you! :)

So what I ended up doing was:
Authenticate the user making the request via JWT access_token
Get the user's ID and set it to the state option's property
The user is redirected to the google authorization page and choose the account (s)he wants to connect
(S)He gets redirected to my callback url with the state query param having the user's id
Now I just have to get that id, search the user in the database, and set the data I need from req.account which contains the user's openid profile.
var googleScope = ['openid', 'email', 'https://www.googleapis.com/auth/calendar'];
routes.get(
'/google',
auth.authenticate(),
auth.isLoggedIn,
function (req, res, next) {
var _id = '' + req.user._id; // convert to String... _id is an mongoose object
return auth.authorize('google', { session: false, scope: googleScope, passReqToCallback: true, state: _id })(req, res, next)
}
);
routes.get('/callback/google',
function (req, res, next) {
auth.authorize('google', { session: false, scope: googleScope, passReqToCallback: true })(req, res, next);
},
auth.saveUserData()
);
saveUserData= function () {
return function (req, res, next) {
if (req.query.state) {
var _id = req.query.state;
User.findOne({ _id, deleted: false, active: true })
.exec(function (err, user) {
if (err) {
res.send(err);
}
if (user) {
user.auth.google = {
id: req.account.id,
token: req.account.token,
email: (req.account.emails.length ? req.account.emails[0].value : null),
name: req.account.displayName
}
user.save(function (err, data) {
if (err) {
res.send(err);
} else {
res.redirect('/')
}
})
} else {
res.sendStatus(401);
}
})
} else {
res.sendStatus(400)
}
}

Related

Google OAuth2 with Passport and Express

I am struggling with getting Google OAuth to work with my Express/React application whilst using Passport.js. I am using JWTs, not sessions.
In my React webapp client, I have a "login with Google" button that calls my backend API /auth/google/ with the following route setup in Express:
router.get('auth/google', passport.authenticate('google', {session: false, scope: ['email','profile']}) );
My Passport.js google strategy is:
const googleStrategy = new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/api/v1/auth/google/callback",
passReqToCallback : true
},
async (request, accessToken, refreshToken, profile, done) => {
try {
console.log('profile', profile);// ** CORRECT USER PRINTED **
let existingUser = await User.findOne({ 'google.id': profile.id });
// if user exists return the user
if (existingUser) {
console.log('Found existing user...');
return done(null, existingUser);
}
// if user does not exist create a new user
const newUser = new User({
method: 'google',
googleId: profile.id,
profileImage: profile.photos[0].value,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
shortName: profile.displayName,
});
await newUser.save();
return done(null, newUser);
} catch (error) {
return done(error, false)
}
}
);
My Google developer dashboard is setup to call the following URL in my Express API backend upon successful authentication: /auth/google/callback
My Express route for this is defined as: router.get('auth/google/callback', passport.authenticate('google', {session: false}), authController.googleAuthCallback);
My Express googleAuthCallback function is defined as:
exports.googleAuthCallback = async (req, res) => {
console.log(req.user) // ** WRONG USER PRINTED HERE ** different from above user printed in google strategy
}
The strange this is when I console.log the profile variable in my googleStrategy, I get the right user profile information for the account from Google. This means the authentication vis a vis Google is fine. However, this same account is NOT being provided to my /auth/google/callback endpoint in the req.user object at that location. It is an entirely different account (it is the first value from my database of Users, which is authenticated using local authentication).
How do I get the user object back to my Express callback endpoint that I supplied to Google in the developer console as the authorized redirect URI?
As a general question, what happens after the strategy calls return done(null, existingUser);? I have no callback in the /auth/google route after the passport.authenticate() middleware is called so what happens next?
I am using "passport-google-oauth20": "^2.0.0"
My let existingUser = await User.findOne({ 'google.id': profile.id });
line was incorrect and was essentially returning no user. Mongoose does not complain and hence the strategy was just returning the first user from my database rather than the authenticated google user.

Is NextAuth Credentials safe?

I use next-auth Credentials (v3) to allow my users to register and sign in with good old email and password in my NextJS website. I use MongoDB as my database.
This is my [...nextauth].js file:
export default NextAuth({
session: {
jwt: true
},
providers: [
Providers.Credentials({
async authorize(credentials) {
await dbConnect();
// Check if a user with the email exists
const user = await UserModel.findOne({ email: credentials.email });
if (!user) throw new Error("Emailen is not in use");
// Check if the password is correct
const correctPassword = await bcrypt.compare(
credentials.password,
user.password
);
if (!correctPassword) throw new Error("Wrong password");
return {
userid: user._id,
email: user.email,
};
},
}),
],
callbacks: {
// Add userid to token
async jwt(token, user, account, profile, isNewUser) {
if (user) {
token.id = user.userid;
}
return token
},
// Add userid to session returned to front-end
async session(session, token) {
session.user.id = token.id;
return session
}
}
});
Before fetching data in my NextJS API endpoints, I check if the user is authenticated like this:
const session = await getSession({ req });
const user = await UserModel.findById(session?.user?.id);
if (!session || !user)
return res.status(400).json({ success: false });
But I'm worried that if a person gets the id of another user, they can just edit their JWT session.user.id and access any API endpoint pretending to be another user?
Is that true? Would the users be able to fake their id's in my code?
If so, what can I do to avoid that?

Session from express-session not persisting through requests

I'm using express-session and trying to implement a protected route with custom middleware.
[NOTE: I'm currently storing my session in-memory]
app.use(
session({
secret: "f4z4gs$Gcg",
cookie: { maxAge: 300000000, secure: true },
saveUninitialized: false,
resave: false,
store,
})
);
// MIDDLEWARE
function ensureAuthenticated(req, res, next) {
console.log(req.session) // This doesn't show the user and authenticated properties created in the POST login request
if (req.session.authenticated) {
return next();
} else {
res.status(403).json({ msg: "You're not authorized to view this page" });
}
};
app.post("/login", (req, res) => {
const { username, password } = req.body;
db.users.findByUsername(username, (err, user) => {
if (user) {
if (user.password === password) {
// Add your authenticated property below:
req.session.authenticated = true;
// Add the user object below:
req.session.user = {
username,
password,
};
// Send the session back to the client below:
res.json(req.session); // Properties show up here
} else {
res.status(403).json({ msg: "Bad Credentials" });
}
} else {
res.status(403).json({ msg: "No user found!" });
}
});
});
// PROTECTED ROUTE
app.get("/protected", ensureAuthenticated, (req, res) => {
res.render("profile");
});
Once a user logs in successfully, I try to add two properties into req.session: authenticated and the user object. However, once I login and try to access /protected with the middleware, my session properties do not persist (no user or authenticated property). Am I missing something?
Try setting secure to false in the cookie object. If you want it to be httpOnly, then just set httpOnly to true.

express-session: session is not accessable in other routes

I'm using express-session to store auth token in the session. The problem i'm facing is that the session i set in the /authenticate (post route) is not undefined in the /join (get route). I have searched for the similar questions but that didn't help. Any idea what's going wrong in my code?
server.js
// All required modules loaded..
// Session config
app.use(
session({
secret: "mysessionsecret",
resave: false,
saveUninitialized: false,
cookie: { secure: false, maxAge: 6000000 }
})
);
// #route:authenticate
app.post("/authenticate", async (req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(400).json({ msg: "Invalid username entered" });
}
// Compare the password
const compare = await bcrypt.compare(password, user.password);
if (!compare) {
return res.status(400).json({ msg: "Incorrect password" });
}
// Create token of the user ID
jwt.sign(
{
userId: user.id
},
config.get("jwtSecret"),
{
expiresIn: "2d"
},
(err, token) => {
if (err) throw err;
if (!req.session.user_id) {
req.session.token = token;
console.log(req.session.token); // Accessable here
}
}
);
res.end();
} catch (error) {
return res.send("Server error");
}
});
// #route:get /join
app.get("/join", (req, res) => {
console.log(req.session.token); // token not accessable here. returns undefined
return res.end();
});
The token will not be in the cookie, that's on the server only. The cookie is just a session ID. The default name for the express-session cookie is connect.sid. There should be a cookie with that name.
If you don't see that cookie anywhere, try saveUninitialized:true. You may also try calling req.session.save() after you modify the session in your /authenticate route. Either one of those should cause the session cookie to get set.
When you set saveUnitialized: false, you tell express-session NOT to set your session cookie until you tell it to. Unfortunately, the doc doesn't really say how you tell it to now set the session cookie. My guess was that req.session.save() might do it or just turning saveUnitialized to true would also do it. You can experiment with only using one of the two changes, though now you have a session cookie so you'd have to clear it in order to test with just one of them.

Authentication as an anonymous user

I would like to reproduce how plunker manages the anonymous accounts.
Plunker can recognise an anonymous user. For example, we can save a plunker as anonym and then freeze it. As a result,
only the same user (before clearing browser history) has the full access to this plunker (eg, save a modification, unfreeze).
if the same user opens it in another browser or other users open the same link, they can NOT save any modification; they have to fork it.
In my website, I use the local strategy of passport.js to manage named users. For example,
router.post('/login', function (req, res, next) {
if (!req.body.username || !req.body.password)
return res.status(400).json({ message: 'Please fill out all fields' });
passport.authenticate('local', function (err, user, info) {
if (err) return next(err);
if (user) res.json({ token: user.generateJWT() });
else return res.status(401).json(info);
})(req, res, next);
});
And I use a localStorage to store the token. For example,
auth.logIn = function (user) {
return $http.post('/login', user).success(function (token) {
$window.localStorage['account-token'] = token;
})
};
auth.logOut = function () {
$window.localStorage.removeItem('account-token');
};
Does anyone know if passport.js has any strategy or existing tools to manage the anonymous account like what plunker does? Otherwise, is there a conventional way to achieve this?
Passport allows anonymous auth. There is a passport anonymous strategy for the same:
app.get('/',
// Authenticate using HTTP Basic credentials, with session support disabled,
// and allow anonymous requests.
passport.authenticate(['basic', 'anonymous'], { session: false }),
function(req, res){
if (req.user) {
res.json({ username: req.user.username, email: req.user.email });
} else {
res.json({ anonymous: true });
}
});
This uses your basic strategy in place, you can substitute that with a local strategy if you're using local authentication. It falls back to an anonymous strategy in case nothing is supplied, as can be seen here:
passport.use(new BasicStrategy({
},
function(username, password, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure. Otherwise, return the authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (user.password != password) { return done(null, false); }
return done(null, user);
})
});
}
));
// Use the BasicStrategy within Passport.
// This is used as a fallback in requests that prefer authentication, but
// support unauthenticated clients.
passport.use(new AnonymousStrategy());
The full example may be found here:- https://github.com/jaredhanson/passport-anonymous/blob/master/examples/basic/app.js
Remember cookies with a longer expiration date is how anonymous user is identified. This goes the same way as any server side technology trying to authenticate user by username and password and then just sets a cookie for the http request.