Skip to content

Refactor User Authentication Strategies #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ on:

jobs:
build:
if: false
runs-on: ubuntu-latest

strategy:
Expand Down
12 changes: 12 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"octokit": "^3.2.1",
"passport": "^0.7.0",
"passport-github2": "^0.1.12",
"passport-google-oauth20": "^2.0.0",
"passport-local": "^1.0.0",
"pm2": "^5.3.1",
"short-uuid": "^5.2.0",
Expand Down
69 changes: 40 additions & 29 deletions src/auth/githubStrategy.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,34 +35,39 @@ const getGitHubStrategy = () => {

async function getOrCreateUserFromGitHubProfile({ profile, accessToken }) {
const isAdmin = config.ADMIN_USERNAMES.includes(profile.username);
// Create a new user from GitHub API Profile data

// Restructured payload to match new schema
const payload = {
githubId: profile.id,
nodeId: profile.nodeId,
displayName: profile.displayName,
username: profile.username,
profileUrl: profile.profileUrl,

avatarUrl: profile._json.avatar_url,
apiUrl: profile._json.url,
company: profile._json.company,
blog: profile._json.blog,
location: profile._json.location,
email: profile._json.email,
hireable: profile._json.hireable,
bio: profile._json.bio,
public_repos: profile._json.public_repos,
public_gists: profile._json.public_gists,
followers: profile._json.followers,
following: profile._json.following,
created_at: profile._json.created_at,
updated_at: profile._json.updated_at,
displayName: profile.displayName,
authType: 'github',

// GitHub specific data moved to github subdocument
github: {
id: profile.id,
nodeId: profile.nodeId,
profileUrl: profile.profileUrl,
avatarUrl: profile._json.avatar_url,
apiUrl: profile._json.url,
company: profile._json.company,
blog: profile._json.blog,
location: profile._json.location,
hireable: profile._json.hireable,
bio: profile._json.bio,
public_repos: profile._json.public_repos,
public_gists: profile._json.public_gists,
followers: profile._json.followers,
following: profile._json.following,
created_at: profile._json.created_at,
updated_at: profile._json.updated_at,
},

isDemo: false,
isVerified: true,
isAdmin,
};

// Update query to use github.id instead of githubId
let user = await getByGitHubId(profile.id);

const tokenInfo = encryptToken(accessToken);
Expand All @@ -72,33 +77,39 @@ async function getOrCreateUserFromGitHubProfile({ profile, accessToken }) {
}

// Update the user with the latest data
// Note: Using spread to maintain other fields while updating github subdocument
user = Object.assign(user, payload, {
accessToken: tokenInfo.token,
accessTokenIV: tokenInfo.iv,
github: {
...payload.github,
accessToken: tokenInfo.token,
accessTokenIV: tokenInfo.iv,
},
updatedAt: new Date(),
});
await updateById(user._id, user);
} else {
// Create a new user
user = await create({
...payload,
accessToken: tokenInfo.token,
accessTokenIV: tokenInfo.iv,
github: {
...payload.github,
accessToken: tokenInfo.token,
accessTokenIV: tokenInfo.iv,
},
});
}

const userObj = user.toObject();
const trimmedPayloadForSession = {
_id: userObj._id,
githubId: userObj.githubId,
nodeId: userObj.nodeId,
email: userObj.email,
authType: userObj.authType,
isAdmin: userObj.isAdmin,
isDeactivated: userObj.isDeactivated,
isDemo: userObj.isDemo,
// UI info
username: userObj.username,
displayName: userObj.displayName,
avatarUrl: userObj.avatarUrl,
email: userObj.email,
avatarUrl: userObj.github.avatarUrl,
};
return trimmedPayloadForSession;
}
Expand Down
85 changes: 85 additions & 0 deletions src/auth/googleStrategy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
const config = require('../configs');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const { AppError } = require('../libraries/error-handling/AppError');
const {
getByGoogleId,
create,
updateById,
} = require('../domains/user/service');

const getGoogleStrategy = () => {
return new GoogleStrategy(
{
clientID: config.GOOGLE_CLIENT_ID,
clientSecret: config.GOOGLE_CLIENT_SECRET,
callbackURL: `${config.HOST}/api/auth/google/callback`,
scope: ['profile', 'email'],
},
async (accessToken, refreshToken, profile, cb) => {
try {
const trimmedPayloadForSession = await getOrCreateUserFromGoogleProfile(
{
profile,
accessToken,
}
);
cb(null, trimmedPayloadForSession);
} catch (error) {
cb(error, null);
}
}
);
};

