Using a C8Y Plugin/widget, I am attempting to get the roles the current user has.
The below is my attempt that returns a different role types then I’m after e.g.
["ROLE_USER_MANAGEMENT_OWN_READ", "ROLE_USER_MANAGEMENT_OWN_ADMIN"]
I am after the roles assigned to a user in “/apps/administration/index.html#/roles/global_roles”
My attempt:
import { UserService } from '@c8y/client';
@Component({
selector: 'c8y-widget-plugin',
templateUrl: './widget-plugin.component.html',
styleUrls: ['./widget-plugin.component.css']
})
export class WidgetPluginComponent implements OnInit {
async getCurrentUserRoles(role: string): Promise<boolean> {
try {
const currentUser = await this.userService.current().then(res => res.data);
const roles = currentUser.roles?.references?.map(ref => ref['role'].name);
return roles.includes(role);
} catch (error) {
console.error("Error fetching user roles:", error);
return false;
}
}
console.log(
"hasRole ",
await this.getCurrentUserRoles("admins")
);
}
Got it:
import { UserService } from '@c8y/client';
@Component({
selector: 'c8y-widget-plugin',
templateUrl: './widget-plugin.component.html',
styleUrls: ['./widget-plugin.component.css']
})
async isUserInGroup(groupName: string): Promise<boolean> {
try {
const currentUser = await this.userService.current().then(res => res.data);
const groups = currentUser['groups']?.references?.map(ref => ref['group'].name);
return groups?.includes(groupName) ?? false;
} catch (error) {
console.error("Error fetching user groups:", error);
return false;
}
}
async getCurrentUserGroups(): Promise<string[]> {
try {
const currentUser = await this.userService.current().then(res => res.data);
const groups = currentUser['groups']?.references?.map(ref => ref['group'].name);
return groups || [];
} catch (error) {
console.error("Error fetching user groups:", error);
return [];
}
}
console.log(
"hasGroup 'admins':",
await this.isUserInGroup("admins")
);
console.log(
"User groups:",
await this.getCurrentUserGroups()
);
Hi @kristopher.takken,
Please also consider using the Permissions
service available in the Web SDK, that does exactly this: codex
We also provide a IfAllowedDirective
directive: codex
Regards,
Tristan