-
Notifications
You must be signed in to change notification settings - Fork 13.8k
feat: Configure Passport #39604
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
feat: Configure Passport #39604
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
08a4e9e
WIP: configure passport and basic code structure
yash-rajpal ad189cb
lock file
yash-rajpal ebf2db2
email scopes
yash-rajpal f9d83ce
move validations to verify function
yash-rajpal c754b05
refactor
yash-rajpal d128e62
remove console.logs
yash-rajpal f9c35d7
unuse passport strategy before configuring
yash-rajpal ef8b5b0
guard if user isn't created as expected
yash-rajpal 2626e44
oops: console logs :-(
yash-rajpal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| import { Users } from '@rocket.chat/models'; | ||
| import { Random } from '@rocket.chat/random'; | ||
| import express from 'express'; | ||
| import session from 'express-session'; | ||
| import { WebApp } from 'meteor/webapp'; | ||
| import passport from 'passport'; | ||
|
|
||
| import type { ICachedSettings } from '../../app/settings/server/CachedSettings'; | ||
| import { configureOAuthServices } from '../lib/oauth/configureOAuthServices'; | ||
| import { createOAuthServiceConfig } from '../lib/oauth/createOAuthServiceConfig'; | ||
| import { getOAuthServices } from '../lib/oauth/getOAuthServices'; | ||
|
|
||
| export const oAuthRouter = express(); | ||
|
|
||
| oAuthRouter.use( | ||
| session({ | ||
| name: 'oauth', | ||
| secret: Random.secret(), | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TODO: check with @cardoso if this is FIPS-compliant.
yash-rajpal marked this conversation as resolved.
|
||
| resave: false, | ||
| saveUninitialized: false, | ||
| cookie: { | ||
| httpOnly: true, | ||
| secure: process.env.NODE_ENV === 'production', | ||
| maxAge: 5 * 60 * 1000, // 5 minutes | ||
| }, | ||
| }), | ||
| ); | ||
|
|
||
| oAuthRouter.use(passport.initialize()); | ||
| oAuthRouter.use(passport.session()); | ||
|
|
||
| export const configurePassport = (settings: ICachedSettings) => { | ||
| passport.serializeUser((user: any, done) => { | ||
| done(null, user._id); | ||
| }); | ||
|
|
||
| passport.deserializeUser(async (id, done) => { | ||
| const user = await Users.findOneById(id as string); | ||
| // we don’t actually use this user later | ||
| done(null, user); | ||
|
yash-rajpal marked this conversation as resolved.
|
||
| }); | ||
|
|
||
| settings.watchByRegex(/^(Accounts_OAuth_)[a-z0-9_]+$/i, () => { | ||
| const services = getOAuthServices(settings); | ||
| const oauthServiceConfigs = createOAuthServiceConfig(settings, services); | ||
| configureOAuthServices(oauthServiceConfigs); | ||
| }); | ||
|
|
||
| WebApp.rawConnectHandlers.use(oAuthRouter); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import { type IUser } from '@rocket.chat/core-typings'; | ||
| import { Users } from '@rocket.chat/models'; | ||
| import { Accounts } from 'meteor/accounts-base'; | ||
| import { Meteor } from 'meteor/meteor'; | ||
| import passport from 'passport'; | ||
| import type { Profile, DoneCallback } from 'passport'; | ||
|
|
||
| import type { OAuthServiceConfig } from './createOAuthServiceConfig'; | ||
| import { oAuthRouter } from '../../configuration/configurePassport'; | ||
|
|
||
| export const configureOAuthServices = (oauthServiceConfig: OAuthServiceConfig[]) => { | ||
| oauthServiceConfig.forEach((config) => { | ||
| const Strategy = config.strategy; | ||
|
|
||
| passport.unuse(config.provider); | ||
|
|
||
| passport.use( | ||
| config.provider, | ||
| new Strategy( | ||
| { | ||
| clientID: config.clientId, | ||
| clientSecret: config.clientSecret, | ||
| callbackURL: `${Meteor.absoluteUrl()}oauth/${config.provider}/callback`, | ||
| state: true, | ||
| pkce: true, | ||
| scope: config.scope, | ||
| profileFields: ['id', 'displayName', 'emails'], | ||
| }, | ||
| async (accessToken: string, refreshToken: string, profile: Profile, done: DoneCallback) => { | ||
| const profileWithRaw = profile as Profile & { _json?: Record<string, unknown>; _raw?: string }; | ||
| const { _json, _raw, ...restProfile } = profileWithRaw; | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/await-thenable | ||
| const user = await Accounts.updateOrCreateUserFromExternalService( | ||
| config.provider, | ||
| { | ||
| accessToken, | ||
| refreshToken, | ||
| name: profile.displayName, | ||
| email: profile?.emails?.[0]?.value, | ||
| ...restProfile, | ||
| ..._json, | ||
| }, | ||
| {}, | ||
| ); | ||
|
|
||
| if (!user?.userId || typeof user?.userId !== 'string') { | ||
| return done(new Error('User not found')); | ||
| } | ||
|
|
||
| const userFromDB = await Users.findOneById(user.userId); | ||
|
|
||
| if (!userFromDB) { | ||
| return done(new Error('User not found')); | ||
| } | ||
|
|
||
| return done(null, userFromDB); | ||
|
yash-rajpal marked this conversation as resolved.
|
||
| }, | ||
| ), | ||
| ); | ||
|
|
||
| oAuthRouter.get( | ||
| `/oauth/${config.provider}`, | ||
| passport.authenticate(config.provider, { scope: config.scope, prompt: 'consent', failureRedirect: '/login' }), | ||
| ); | ||
| oAuthRouter.get( | ||
| `/oauth/${config.provider}/callback`, | ||
| passport.authenticate(config.provider, { failureRedirect: '/login' }), | ||
|
yash-rajpal marked this conversation as resolved.
|
||
| async (req, res) => { | ||
| const oAuthUser = req.user as IUser; | ||
|
|
||
| if (!oAuthUser) { | ||
| return res.redirect('/login'); | ||
| } | ||
|
|
||
| const stampedToken = Accounts._generateStampedLoginToken(); | ||
| Accounts._insertLoginToken(oAuthUser._id, stampedToken); | ||
|
|
||
| res.redirect(`/home?resumeToken=${stampedToken.token}`); | ||
|
yash-rajpal marked this conversation as resolved.
|
||
|
|
||
| req.session.destroy((err) => { | ||
| if (err) { | ||
| console.error('Error destroying session', err); | ||
| } | ||
| }); | ||
| }, | ||
|
yash-rajpal marked this conversation as resolved.
Dismissed
|
||
| ); | ||
| }); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import { capitalize } from '@rocket.chat/string-helpers'; | ||
| import type { Strategy } from 'passport'; | ||
|
|
||
| import { OAuthConfigs } from './oauthConfigs'; | ||
| import { type ICachedSettings } from '../../../app/settings/server/CachedSettings'; | ||
|
|
||
| export type OAuthServiceConfig = { | ||
| provider: string; | ||
| strategy: new (...args: any[]) => Strategy; | ||
| clientId: string; | ||
| clientSecret: string; | ||
| scope: string[]; | ||
| }; | ||
|
|
||
| export const createOAuthServiceConfig = (settings: ICachedSettings, services: string[]): OAuthServiceConfig[] => { | ||
| return services.map((service) => { | ||
| return { | ||
| provider: service, | ||
| strategy: OAuthConfigs[service].strategy, | ||
| clientId: settings.get<string>(`Accounts_OAuth_${capitalize(service)}_id`), | ||
|
yash-rajpal marked this conversation as resolved.
|
||
| clientSecret: settings.get<string>(`Accounts_OAuth_${capitalize(service)}_secret`), | ||
| scope: OAuthConfigs[service].scope, | ||
| }; | ||
| }); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import { isTruthy } from '@rocket.chat/tools'; | ||
|
|
||
| import { OAuthConfigs } from './oauthConfigs'; | ||
| import { type ICachedSettings } from '../../../app/settings/server/CachedSettings'; | ||
|
|
||
| export const getOAuthServices = (settings: ICachedSettings) => { | ||
| const services = settings.getByRegexp(/^(Accounts_OAuth_|Accounts_OAuth_Custom-)[a-z0-9_]+$/i); | ||
| const filteredServices = services.filter(([, value]) => typeof value === 'boolean' && value === true); | ||
| return filteredServices | ||
| .map(([key, value]) => { | ||
| if (!value) { | ||
| return; | ||
| } | ||
|
|
||
| let serviceName = key.replace('Accounts_OAuth_', ''); | ||
| if (serviceName === 'Meteor') { | ||
| serviceName = 'meteor-developer'; | ||
| } | ||
| if (/Accounts_OAuth_Custom-/.test(key)) { | ||
| return; | ||
| } | ||
|
|
||
| const serviceKey = serviceName.toLowerCase(); | ||
|
|
||
| const oauthConfig = OAuthConfigs[serviceKey]; | ||
| if (!oauthConfig) { | ||
| return; | ||
| } | ||
|
|
||
| return serviceKey; | ||
| }) | ||
| .filter(isTruthy); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import type { Strategy } from 'passport'; | ||
| import { Strategy as FacebookStrategy } from 'passport-facebook'; | ||
| import { Strategy as GitHubStrategy } from 'passport-github2'; | ||
|
|
||
| export type OAuthConfig = { | ||
| strategy: new (...args: any[]) => Strategy; | ||
| scope: string[]; | ||
| }; | ||
|
|
||
| export const OAuthConfigs: Record<string, OAuthConfig> = { | ||
|
yash-rajpal marked this conversation as resolved.
|
||
| github: { | ||
| strategy: GitHubStrategy, | ||
| scope: ['user:email'], | ||
| }, | ||
| facebook: { | ||
| strategy: FacebookStrategy, | ||
| scope: ['email'], | ||
| }, | ||
| } as const; | ||
|
|
||
| export type Provider = keyof typeof OAuthConfigs; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.