async function getOrCreateUserFromGoogleProfile({ profile, accessToken }) {
const isAdmin = config.ADMIN_USERNAMES.includes(profile.emails[0].value);

const payload = {
email: profile.emails[0].value,
displayName: profile.displayName,
authType: 'google',

google: {
id: profile.id,
email: profile.emails[0].value,
picture: profile.photos[0].value,
},

isDemo: false,
isVerified: true,
isAdmin,
};

let user = await getByGoogleId(profile.id);

if (user) {
if (user.isDeactivated) {
throw new AppError('user-is-deactivated', 'User is deactivated', 401);
}

user = Object.assign(user, payload, {
updatedAt: new Date(),
});
await updateById(user._id, user);
} else {
user = await create(payload);
}

const userObj = user.toObject();
const trimmedPayloadForSession = {
_id: userObj._id,
email: userObj.email,
authType: userObj.authType,
isAdmin: userObj.isAdmin,
isDeactivated: userObj.isDeactivated,
isDemo: userObj.isDemo,
displayName: userObj.displayName,
avatarUrl: userObj.google.picture,
};
return trimmedPayloadForSession;
}

module.exports = {
getGoogleStrategy,
getOrCreateUserFromGoogleProfile,
};
7 changes: 6 additions & 1 deletion src/auth/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ const {
getOrCreateUserFromGitHubProfile,
} = require('./githubStrategy');
const { localStrategy, registerUser } = require('./localStrategy');

const {
getGoogleStrategy,
getOrCreateUserFromGoogleProfile,
} = require('./googleStrategy');
// clear the accessToken value from database after logout
const clearAuthInfo = async (userId) => {
return await updateById(userId, {
Expand All @@ -24,4 +27,6 @@ module.exports = {
decryptToken,
localStrategy,
registerUser,
getGoogleStrategy,
getOrCreateUserFromGoogleProfile,
};
50 changes: 31 additions & 19 deletions src/auth/localStrategy.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,39 @@
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const { getByUsername, getByEmail, create } = require('../domains/user/service');
const {
getByUsername,
getByEmail,
create,
} = require('../domains/user/service');
const { AppError } = require('../libraries/error-handling/AppError');

const verifyCallback = async (username, password, done) => {
try {
const user = await getByUsername(username);
// Find user by email (since we're using email as username)
const user = await getByEmail(username);

if (!user) {
return done(null, false, { message: 'Incorrect username.' });
return done(null, false, { message: 'Incorrect email.' });
}

// Verify this is a local auth user
if (user.authType !== 'local') {
return done(null, false, {
message: `Please use ${user.authType} authentication for this account.`
});
}
console.log('user', user);
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
const isValidPassword = await bcrypt.compare(password, user.password);

console.log(
'user',
password,
user.password,
hashedPassword,
isValidPassword
);
// Verify password
const isValidPassword = await bcrypt.compare(password, user.local.password);
if (!isValidPassword) {
return done(null, false, { message: 'Incorrect password.' });
}

// Check if user is deactivated
if (user.isDeactivated) {
return done(null, false, { message: 'Account is deactivated.' });
}

return done(null, user);
} catch (err) {
return done(err);
Expand All @@ -33,7 +42,6 @@ const verifyCallback = async (username, password, done) => {

const registerUser = async ({ email, password }) => {
try {
console.log('registerUser', email, password);
// Check if user already exists
const existingUser = await getByEmail(email);
if (existingUser) {
Expand All @@ -44,12 +52,15 @@ const registerUser = async ({ email, password }) => {
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

// Create user payload
// Create user payload matching new schema structure
const payload = {
email,
username: email,
password: hashedPassword,
displayName: email,
authType: 'local', // Specify auth type
local: {
username: email,
password: hashedPassword,
},
isDemo: false,
isVerified: false,
isAdmin: false,
Expand All @@ -62,10 +73,11 @@ const registerUser = async ({ email, password }) => {
const userObj = newUser.toObject();
const trimmedPayloadForSession = {
_id: userObj._id,
email: userObj.email,
authType: userObj.authType,
isAdmin: userObj.isAdmin,
isDeactivated: userObj.isDeactivated,
isDemo: userObj.isDemo,
username: userObj.username,
displayName: userObj.displayName,
};

Expand Down
2 changes: 2 additions & 0 deletions src/configs/config.schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ const schema = Joi.object({
}),
GITHUB_CLIENT_ID: Joi.string().required(),
GITHUB_CLIENT_SECRET: Joi.string().required(),
GOOGLE_CLIENT_ID: Joi.string().required(),
GOOGLE_CLIENT_SECRET: Joi.string().required(),
// host should start with http:// or https://
HOST: Joi.string()
.pattern(/^(http:\/\/|https:\/\/)/)
Expand Down
Loading