Add Google OAuth authentication infrastructure

- Add passport, passport-google-oauth20, jsonwebtoken, cookie-parser, uuid deps
- Create config/auth.js with JWT, cookie, and OAuth configuration
- Create models/user.js with MongoDB user model and indexes
- Create middleware/passport.js with Google OAuth strategy
- Create middleware/auth.js with requireAuth middleware and sliding window refresh
- Create routes/auth.js with OAuth flow endpoints
- Update server.js to integrate auth, protect all data endpoints (except /health)
- Configure CORS for cookie-based authentication
This commit is contained in:
2026-01-21 16:45:34 -07:00
parent 04a78a21cc
commit 67f2d9a12e
8 changed files with 702 additions and 31 deletions

129
models/user.js Normal file
View File

@ -0,0 +1,129 @@
const { ObjectId } = require('mongodb');
const USER_COLLECTION = 'users';
/**
* Find or create a user based on Google OAuth profile
* Uses upsert pattern to handle both new and returning users
*
* @param {Db} db - MongoDB database instance
* @param {Object} profile - Google OAuth profile
* @param {string} profile.id - Google's unique user ID
* @param {string} profile.displayName - User's display name
* @param {Array} profile.emails - Array of email objects
* @param {Array} profile.photos - Array of photo objects
* @returns {Promise<Object>} User document
*/
async function findOrCreateUser(db, profile) {
const now = new Date();
const result = await db.collection(USER_COLLECTION).findOneAndUpdate(
{ googleId: profile.id },
{
$set: {
email: profile.emails[0].value,
name: profile.displayName,
picture: profile.photos?.[0]?.value || null,
lastLoginAt: now
},
$inc: { loginCount: 1 },
$setOnInsert: {
googleId: profile.id,
isActive: true,
role: 'user',
createdAt: now,
loginCount: 0 // Will be incremented to 1 by $inc
}
},
{
upsert: true,
returnDocument: 'after'
}
);
return result;
}
/**
* Find a user by Google ID
*
* @param {Db} db - MongoDB database instance
* @param {string} googleId - Google's unique user ID
* @returns {Promise<Object|null>} User document or null
*/
async function findByGoogleId(db, googleId) {
return await db.collection(USER_COLLECTION).findOne({ googleId });
}
/**
* Find a user by MongoDB ObjectId
*
* @param {Db} db - MongoDB database instance
* @param {string|ObjectId} id - User's MongoDB _id
* @returns {Promise<Object|null>} User document or null
*/
async function findById(db, id) {
// Convert string to ObjectId if needed
const objectId = typeof id === 'string' ? new ObjectId(id) : id;
return await db.collection(USER_COLLECTION).findOne({ _id: objectId });
}
/**
* Enable or disable a user account
*
* @param {Db} db - MongoDB database instance
* @param {string|ObjectId} id - User's MongoDB _id
* @param {boolean} isActive - New active status
* @returns {Promise<Object>} Update result
*/
async function setUserActive(db, id, isActive) {
// Convert string to ObjectId if needed
const objectId = typeof id === 'string' ? new ObjectId(id) : id;
const result = await db.collection(USER_COLLECTION).findOneAndUpdate(
{ _id: objectId },
{ $set: { isActive } },
{ returnDocument: 'after' }
);
return result;
}
/**
* Create required indexes for the users collection
* Should be called once during application startup
*
* @param {Db} db - MongoDB database instance
* @returns {Promise<void>}
*/
async function createIndexes(db) {
const collection = db.collection(USER_COLLECTION);
// Unique index on googleId for OAuth lookups
await collection.createIndex(
{ googleId: 1 },
{ unique: true }
);
// Unique index on email for user identification
await collection.createIndex(
{ email: 1 },
{ unique: true }
);
// Compound index for querying active users sorted by last login
await collection.createIndex(
{ isActive: 1, lastLoginAt: -1 }
);
console.log('User collection indexes created successfully');
}
module.exports = {
USER_COLLECTION,
findOrCreateUser,
findByGoogleId,
findById,
setUserActive,
createIndexes
};