@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
77 lines (76 loc) • 2.82 kB
JavaScript
export const Auth_UnknownUserName = 'Unknown User';
export const Auth_UnknownUserInitials = '??';
/**
* This class represents user information extracted from the authentication process' userInfo endpoint.
* It supports mapping of GMF custom properties and OIDC standard properties.
*/
export default class AuthUserInfo {
identifier;
displayName;
fullName;
initials;
email;
roles;
two_factor_enabled;
functionalities;
constructor(userInfo) {
this.identifier = this.extractIdentifier(userInfo);
this.displayName = this.extractDisplayName(userInfo);
this.fullName = this.extractFullName(userInfo);
this.initials = this.extractInitials();
this.email = userInfo['email'] ?? undefined;
this.roles = userInfo['roles'] ?? undefined; // Not parsed yet
this.two_factor_enabled = userInfo['two_factor_enabled'] === 'true';
this.functionalities = userInfo['functionalities'] ?? {};
}
/**
* This is the unique identifier at the provider.
* Check for the OIDC standard field `sub`, then try GMF-specific field `username`.
*/
extractIdentifier(userInfo) {
return userInfo['sub'] ?? userInfo['username'] ?? undefined;
}
/**
* This corresponds to an account or user name.
* Check first for OIDC standard field `preferred_username`, then try GMF-specific fields `display_name` and `username`.
* If none of these fields are found, try `email` or fall back to `Unknown User`.
*/
extractDisplayName(userInfo) {
return (userInfo['preferred_username'] ??
userInfo['display_name'] ??
userInfo['username'] ??
userInfo['email'] ??
Auth_UnknownUserName);
}
/**
* Gets the OIDC `name` field, falling back to `given_name` and `family_name`.
*/
extractFullName(userInfo) {
if (userInfo['name']) {
return userInfo['name'];
}
if (userInfo['given_name']) {
return `${userInfo['given_name']} ${userInfo['family_name']}`;
}
return undefined;
}
/**
* Extracts the first letters of the full name or the this.displayName. Examples:
* super_admin -> SA
* Gustave-André de la Girouette -> GG
*/
extractInitials() {
const name = this.fullName ?? this.displayName;
if (name === Auth_UnknownUserName) {
return Auth_UnknownUserInitials;
}
const parts = name.split(/[\s_-]+/).filter((part) => part.length > 0);
if (parts.length === 0) {
return Auth_UnknownUserInitials;
}
else if (parts.length === 1) {
return parts[0].substring(0, 2).toUpperCase();
}
return (parts[0][0] + parts.at(-1)[0]).toUpperCase();
}
}