LibreChat/api/strategies/facebookStrategy.js

39 lines
1.2 KiB
JavaScript
Raw Normal View History

const FacebookStrategy = require('passport-facebook').Strategy;
const socialLogin = require('./socialLogin');
feat: Auth and User System (#205) * server-side JWT auth implementation * move oauth routes and strategies, fix bugs * backend modifications for wiring up the frontend login and reg forms * Add frontend data services for login and registration * Add login and registration forms * Implment auth context, functional client side auth * protect routes with jwt auth * finish local strategy (using local storage) * Start setting up google auth * disable token refresh, remove old auth middleware * refactor client, add ApiErrorBoundary context * disable google and facebook strategies * fix: fix presets not displaying specific to user * fix: fix issue with browser refresh * fix: casing issue with User.js (#11) * delete user.js to be renamed * fix: fix casing issue with User.js * comment out api error watcher temporarily * fix: issue with api error watcher (#12) * delete user.js to be renamed * fix: fix casing issue with User.js * comment out api error watcher temporarily * feat: add google auth social login * fix: make google login url dynamic based on dev/prod * fix: bug where UI is briefly displayed before redirecting to login * fix: fix cookie expires value for local auth * Update README.md * Update LOCAL_INSTALL structure * Add local testing instructions * Only load google strategy if client id and secret are provided * Update .env.example files with new params * fix issue with not redirecting to register form * only show google login button if value is set in .env * cleanup log messages * Add label to button for google login on login form * doc: fix client/server url values in .env.example * feat: add error message details to registration failure * Restore preventing paste on confirm password * auto-login user after registering * feat: forgot password (#24) * make login/reg pages look like openai's * add password reset data services * new form designs similar to openai, add password reset pages * add api's for password reset * email utils for password reset * remove bcrypt salt rounds from process.env * refactor: restructure api auth code, consolidate routes (#25) * add api's for password reset * remove bcrypt salt rounds from process.env * refactor: consolidate auth routes, use controller pattern * refactor: code cleanup * feat: migrate data to first user (#26) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes after refactor (#27) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: issue with auto-login when logging out then logging in with new browser window (#28) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: fix issue with auto-login in new tab * doc: Update README and .env.example files with user system information (#29) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: fix issue with auto-login in new tab * doc: update README and .env.example files * Fixup: LOCAL_INSTALL.md PS instructions (#200) (#30) Co-authored-by: alfredo-f <alfredo.fomitchenko@mail.polimi.it> * feat: send user with completion to protect against abuse (#31) * Fixup: LOCAL_INSTALL.md PS instructions (#200) * server-side JWT auth implementation * move oauth routes and strategies, fix bugs * backend modifications for wiring up the frontend login and reg forms * Add frontend data services for login and registration * Add login and registration forms * Implment auth context, functional client side auth * protect routes with jwt auth * finish local strategy (using local storage) * Start setting up google auth * disable token refresh, remove old auth middleware * refactor client, add ApiErrorBoundary context * disable google and facebook strategies * fix: fix presets not displaying specific to user * fix: fix issue with browser refresh * fix: casing issue with User.js (#11) * delete user.js to be renamed * fix: fix casing issue with User.js * comment out api error watcher temporarily * feat: add google auth social login * fix: make google login url dynamic based on dev/prod * fix: bug where UI is briefly displayed before redirecting to login * fix: fix cookie expires value for local auth * Only load google strategy if client id and secret are provided * Update .env.example files with new params * fix issue with not redirecting to register form * only show google login button if value is set in .env * cleanup log messages * Add label to button for google login on login form * doc: fix client/server url values in .env.example * feat: add error message details to registration failure * Restore preventing paste on confirm password * auto-login user after registering * feat: forgot password (#24) * make login/reg pages look like openai's * add password reset data services * new form designs similar to openai, add password reset pages * add api's for password reset * email utils for password reset * remove bcrypt salt rounds from process.env * refactor: restructure api auth code, consolidate routes (#25) * add api's for password reset * remove bcrypt salt rounds from process.env * refactor: consolidate auth routes, use controller pattern * refactor: code cleanup * feat: migrate data to first user (#26) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes after refactor (#27) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: issue with auto-login when logging out then logging in with new browser window (#28) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: fix issue with auto-login in new tab * doc: Update README and .env.example files with user system information (#29) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: fix issue with auto-login in new tab * doc: update README and .env.example files * Send user id to openai to protect against abuse * add meilisearch to gitignore * Remove webpack --------- Co-authored-by: alfredo-f <alfredo.fomitchenko@mail.polimi.it> --------- Co-authored-by: Danny Avila <110412045+danny-avila@users.noreply.github.com> Co-authored-by: Alfredo Fomitchenko <alfredo.fomitchenko@mail.polimi.it>
2023-05-07 10:04:51 -07:00
const getProfileDetails = ({ profile }) => ({
email: profile.emails[0]?.value,
id: profile.id,
avatarUrl: profile.photos[0]?.value,
username: profile.displayName,
name: profile.name?.givenName + ' ' + profile.name?.familyName,
📧 feat: email verification (#2344) * feat: verification email * chore: email verification invalid; localize: update * fix: redirect to login when signup: fix: save emailVerified correctly * docs: update ALLOW_UNVERIFIED_EMAIL_LOGIN; fix: don't accept login only when ALLOW_UNVERIFIED_EMAIL_LOGIN = true * fix: user needs to be authenticated * style: update * fix: registration success message and redirect logic * refactor: use `isEnabled` in ALLOW_UNVERIFIED_EMAIL_LOGIN * refactor: move checkEmailConfig to server/utils * refactor: use req as param for verifyEmail function * chore: jsdoc * chore: remove console log * refactor: rename `createNewUser` to `createSocialUser` * refactor: update typing and add expiresAt field to userSchema * refactor: begin use of user methods over direct model access for User * refactor: initial email verification rewrite * chore: typing * refactor: registration flow rewrite * chore: remove help center text * refactor: update getUser to getUserById and add findUser methods. general fixes from recent changes * refactor: Update updateUser method to remove expiresAt field and use $set and $unset operations, createUser now returns Id only * refactor: Update openidStrategy to use optional chaining for avatar check, move saveBuffer init to buffer condition * refactor: logout on deleteUser mutatation * refactor: Update openidStrategy login success message format * refactor: Add emailVerified field to Discord and Facebook profile details * refactor: move limiters to separate middleware dir * refactor: Add limiters for email verification and password reset * refactor: Remove getUserController and update routes and controllers accordingly * refactor: Update getUserById method to exclude password and version fields * refactor: move verification to user route, add resend verification option * refactor: Improve email verification process and resend option * refactor: remove more direct model access of User and remove unused code * refactor: replace user authentication methods and token generation * fix: add user.id to jwt user * refactor: Update AuthContext to include setError function, add resend link to Login Form, make registration redirect shorter * fix(updateUserPluginsService): ensure userPlugins variable is defined * refactor: Delete all shared links for a specific user * fix: remove use of direct User.save() in handleExistingUser * fix(importLibreChatConvo): handle missing createdAt field in messages --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2024-06-07 21:06:47 +02:00
emailVerified: true,
});
const facebookLogin = socialLogin('facebook', getProfileDetails);
🔐 feat: Admin Auth Support for SAML and Social OAuth Providers (#12472) * refactor: Add existingUsersOnly support to social and SAML auth callbacks - Add `existingUsersOnly` option to the `socialLogin` handler factory to reject unknown users instead of creating new accounts - Refactor SAML strategy callback into `createSamlCallback(existingUsersOnly)` factory function, mirroring the OpenID `createOpenIDCallback` pattern - Extract shared SAML config into `getBaseSamlConfig()` helper - Register `samlAdmin` passport strategy with `existingUsersOnly: true` and admin-specific callback URL, called automatically from `setupSaml()` * feat: Register admin OAuth strategy variants for all social providers - Add admin strategy exports to Google, GitHub, Discord, Facebook, and Apple strategy files with admin callback URLs and existingUsersOnly - Extract provider configs into reusable helpers to avoid duplication between regular and admin strategy constructors - Re-export all admin strategy factories from strategies/index.js - Register admin passport strategies (googleAdmin, githubAdmin, etc.) alongside regular ones in socialLogins.js when env vars are present * feat: Add admin auth routes for SAML and social OAuth providers - Add initiation and callback routes for SAML, Google, GitHub, Discord, Facebook, and Apple to the admin auth router - Each provider follows the exchange code + PKCE pattern established by OpenID admin auth: store PKCE challenge on initiation, retrieve on callback, generate exchange code for the admin panel - SAML and Apple use POST callbacks with state extracted from req.body.RelayState and req.body.state respectively - Extract storePkceChallenge(), retrievePkceChallenge(), and generateState() helpers; refactor existing OpenID routes to use them - All callback chains enforce requireAdminAccess, setBalanceConfig, checkDomainAllowed, and the shared createOAuthHandler - No changes needed to the generic POST /oauth/exchange endpoint * fix: Update SAML strategy test to handle dual strategy registration setupSaml() now registers both 'saml' and 'samlAdmin' strategies, causing the SamlStrategy mock to be called twice. The verifyCallback variable was getting overwritten with the admin callback (which has existingUsersOnly: true), making all new-user tests fail. Fix: capture only the first callback per setupSaml() call and reset between tests. * fix: Address review findings for admin OAuth strategy changes - Fix existingUsersOnly rejection in socialLogin.js to use cb(null, false, { message }) instead of cb(error), ensuring passport's failureRedirect fires correctly for admin flows - Consolidate duplicate require() calls in strategies/index.js by destructuring admin exports from the already-imported default export - Pass pre-parsed baseConfig to setupSamlAdmin() to avoid redundant certificate file I/O at startup - Extract getGoogleConfig() helper in googleStrategy.js for consistency with all other provider strategy files - Replace randomState() (openid-client) with generateState() (crypto) in the OpenID admin route for consistency with all other providers, and remove the now-unused openid-client import * Reorder import statements in auth.js
2026-03-30 22:49:44 -04:00
const facebookAdminLogin = socialLogin('facebook', getProfileDetails, { existingUsersOnly: true });
🔐 feat: Admin Auth Support for SAML and Social OAuth Providers (#12472) * refactor: Add existingUsersOnly support to social and SAML auth callbacks - Add `existingUsersOnly` option to the `socialLogin` handler factory to reject unknown users instead of creating new accounts - Refactor SAML strategy callback into `createSamlCallback(existingUsersOnly)` factory function, mirroring the OpenID `createOpenIDCallback` pattern - Extract shared SAML config into `getBaseSamlConfig()` helper - Register `samlAdmin` passport strategy with `existingUsersOnly: true` and admin-specific callback URL, called automatically from `setupSaml()` * feat: Register admin OAuth strategy variants for all social providers - Add admin strategy exports to Google, GitHub, Discord, Facebook, and Apple strategy files with admin callback URLs and existingUsersOnly - Extract provider configs into reusable helpers to avoid duplication between regular and admin strategy constructors - Re-export all admin strategy factories from strategies/index.js - Register admin passport strategies (googleAdmin, githubAdmin, etc.) alongside regular ones in socialLogins.js when env vars are present * feat: Add admin auth routes for SAML and social OAuth providers - Add initiation and callback routes for SAML, Google, GitHub, Discord, Facebook, and Apple to the admin auth router - Each provider follows the exchange code + PKCE pattern established by OpenID admin auth: store PKCE challenge on initiation, retrieve on callback, generate exchange code for the admin panel - SAML and Apple use POST callbacks with state extracted from req.body.RelayState and req.body.state respectively - Extract storePkceChallenge(), retrievePkceChallenge(), and generateState() helpers; refactor existing OpenID routes to use them - All callback chains enforce requireAdminAccess, setBalanceConfig, checkDomainAllowed, and the shared createOAuthHandler - No changes needed to the generic POST /oauth/exchange endpoint * fix: Update SAML strategy test to handle dual strategy registration setupSaml() now registers both 'saml' and 'samlAdmin' strategies, causing the SamlStrategy mock to be called twice. The verifyCallback variable was getting overwritten with the admin callback (which has existingUsersOnly: true), making all new-user tests fail. Fix: capture only the first callback per setupSaml() call and reset between tests. * fix: Address review findings for admin OAuth strategy changes - Fix existingUsersOnly rejection in socialLogin.js to use cb(null, false, { message }) instead of cb(error), ensuring passport's failureRedirect fires correctly for admin flows - Consolidate duplicate require() calls in strategies/index.js by destructuring admin exports from the already-imported default export - Pass pre-parsed baseConfig to setupSamlAdmin() to avoid redundant certificate file I/O at startup - Extract getGoogleConfig() helper in googleStrategy.js for consistency with all other provider strategy files - Replace randomState() (openid-client) with generateState() (crypto) in the OpenID admin route for consistency with all other providers, and remove the now-unused openid-client import * Reorder import statements in auth.js
2026-03-30 22:49:44 -04:00
const getFacebookConfig = (callbackURL) => ({
clientID: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
callbackURL,
proxy: true,
scope: ['public_profile'],
profileFields: ['id', 'email', 'name'],
});
const facebookStrategy = () =>
new FacebookStrategy(
🔐 feat: Admin Auth Support for SAML and Social OAuth Providers (#12472) * refactor: Add existingUsersOnly support to social and SAML auth callbacks - Add `existingUsersOnly` option to the `socialLogin` handler factory to reject unknown users instead of creating new accounts - Refactor SAML strategy callback into `createSamlCallback(existingUsersOnly)` factory function, mirroring the OpenID `createOpenIDCallback` pattern - Extract shared SAML config into `getBaseSamlConfig()` helper - Register `samlAdmin` passport strategy with `existingUsersOnly: true` and admin-specific callback URL, called automatically from `setupSaml()` * feat: Register admin OAuth strategy variants for all social providers - Add admin strategy exports to Google, GitHub, Discord, Facebook, and Apple strategy files with admin callback URLs and existingUsersOnly - Extract provider configs into reusable helpers to avoid duplication between regular and admin strategy constructors - Re-export all admin strategy factories from strategies/index.js - Register admin passport strategies (googleAdmin, githubAdmin, etc.) alongside regular ones in socialLogins.js when env vars are present * feat: Add admin auth routes for SAML and social OAuth providers - Add initiation and callback routes for SAML, Google, GitHub, Discord, Facebook, and Apple to the admin auth router - Each provider follows the exchange code + PKCE pattern established by OpenID admin auth: store PKCE challenge on initiation, retrieve on callback, generate exchange code for the admin panel - SAML and Apple use POST callbacks with state extracted from req.body.RelayState and req.body.state respectively - Extract storePkceChallenge(), retrievePkceChallenge(), and generateState() helpers; refactor existing OpenID routes to use them - All callback chains enforce requireAdminAccess, setBalanceConfig, checkDomainAllowed, and the shared createOAuthHandler - No changes needed to the generic POST /oauth/exchange endpoint * fix: Update SAML strategy test to handle dual strategy registration setupSaml() now registers both 'saml' and 'samlAdmin' strategies, causing the SamlStrategy mock to be called twice. The verifyCallback variable was getting overwritten with the admin callback (which has existingUsersOnly: true), making all new-user tests fail. Fix: capture only the first callback per setupSaml() call and reset between tests. * fix: Address review findings for admin OAuth strategy changes - Fix existingUsersOnly rejection in socialLogin.js to use cb(null, false, { message }) instead of cb(error), ensuring passport's failureRedirect fires correctly for admin flows - Consolidate duplicate require() calls in strategies/index.js by destructuring admin exports from the already-imported default export - Pass pre-parsed baseConfig to setupSamlAdmin() to avoid redundant certificate file I/O at startup - Extract getGoogleConfig() helper in googleStrategy.js for consistency with all other provider strategy files - Replace randomState() (openid-client) with generateState() (crypto) in the OpenID admin route for consistency with all other providers, and remove the now-unused openid-client import * Reorder import statements in auth.js
2026-03-30 22:49:44 -04:00
getFacebookConfig(`${process.env.DOMAIN_SERVER}${process.env.FACEBOOK_CALLBACK_URL}`),
facebookLogin,
);
🔐 feat: Admin Auth Support for SAML and Social OAuth Providers (#12472) * refactor: Add existingUsersOnly support to social and SAML auth callbacks - Add `existingUsersOnly` option to the `socialLogin` handler factory to reject unknown users instead of creating new accounts - Refactor SAML strategy callback into `createSamlCallback(existingUsersOnly)` factory function, mirroring the OpenID `createOpenIDCallback` pattern - Extract shared SAML config into `getBaseSamlConfig()` helper - Register `samlAdmin` passport strategy with `existingUsersOnly: true` and admin-specific callback URL, called automatically from `setupSaml()` * feat: Register admin OAuth strategy variants for all social providers - Add admin strategy exports to Google, GitHub, Discord, Facebook, and Apple strategy files with admin callback URLs and existingUsersOnly - Extract provider configs into reusable helpers to avoid duplication between regular and admin strategy constructors - Re-export all admin strategy factories from strategies/index.js - Register admin passport strategies (googleAdmin, githubAdmin, etc.) alongside regular ones in socialLogins.js when env vars are present * feat: Add admin auth routes for SAML and social OAuth providers - Add initiation and callback routes for SAML, Google, GitHub, Discord, Facebook, and Apple to the admin auth router - Each provider follows the exchange code + PKCE pattern established by OpenID admin auth: store PKCE challenge on initiation, retrieve on callback, generate exchange code for the admin panel - SAML and Apple use POST callbacks with state extracted from req.body.RelayState and req.body.state respectively - Extract storePkceChallenge(), retrievePkceChallenge(), and generateState() helpers; refactor existing OpenID routes to use them - All callback chains enforce requireAdminAccess, setBalanceConfig, checkDomainAllowed, and the shared createOAuthHandler - No changes needed to the generic POST /oauth/exchange endpoint * fix: Update SAML strategy test to handle dual strategy registration setupSaml() now registers both 'saml' and 'samlAdmin' strategies, causing the SamlStrategy mock to be called twice. The verifyCallback variable was getting overwritten with the admin callback (which has existingUsersOnly: true), making all new-user tests fail. Fix: capture only the first callback per setupSaml() call and reset between tests. * fix: Address review findings for admin OAuth strategy changes - Fix existingUsersOnly rejection in socialLogin.js to use cb(null, false, { message }) instead of cb(error), ensuring passport's failureRedirect fires correctly for admin flows - Consolidate duplicate require() calls in strategies/index.js by destructuring admin exports from the already-imported default export - Pass pre-parsed baseConfig to setupSamlAdmin() to avoid redundant certificate file I/O at startup - Extract getGoogleConfig() helper in googleStrategy.js for consistency with all other provider strategy files - Replace randomState() (openid-client) with generateState() (crypto) in the OpenID admin route for consistency with all other providers, and remove the now-unused openid-client import * Reorder import statements in auth.js
2026-03-30 22:49:44 -04:00
const facebookAdminStrategy = () =>
new FacebookStrategy(
getFacebookConfig(`${process.env.DOMAIN_SERVER}/api/admin/oauth/facebook/callback`),
facebookAdminLogin,
);
module.exports = facebookStrategy;
module.exports.facebookAdminLogin = facebookAdminStrategy;