Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

Add external id support for auth plugins

Chocobozzzc46e430b591b
diff --git a/packages/tests/fixtures/peertube-plugin-test-external-auth-four/main.js b/packages/tests/fixtures/peertube-plugin-test-external-auth-four/main.js
new file mode 100644
index 0000000000..95a6abf39a
--- /dev/null
+++ b/packages/tests/fixtures/peertube-plugin-test-external-auth-four/main.js
@@ -0,0 +1,46 @@
+async function register ({
+ registerExternalAuth
+}) {
+ {
+ const result = registerExternalAuth({
+ authName: 'external-auth-id-1',
+ authDisplayName: () => 'External Auth Id 1',
+ onAuthRequest: (req, res) => {
+ result.userAuthenticated({
+ req,
+ res,
+ username: req.query.username,
+ email: req.query.email,
+ externalId: req.query.externalId || undefined
+ })
+ }
+ })
+ }
+
+ {
+ const result = registerExternalAuth({
+ authName: 'external-auth-id-2',
+ authDisplayName: () => 'External Auth Id 2',
+ onAuthRequest: (req, res) => {
+ result.userAuthenticated({
+ req,
+ res,
+ username: req.query.username,
+ email: req.query.email,
+ externalId: req.query.externalId || undefined
+ })
+ }
+ })
+ }
+}
+
+async function unregister () {
+ return
+}
+
+module.exports = {
+ register,
+ unregister
+}
+
+// ###########################################################################
diff --git a/packages/tests/fixtures/peertube-plugin-test-external-auth-four/package.json b/packages/tests/fixtures/peertube-plugin-test-external-auth-four/package.json
new file mode 100644
index 0000000000..7ea60c8a45
--- /dev/null
+++ b/packages/tests/fixtures/peertube-plugin-test-external-auth-four/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "peertube-plugin-test-external-auth-four",
+ "version": "0.0.1",
+ "description": "External auth four (stable external id)",
+ "engine": {
+ "peertube": ">=1.3.0"
+ },
+ "keywords": [
+ "peertube",
+ "plugin"
+ ],
+ "homepage": "https://github.com/Chocobozzz/PeerTube",
+ "author": "Chocobozzz",
+ "bugs": "https://github.com/Chocobozzz/PeerTube/issues",
+ "library": "./main.js",
+ "staticDirs": {},
+ "css": [],
+ "clientScripts": [],
+ "translations": {}
+}
diff --git a/packages/tests/src/plugins/external-auth-external-id.ts b/packages/tests/src/plugins/external-auth-external-id.ts
new file mode 100644
index 0000000000..3d8d725d0c
--- /dev/null
+++ b/packages/tests/src/plugins/external-auth-external-id.ts
@@ -0,0 +1,140 @@
+/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+
+import { HttpStatusCode } from '@peertube/peertube-models'
+import {
+ cleanupTests,
+ createSingleServer,
+ PeerTubeServer,
+ PluginsCommand,
+ setAccessTokensToServers
+} from '@peertube/peertube-server-commands'
+import { loginExternal } from '@tests/shared/plugins.js'
+import { SQLCommand } from '@tests/shared/sql-command.js'
+import { expect } from 'chai'
+
+describe('Test external auth plugins with a stable external id', function () {
+ let server: PeerTubeServer
+
+ let terraId: number
+ let terraToken: string
+
+ before(async function () {
+ this.timeout(30000)
+
+ server = await createSingleServer(1)
+
+ await setAccessTokensToServers([ server ])
+
+ await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-external-auth-four') })
+ })
+
+ it('Should create a new user using a stable external id', async function () {
+ const body = await loginExternal({
+ server,
+ authName: 'external-auth-id-1',
+ npmName: 'test-external-auth-four',
+ username: 'terra',
+ query: {
+ username: 'terra',
+ email: '[email protected]',
+ externalId: 'terra-external-id'
+ }
+ })
+
+ terraToken = body.access_token
+
+ const me = await server.users.getMyInfo({ token: terraToken })
+ terraId = me.id
+ expect(me.username).to.equal('terra')
+ expect(me.email).to.equal('[email protected]')
+ })
+
+ it('Should reuse the same account and sync the email when it changes at the identity provider', async function () {
+ const body = await loginExternal({
+ server,
+ authName: 'external-auth-id-1',
+ npmName: 'test-external-auth-four',
+ username: 'terra',
+ query: {
+ username: 'terra',
+ email: '[email protected]',
+ externalId: 'terra-external-id'
+ }
+ })
+
+ terraToken = body.access_token
+
+ const me = await server.users.getMyInfo({ token: terraToken })
+ expect(me.id).to.equal(terraId)
+ expect(me.email).to.equal('[email protected]')
+ })
+
+ it('Should backfill the external id for an previously created account that did not have an externalId', async function () {
+ const sqlCommand = new SQLCommand(server)
+
+ await loginExternal({
+ server,
+ authName: 'external-auth-id-2',
+ npmName: 'test-external-auth-four',
+ username: 'luna',
+ query: {
+ username: 'luna',
+ }
+ })
+
+ expect(await sqlCommand.getUserExternalId('luna')).to.not.exist
+
+ await loginExternal({
+ server,
+ authName: 'external-auth-id-2',
+ npmName: 'test-external-auth-four',
+ username: 'luna',
+ query: {
+ username: 'luna',
+ email: '[email protected]',
+ externalId: 'luna-external-id'
+ }
+ })
+
+ expect(await sqlCommand.getUserExternalId('luna')).to.equal('luna-external-id')
+
+ await sqlCommand.cleanup()
+ })
+
+ it('Should reject login when the account is already linked to a different external id for the same auth strategy', async function () {
+ await loginExternal({
+ server,
+ authName: 'external-auth-id-1',
+ npmName: 'test-external-auth-four',
+ username: 'terra',
+ query: {
+ username: 'terra',
+ email: '[email protected]',
+ externalId: 'a-completely-different-external-id'
+ },
+ expectedStatusStep2: HttpStatusCode.BAD_REQUEST_400
+ })
+ })
+
+ it('Should still allow login with the original external id after a rejected collision attempt', async function () {
+ const body = await loginExternal({
+ server,
+ authName: 'external-auth-id-1',
+ npmName: 'test-external-auth-four',
+ username: 'terra',
+ query: {
+ username: 'terra',
+ email: '[email protected]',
+ externalId: 'terra-external-id'
+ }
+ })
+
+ const me = await server.users.getMyInfo({ token: body.access_token })
+ expect(me.id).to.equal(terraId)
+ })
+
+ after(async function () {
+ await cleanupTests([ server ])
+ })
+})
diff --git a/packages/tests/src/plugins/external-auth.ts b/packages/tests/src/plugins/external-auth.ts
index 0830da798b..9fd2cb4a73 100644
--- a/packages/tests/src/plugins/external-auth.ts
+++ b/packages/tests/src/plugins/external-auth.ts
@@ -1,7 +1,7 @@
/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
import { wait } from '@peertube/peertube-core-utils'
-import { HttpStatusCode, HttpStatusCodeType, UserAdminFlag, UserRole } from '@peertube/peertube-models'
+import { HttpStatusCode, UserAdminFlag, UserRole } from '@peertube/peertube-models'
import {
cleanupTests,
createSingleServer,
@@ -10,52 +10,9 @@ import {
PluginsCommand,
setAccessTokensToServers
} from '@peertube/peertube-server-commands'
+import { fetchExternalToken, loginExternal } from '@tests/shared/plugins.js'
import { expect } from 'chai'
-async function loginExternal (options: {
- server: PeerTubeServer
- npmName: string
- authName: string
- username: string
- query?: any
- expectedStatus?: HttpStatusCodeType
- expectedStatusStep2?: HttpStatusCodeType
-}) {
- const externalAuthToken = await fetchExternalToken(options)
- if (!externalAuthToken) return
-
- const resLogin = await options.server.login.loginUsingExternalToken({
- username: options.username,
- externalAuthToken,
- expectedStatus: options.expectedStatusStep2
- })
-
- return resLogin.body
-}
-
-async function fetchExternalToken (options: {
- server: PeerTubeServer
- npmName: string
- authName: string
- query?: any
- expectedStatus?: HttpStatusCodeType
-}) {
- const res = await options.server.plugins.getExternalAuth({
- npmName: options.npmName,
- npmVersion: '0.0.1',
- authName: options.authName,
- query: options.query,
- expectedStatus: options.expectedStatus || HttpStatusCode.FOUND_302
- })
-
- if (res.status !== HttpStatusCode.FOUND_302) return undefined
-
- const location = res.header.location
- const { externalAuthToken } = decodeQueryString(location)
-
- return externalAuthToken as string
-}
-
describe('Test external auth plugins', function () {
let server: PeerTubeServer
diff --git a/packages/tests/src/shared/plugins.ts b/packages/tests/src/shared/plugins.ts
index 4b2ddf9f80..f0098779ff 100644
--- a/packages/tests/src/shared/plugins.ts
+++ b/packages/tests/src/shared/plugins.ts
@@ -1,9 +1,10 @@
/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+import { HttpStatusCode, HttpStatusCodeType } from '@peertube/peertube-models'
+import { decodeQueryString, PeerTubeServer } from '@peertube/peertube-server-commands'
import { expect } from 'chai'
-import { PeerTubeServer } from '@peertube/peertube-server-commands'
-async function testHelloWorldRegisteredSettings (server: PeerTubeServer) {
+export async function testHelloWorldRegisteredSettings (server: PeerTubeServer) {
const body = await server.plugins.getRegisteredSettings({ npmName: 'peertube-plugin-hello-world' })
const registeredSettings = body.registeredSettings
@@ -13,6 +14,46 @@ async function testHelloWorldRegisteredSettings (server: PeerTubeServer) {
expect(adminNameSettings).to.not.be.undefined
}
-export {
- testHelloWorldRegisteredSettings
+export async function loginExternal (options: {
+ server: PeerTubeServer
+ npmName: string
+ authName: string
+ username: string
+ query?: any
+ expectedStatus?: HttpStatusCodeType
+ expectedStatusStep2?: HttpStatusCodeType
+}) {
+ const externalAuthToken = await fetchExternalToken(options)
+ if (!externalAuthToken) return
+
+ const resLogin = await options.server.login.loginUsingExternalToken({
+ username: options.username,
+ externalAuthToken,
+ expectedStatus: options.expectedStatusStep2
+ })
+
+ return resLogin.body
+}
+
+export async function fetchExternalToken (options: {
+ server: PeerTubeServer
+ npmName: string
+ authName: string
+ query?: Record<string, string>
+ expectedStatus?: HttpStatusCodeType
+}) {
+ const res = await options.server.plugins.getExternalAuth({
+ npmName: options.npmName,
+ npmVersion: '0.0.1',
+ authName: options.authName,
+ query: options.query,
+ expectedStatus: options.expectedStatus || HttpStatusCode.FOUND_302
+ })
+
+ if (res.status !== HttpStatusCode.FOUND_302) return undefined
+
+ const location = res.header.location
+ const { externalAuthToken } = decodeQueryString(location)
+
+ return externalAuthToken as string
}
diff --git a/packages/tests/src/shared/sql-command.ts b/packages/tests/src/shared/sql-command.ts
index 067371b620..de9d848ee3 100644
--- a/packages/tests/src/shared/sql-command.ts
+++ b/packages/tests/src/shared/sql-command.ts
@@ -107,6 +107,15 @@ export class SQLCommand {
await this.updateQuery(`UPDATE "user" SET email = :email WHERE "username" = :username`, { email, username })
}
+ async getUserExternalId (username: string) {
+ const rows = await this.selectQuery<{ pluginAuthExternalId: string }>(
+ `SELECT "pluginAuthExternalId" FROM "user" WHERE "username" = :username`,
+ { username }
+ )
+
+ return rows[0]?.pluginAuthExternalId
+ }
+
// ---------------------------------------------------------------------------
async setImportUrl (videoImportId: number, importUrl: string) {
diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.ts
index 4d4506d972..fc804b0d95 100644
--- a/server/core/initializers/constants.ts
+++ b/server/core/initializers/constants.ts
@@ -62,7 +62,7 @@ import { CONFIG, registerConfigChangedHandler } from './config.js'
// ---------------------------------------------------------------------------
-export const LAST_MIGRATION_VERSION = 1070
+export const LAST_MIGRATION_VERSION = 1075
// ---------------------------------------------------------------------------
diff --git a/server/core/initializers/migrations/1075-add-user-plugin-auth-external-id.ts b/server/core/initializers/migrations/1075-add-user-plugin-auth-external-id.ts
new file mode 100644
index 0000000000..c70949dae2
--- /dev/null
+++ b/server/core/initializers/migrations/1075-add-user-plugin-auth-external-id.ts
@@ -0,0 +1,24 @@
+import * as Sequelize from 'sequelize'
+
+async function up (utils: {
+ transaction: Sequelize.Transaction
+ queryInterface: Sequelize.QueryInterface
+ sequelize: Sequelize.Sequelize
+}): Promise<void> {
+ const { transaction } = utils
+
+ await utils.queryInterface.addColumn('user', 'pluginAuthExternalId', {
+ type: Sequelize.STRING(255),
+ allowNull: true,
+ defaultValue: null
+ }, { transaction })
+}
+
+function down () {
+ throw new Error('Not implemented.')
+}
+
+export {
+ down,
+ up
+}
diff --git a/server/core/lib/auth/external-auth.ts b/server/core/lib/auth/external-auth.ts
index 7883b4c27d..3554cb6abd 100644
--- a/server/core/lib/auth/external-auth.ts
+++ b/server/core/lib/auth/external-auth.ts
@@ -23,7 +23,7 @@ import { isDevInstance } from '@peertube/peertube-node-utils'
export type ExternalUser =
& Pick<MUser, 'username' | 'email' | 'role' | 'adminFlags' | 'videoQuotaDaily' | 'videoQuota'>
- & { displayName: string }
+ & { displayName: string, externalId?: string }
// Token is the key, expiration date is the value
const authBypassTokens = new Map<string, {
@@ -227,6 +227,10 @@ function isAuthResultValid (npmName: string, authName: string, result: RegisterS
return false
}
+ if (result.externalId && (typeof result.externalId !== 'string' || result.externalId.length > 255)) {
+ return returnError('externalId')
+ }
+
return true
}
@@ -240,7 +244,9 @@ function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
adminFlags: pluginResult.adminFlags ?? UserAdminFlag.NONE,
videoQuota: pluginResult.videoQuota,
- videoQuotaDaily: pluginResult.videoQuotaDaily
+ videoQuotaDaily: pluginResult.videoQuotaDaily,
+
+ externalId: pluginResult.externalId || undefined
}
}
diff --git a/server/core/lib/auth/oauth-model.ts b/server/core/lib/auth/oauth-model.ts
index 190c3c1f5c..d5aa25c2ae 100644
--- a/server/core/lib/auth/oauth-model.ts
+++ b/server/core/lib/auth/oauth-model.ts
@@ -1,5 +1,5 @@
import { AccessDeniedError } from '@node-oauth/oauth2-server'
-import { pick, maskSecret } from '@peertube/peertube-core-utils'
+import { maskSecret, pick } from '@peertube/peertube-core-utils'
import { AttributesOnly } from '@peertube/peertube-typescript-utils'
import { isUserPasswordTooLong } from '@server/helpers/custom-validators/users.js'
import { PluginManager } from '@server/lib/plugins/plugin-manager.js'
@@ -102,26 +102,19 @@ async function getUser (usernameOrEmail?: string, password?: string, options?: {
if (bypassLogin?.bypass === true) {
logger.info('Bypassing oauth login by plugin %s.', bypassLogin.pluginName)
- let user = getByEmailPermissive(await UserModel.loadByEmailCaseInsensitive(bypassLogin.user.email), bypassLogin.user.email)
+ const { pluginName, user: externalUser, userUpdater } = bypassLogin
- if (!user) {
- user = await createUserFromExternal(bypassLogin.pluginName, bypassLogin.user)
- } else if (user.pluginAuth === bypassLogin.pluginName) {
- user = await updateUserFromExternal(user, bypassLogin.user, bypassLogin.userUpdater)
- }
-
- // Cannot create a user
- if (!user) throw new AccessDeniedError(req.t('Cannot create such user: an actor with that name already exists.'))
+ const user = await findExternalUserOrThrow({ externalUser, pluginName, userUpdater, req })
// If the user does not belongs to a plugin, it was created before its installation
// Then we just go through a regular login process
if (user.pluginAuth !== null) {
// This user does not belong to this plugin, skip it
- if (user.pluginAuth !== bypassLogin.pluginName) {
+ if (user.pluginAuth !== pluginName) {
logger.info(
'Cannot bypass oauth login by plugin %s because %s has another plugin auth method (%s).',
- bypassLogin.pluginName,
- bypassLogin.user.email,
+ pluginName,
+ externalUser.email,
user.pluginAuth
)
@@ -266,6 +259,45 @@ export {
// ---------------------------------------------------------------------------
+async function findExternalUserOrThrow (options: {
+ externalUser: ExternalUser
+ pluginName: string
+ userUpdater: RegisterServerAuthenticatedResult['userUpdater']
+ req: express.Request
+}): Promise<MUserDefault> {
+ const { externalUser, pluginName, userUpdater, req } = options
+
+ if (externalUser.externalId) {
+ const userByExternalId = await UserModel.loadByPluginAuthExternalId(pluginName, externalUser.externalId)
+
+ if (userByExternalId) {
+ // Authoritative match by stable external id: trust it even if the email changed at the identity provider
+ return updateUserFromExternal({ user: userByExternalId, userOptions: externalUser, userUpdater, syncEmail: true })
+ }
+ }
+
+ // Plugin does not supply a stable external id: unchanged email-only behavior
+ const userByEmail = getByEmailPermissive(await UserModel.loadByEmailCaseInsensitive(externalUser.email), externalUser.email)
+ if (!userByEmail) return createUserFromExternal(pluginName, externalUser)
+
+ if (userByEmail.pluginAuth === pluginName) {
+ if (externalUser.externalId && userByEmail.pluginAuthExternalId !== null) {
+ // This account is already linked to a different external id for this plugin
+ // Refuse to silently relink (identity provider email reuse, or a possible hijack attempt)
+ throw new AccessDeniedError(
+ req.t(
+ `Refusing external auth bypass for plugin {pluginName}: {email} is already linked to a different external id.`,
+ { pluginName, email: externalUser.email }
+ )
+ )
+ }
+
+ return updateUserFromExternal({ user: userByEmail, userOptions: externalUser, userUpdater, syncEmail: false })
+ }
+
+ return userByEmail
+}
+
async function createUserFromExternal (pluginAuth: string, userOptions: ExternalUser) {
const username = await findAvailableLocalActorName(userOptions.username)
@@ -275,7 +307,8 @@ async function createUserFromExternal (pluginAuth: string, userOptions: External
username,
emailVerified: null,
password: null,
- pluginAuth
+ pluginAuth,
+ pluginAuthExternalId: userOptions.externalId
})
const { user } = await createUserAccountAndChannelAndPlaylist({
@@ -286,45 +319,58 @@ async function createUserFromExternal (pluginAuth: string, userOptions: External
return user
}
-async function updateUserFromExternal (
- user: MUserDefault,
- userOptions: ExternalUser,
+async function updateUserFromExternal (options: {
+ user: MUserDefault
+ userOptions: ExternalUser
userUpdater: RegisterServerAuthenticatedResult['userUpdater']
-) {
- if (!userUpdater) return user
-
- {
- type UserAttributeKeys = keyof AttributesOnly<UserModel>
- const mappingKeys: { [id in UserAttributeKeys]?: AuthenticatedResultUpdaterFieldName } = {
- role: 'role',
- adminFlags: 'adminFlags',
- videoQuota: 'videoQuota',
- videoQuotaDaily: 'videoQuotaDaily'
- }
+ syncEmail: boolean
+}) {
+ const { user, userOptions, userUpdater, syncEmail } = options
+
+ if (userUpdater) {
+ {
+ type UserAttributeKeys = keyof AttributesOnly<UserModel>
+ const mappingKeys: { [id in UserAttributeKeys]?: AuthenticatedResultUpdaterFieldName } = {
+ role: 'role',
+ adminFlags: 'adminFlags',
+ videoQuota: 'videoQuota',
+ videoQuotaDaily: 'videoQuotaDaily'
+ }
- for (const modelKey of Object.keys(mappingKeys)) {
- const pluginOptionKey = mappingKeys[modelKey]
+ for (const modelKey of Object.keys(mappingKeys)) {
+ const pluginOptionKey = mappingKeys[modelKey]
- const newValue = userUpdater({ fieldName: pluginOptionKey, currentValue: user[modelKey], newValue: userOptions[pluginOptionKey] })
- user.set(modelKey, newValue)
+ const newValue = userUpdater({ fieldName: pluginOptionKey, currentValue: user[modelKey], newValue: userOptions[pluginOptionKey] })
+ user.set(modelKey, newValue)
+ }
}
- }
- {
- type AccountAttributeKeys = keyof Partial<AttributesOnly<AccountModel>>
- const mappingKeys: { [id in AccountAttributeKeys]?: AuthenticatedResultUpdaterFieldName } = {
- name: 'displayName'
- }
+ {
+ type AccountAttributeKeys = keyof Partial<AttributesOnly<AccountModel>>
+ const mappingKeys: { [id in AccountAttributeKeys]?: AuthenticatedResultUpdaterFieldName } = {
+ name: 'displayName'
+ }
- for (const modelKey of Object.keys(mappingKeys)) {
- const optionKey = mappingKeys[modelKey]
+ for (const modelKey of Object.keys(mappingKeys)) {
+ const optionKey = mappingKeys[modelKey]
- const newValue = userUpdater({ fieldName: optionKey, currentValue: user.Account[modelKey], newValue: userOptions[optionKey] })
- user.Account.set(modelKey, newValue)
+ const newValue = userUpdater({ fieldName: optionKey, currentValue: user.Account[modelKey], newValue: userOptions[optionKey] })
+ user.Account.set(modelKey, newValue)
+ }
}
+
+ logger.debug('Updated user %s with plugin userUpdated function.', user.email, { user, userOptions })
}
- logger.debug('Updated user %s with plugin userUpdated function.', user.email, { user, userOptions })
+ if (userOptions.externalId && user.pluginAuthExternalId !== userOptions.externalId) {
+ logger.info('Linking external id for user %s (plugin %s).', user.email, user.pluginAuth)
+ user.set('pluginAuthExternalId', userOptions.externalId)
+ }
+
+ if (syncEmail && userOptions.email && user.email !== userOptions.email) {
+ logger.info('Updating email of user %s to %s after successful external auth.', user.email, userOptions.email)
+ user.email = userOptions.email
+ }
user.Account = await user.Account.save()
diff --git a/server/core/lib/user.ts b/server/core/lib/user.ts
index f7f462e6a0..7a567b2b4e 100644
--- a/server/core/lib/user.ts
+++ b/server/core/lib/user.ts
@@ -44,6 +44,7 @@ export function buildUser (options: {
videoQuotaDaily?: number // Default to CONFIG.USER.VIDEO_QUOTA_DAILY
pluginAuth?: string
+ pluginAuthExternalId?: string
}): MUser {
const {
username,
@@ -54,7 +55,8 @@ export function buildUser (options: {
videoQuota = CONFIG.USER.VIDEO_QUOTA,
videoQuotaDaily = CONFIG.USER.VIDEO_QUOTA_DAILY,
adminFlags = UserAdminFlag.NONE,
- pluginAuth
+ pluginAuth,
+ pluginAuthExternalId
} = options
return new UserModel({
@@ -77,6 +79,7 @@ export function buildUser (options: {
videoQuotaDaily,
pluginAuth,
+ pluginAuthExternalId,
newFeaturesInfoRead: Object.values(UserNewFeatureInfo).reduce((all, curr) => all | curr, 0)
})
diff --git a/server/core/models/user/user.ts b/server/core/models/user/user.ts
index 625d7facd9..de80d53499 100644
--- a/server/core/models/user/user.ts
+++ b/server/core/models/user/user.ts
@@ -249,6 +249,15 @@ type WhereUserIdScopeOptions = { whereUserId?: '$userId' | '"UserModel"."id"' }
{
fields: [ 'email' ],
unique: true
+ },
+ {
+ fields: [ 'pluginAuth', 'pluginAuthExternalId' ],
+ unique: true,
+ where: {
+ pluginAuthExternalId: {
+ [Op.ne]: null
+ }
+ }
}
]
})
@@ -423,6 +432,13 @@ export class UserModel extends SequelizeModel<UserModel> {
@Column
declare pluginAuth: string
+ // Stable identifier of this user at the plugin's identity provider (OIDC `sub` claim, SAML `NameID`...)
+ // Scoped by `pluginAuth`. Nullable so it can stay unset for local accounts and for plugins that don't send it
+ @AllowNull(true)
+ @Default(null)
+ @Column(DataType.STRING(255))
+ declare pluginAuthExternalId: string
+
@AllowNull(false)
@Default(DataType.UUIDV4)
@IsUUID(4)
@@ -727,6 +743,17 @@ export class UserModel extends SequelizeModel<UserModel> {
return UserModel.findAll(query)
}
+ static loadByPluginAuthExternalId (pluginAuth: string, pluginAuthExternalId: string): Promise<MUserDefault> {
+ const query = {
+ where: {
+ pluginAuth,
+ pluginAuthExternalId
+ }
+ }
+
+ return UserModel.findOne(query)
+ }
+
static loadByPendingEmailCaseInsensitive (pendingEmail: string): Promise<MUserDefault[]> {
const query = {
where: where(
diff --git a/server/core/types/plugins/register-server-auth.model.ts b/server/core/types/plugins/register-server-auth.model.ts
index e358f270a1..86be203110 100644
--- a/server/core/types/plugins/register-server-auth.model.ts
+++ b/server/core/types/plugins/register-server-auth.model.ts
@@ -21,6 +21,13 @@ export interface RegisterServerAuthenticatedResult {
role?: UserRoleType
displayName?: string
+ // Stable identifier of this user at the identity provider (OIDC `sub` claim, SAML `NameID`, LDAP `uid`/`entryUUID`...)
+ // When provided, PeerTube links/looks up the local account using this id instead of relying only on the email
+ // address, which is more robust across identity provider email changes and avoids account confusion from
+ // email collisions. Optional for backward compatibility.
+ // PeerTube >= 8.3
+ externalId?: string
+
// PeerTube >= 5.1
adminFlags?: UserAdminFlagType
diff --git a/support/doc/plugins/guide.md b/support/doc/plugins/guide.md
index 6279dca1f1..3dd02a1312 100644
--- a/support/doc/plugins/guide.md
+++ b/support/doc/plugins/guide.md
@@ -353,7 +353,13 @@ function register (...) {
username: 'user'
role: 2
- displayName: 'User display name'
+ displayName: 'User display name',
+
+ // Stable identifier of this user in your own system (e.g. LDAP `uid`/`entryUUID`)
+ // When provided, PeerTube links the local account using this id instead of relying only on the
+ // email address, which is more robust if the email changes on your side later on
+ // PeerTube >= 8.3
+ externalId: 'user-1234'
}
}
@@ -401,6 +407,13 @@ function register (...) {
role: 2
displayName: 'User display name',
+ // Stable identifier of this user at the identity provider (OIDC `sub` claim, SAML `NameID`...)
+ // When provided, PeerTube links/looks up the local account using this id instead of relying only on the
+ // email address, which is more robust across identity provider email changes and avoids account
+ // confusion from email collisions
+ // PeerTube >= 8.3
+ externalId: 'a1b2c3d4-external-provider-subject-id',
+
// Custom admin flags (bypass video auto moderation etc.)
// https://github.com/Chocobozzz/PeerTube/blob/develop/packages/models/src/users/user-flag.model.ts
// PeerTube >= 5.1