Identity Model
Authentication providers and credentials for users.
Schema
{
userId: ObjectId // Reference to User
provider: IdentityProvider // LOCAL, GOOGLE, GITHUB, etc.
providerAccountId: string // Unique ID from provider
email?: string // Email for this identity
emailVerified?: boolean // Verification status
passwordHash?: string // For LOCAL only
salt?: string // For LOCAL only
providerData?: { // OAuth provider data
picture?: string
locale?: string
[key: string]: any
}
createdAt: Date
updatedAt: Date
}Provider Types
enum IdentityProvider {
LOCAL = 'local',
GOOGLE = 'google',
GITHUB = 'github',
MICROSOFT = 'microsoft',
}Usage
Create Local Identity
const identity = new Identity({
userId: user._id,
provider: IdentityProvider.LOCAL,
providerAccountId: user._id.toString(),
email: 'john@example.com',
emailVerified: true,
passwordHash: hashedPassword,
salt: salt.toString('base64')
})
await identity.save()Create OAuth Identity
const identity = new Identity({
userId: user._id,
provider: IdentityProvider.GOOGLE,
providerAccountId: googleProfile.sub,
email: googleProfile.email,
emailVerified: true,
providerData: {
picture: googleProfile.picture,
locale: googleProfile.locale
}
})
await identity.save()Find Identity
// By email and provider
const identity = await Identity.findOne({
email: 'john@example.com',
provider: IdentityProvider.LOCAL
})
// All identities for a user
const identities = await Identity.find({ userId: user._id })Multiple Providers
Users can have multiple identities:
// User has both email and Google login
const identities = await Identity.find({ userId: user._id })
// Returns:
// [
// { provider: 'local', email: 'john@example.com' },
// { provider: 'google', email: 'john@gmail.com' }
// ]Next Steps
Last updated on