Skip to content

Commit

Permalink
Code refactor.
Browse files Browse the repository at this point in the history
  • Loading branch information
shrihari-prakash committed Jul 9, 2024
1 parent 84ab7b2 commit a54344e
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 55 deletions.
Binary file modified src/public/.DS_Store
Binary file not shown.
57 changes: 2 additions & 55 deletions src/service/passport/passport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,12 @@ const log = Logger.getLogger().child({ from: "passport" });

import passport from "passport";
import { Configuration } from "../../singleton/configuration.js";
import { Strategy as GoogleStrategy, Profile } from "passport-google-oauth20";
import UserModel from "../../model/mongo/user.js";
import { googleStrategy } from "./strategies/google.js";

export class Passport {
constructor() {
if (Configuration.get("user.account-creation.sso.google.enabled")) {
passport.use(
new GoogleStrategy(
{
clientID: Configuration.get("user.account-creation.sso.google.client-id"),
clientSecret: Configuration.get("user.account-creation.sso.google.client-secret"),
callbackURL: `${Configuration.get("system.app-host")}/sso/google/callback`,
scope: ["profile"],
},
this.onVerify.bind(this),
),
);
passport.use(googleStrategy);
passport.serializeUser(function (user, done) {
done(null, user);
});
Expand All @@ -31,48 +20,6 @@ export class Passport {
}
}

private async onVerify(_: string, __: string, profile: Profile, cb: (err: Error | null, user: any) => void) {
log.info("Google profile received: %o", profile);
if (!profile.emails || !profile.emails[0] || !profile.name || !profile.name.givenName || !profile.name.familyName) {
return cb(new Error("No email found in Google profile."), undefined);
}
const existingUser = await UserModel.findOne({ email: profile.emails[0].value }).lean();
if (existingUser) {
log.info("User found from Google profile.");
UserModel.updateOne(
{ _id: existingUser._id },
{ ssoEnabled: true, ssoProvider: "google", googleProfileId: profile.id },
).exec();
return cb(null, existingUser);
}
log.info("Creating user from Google profile.");
const role = Configuration.get("system.role.default");
const credits = Configuration.get("user.account-creation.initial-credit-count");
let customData = Configuration.get("user.account-creation.custom-data.default-value");
try {
JSON.parse(customData);
} catch {
customData = "{}";
log.warn("Invalid JSON found in `user.account-creation.custom-data.default-value`.");
}
const newUser = new UserModel({
email: profile.emails[0].value,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
username: profile.emails[0].value,
emailVerified: true,
ssoEnabled: true,
ssoProvider: "google",
googleProfileId: profile.id,
scope: Configuration.get("user.account-creation.default-scope"),
creationIp: "0.0.0.0",
role,
credits,
});
const savedUser = await newUser.save();
return cb(null, savedUser);
}

public initialize() {
passport.initialize();
log.debug("Passport initialized.");
Expand Down
59 changes: 59 additions & 0 deletions src/service/passport/strategies/google.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Logger } from "../../../singleton/logger.js";
const log = Logger.getLogger().child({ from: "google-strategy" });

import { Strategy as GoogleStrategy, Profile } from "passport-google-oauth20";

import { Configuration } from "../../../singleton/configuration.js";
import UserModel from "../../../model/mongo/user.js";

const onVerify = async (_: string, __: string, profile: Profile, cb: (err: Error | null, user: any) => void) => {
log.info("Google profile received: %o", profile);
if (!profile.emails || !profile.emails[0] || !profile.name || !profile.name.givenName || !profile.name.familyName) {
return cb(new Error("No email found in Google profile."), undefined);
}
const existingUser = await UserModel.findOne({ email: profile.emails[0].value }).lean();
if (existingUser) {
log.info("User found from Google profile.");
UserModel.updateOne(
{ _id: existingUser._id },
{ ssoEnabled: true, ssoProvider: "google", googleProfileId: profile.id },
).exec();
return cb(null, existingUser);
}
log.info("Creating user from Google profile.");
const role = Configuration.get("system.role.default");
const credits = Configuration.get("user.account-creation.initial-credit-count");
let customData = Configuration.get("user.account-creation.custom-data.default-value");
try {
JSON.parse(customData);
} catch {
customData = "{}";
log.warn("Invalid JSON found in `user.account-creation.custom-data.default-value`.");
}
const newUser = new UserModel({
email: profile.emails[0].value,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
username: profile.emails[0].value,
emailVerified: true,
ssoEnabled: true,
ssoProvider: "google",
googleProfileId: profile.id,
scope: Configuration.get("user.account-creation.default-scope"),
creationIp: "0.0.0.0",
role,
credits,
});
const savedUser = await newUser.save();
return cb(null, savedUser);
};

export const googleStrategy = new GoogleStrategy(
{
clientID: Configuration.get("user.account-creation.sso.google.client-id"),
clientSecret: Configuration.get("user.account-creation.sso.google.client-secret"),
callbackURL: `${Configuration.get("system.app-host")}/sso/google/callback`,
scope: ["profile"],
},
onVerify,
);

0 comments on commit a54344e

Please sign in to comment.