@ownid/azure-b2c
Version:
Server-side library for integrating OwnID passwordless authentication with Azure Active Directory B2C
105 lines (104 loc) • 3.31 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.OwnIDB2CUserService = void 0;
/**
* Service to manage user operations with Azure B2C
*/
class OwnIDB2CUserService {
constructor(auth) {
this.ownIdExtensionName = 'com.ownid.data';
this.auth = auth;
}
/**
* Find a user by their email address
*
* @param email - Email address to search for
* @returns User object if found, null otherwise
*/
async findUserByEmail(email) {
try {
const result = await this.auth.getGraphClient()
.api('/users')
.filter(`mail eq '${email}'`)
.get();
return result?.value?.[0] || null;
}
catch (error) {
throw error;
}
}
/**
* Store OwnID data for a user
*
* @param userId - Azure B2C user ID
* @param data - OwnID data to store
* @returns true if successful
*/
async setOwnIdData(userId, data) {
const graphClient = this.auth.getGraphClient();
// Verify user exists
await graphClient.api(`/users/${userId}`).get();
try {
// Try to create new extension
await graphClient.api(`/users/${userId}/extensions`).post({
"@odata.type": "microsoft.graph.openTypeExtension",
"extensionName": this.ownIdExtensionName,
"ownIdData": JSON.stringify(data)
});
}
catch (extError) {
// If extension exists (409 error), update it
if (extError.statusCode === 409) {
await graphClient
.api(`/users/${userId}/extensions/${this.ownIdExtensionName}`)
.patch({ "ownIdData": JSON.stringify(data) });
}
else {
throw extError;
}
}
return true;
}
/**
* Get OwnID data for a user
*
* @param userId - Azure B2C user ID
* @returns User object with OwnID data if exists
*/
async getOwnIdData(userId) {
const graphClient = this.auth.getGraphClient();
const user = await graphClient
.api(`/users/${userId}`)
.select('id,displayName,mail')
.get();
try {
const extensions = await graphClient
.api(`/users/${userId}/extensions`)
.get();
const ownIdExtension = extensions?.value?.find((ext) => ext.id === this.ownIdExtensionName);
if (ownIdExtension && ownIdExtension.ownIdData) {
try {
user.ownIdData = JSON.parse(ownIdExtension.ownIdData);
}
catch (e) {
// Silently handle JSON parsing errors
}
}
}
catch (extError) {
// Extension not found, continue
}
return user;
}
/**
* Get authentication tokens for a user
*
* @param userId - Azure B2C user ID
* @param email - User's email address
* @returns Authentication tokens
*/
async getTokens(userId, email) {
return this.auth.getTokens(userId, email);
}
}
exports.OwnIDB2CUserService = OwnIDB2CUserService;