2021-02-09 12:32:41 +00:00
|
|
|
import KeycloakAdminClient from "keycloak-admin";
|
2021-03-24 14:07:49 +00:00
|
|
|
import UserRepresentation from "keycloak-admin/lib/defs/userRepresentation";
|
2021-04-01 14:14:19 +00:00
|
|
|
import ClientRepresentation from "keycloak-admin/lib/defs/clientRepresentation";
|
2021-02-09 12:32:41 +00:00
|
|
|
|
|
|
|
export default class AdminClient {
|
|
|
|
private client: KeycloakAdminClient;
|
|
|
|
constructor() {
|
|
|
|
this.client = new KeycloakAdminClient({
|
|
|
|
baseUrl: "http://localhost:8180/auth",
|
|
|
|
realmName: "master",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
private async login() {
|
|
|
|
await this.client.auth({
|
|
|
|
username: "admin",
|
|
|
|
password: "admin",
|
|
|
|
grantType: "password",
|
|
|
|
clientId: "admin-cli",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async deleteRealm(realm: string) {
|
|
|
|
await this.login();
|
|
|
|
await this.client.realms.del({ realm });
|
|
|
|
}
|
2021-02-28 20:02:31 +00:00
|
|
|
|
2021-04-01 14:14:19 +00:00
|
|
|
async createClient(client: ClientRepresentation) {
|
|
|
|
await this.login();
|
|
|
|
await this.client.clients.create(client);
|
|
|
|
}
|
2021-02-28 20:02:31 +00:00
|
|
|
async deleteClient(clientName: string) {
|
|
|
|
await this.login();
|
|
|
|
const client = (
|
|
|
|
await this.client.clients.find({ clientId: clientName })
|
|
|
|
)[0];
|
|
|
|
await this.client.clients.del({ id: client.id! });
|
|
|
|
}
|
2021-03-16 12:37:57 +00:00
|
|
|
|
|
|
|
async createSubGroups(groups: string[]) {
|
|
|
|
await this.login();
|
|
|
|
let parentGroup = undefined;
|
|
|
|
const createdGroups = [];
|
|
|
|
for (const group of groups) {
|
|
|
|
if (!parentGroup) {
|
|
|
|
parentGroup = await this.client.groups.create({ name: group });
|
|
|
|
} else {
|
|
|
|
parentGroup = await this.client.groups.setOrCreateChild(
|
|
|
|
{ id: parentGroup.id },
|
|
|
|
{ name: group }
|
|
|
|
);
|
|
|
|
}
|
|
|
|
createdGroups.push(parentGroup);
|
|
|
|
}
|
|
|
|
return createdGroups;
|
|
|
|
}
|
|
|
|
|
|
|
|
async deleteGroups() {
|
|
|
|
await this.login();
|
|
|
|
const groups = await this.client.groups.find();
|
|
|
|
for (const group of groups) {
|
|
|
|
await this.client.groups.del({ id: group.id! });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-24 14:07:49 +00:00
|
|
|
async createUser(user: UserRepresentation) {
|
|
|
|
await this.login();
|
|
|
|
return await this.client.users.create(user);
|
|
|
|
}
|
|
|
|
|
2021-03-16 12:37:57 +00:00
|
|
|
async createUserInGroup(username: string, groupId: string) {
|
|
|
|
await this.login();
|
2021-03-24 14:07:49 +00:00
|
|
|
const user = await this.createUser({ username, enabled: true });
|
2021-03-16 12:37:57 +00:00
|
|
|
await this.client.users.addToGroup({ id: user.id!, groupId });
|
|
|
|
}
|
2021-02-09 12:32:41 +00:00
|
|
|
}
|