Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/role-details/role-details.component.ts
import { Component, Input, OnChanges, OnInit } from '@angular/core'; import _ from 'lodash'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; @Component({ selector: 'cd-role-details', templateUrl: './role-details.component.html', styleUrls: ['./role-details.component.scss'] }) export class RoleDetailsComponent implements OnChanges, OnInit { @Input() selection: any; @Input() scopes: Array<string>; selectedItem: any; columns: CdTableColumn[]; scopes_permissions: Array<any> = []; ngOnInit() { this.columns = [ { prop: 'scope', name: $localize`Scope`, flexGrow: 2 }, { prop: 'read', name: $localize`Read`, flexGrow: 1, cellClass: 'text-center', cellTransformation: CellTemplate.checkIcon }, { prop: 'create', name: $localize`Create`, flexGrow: 1, cellClass: 'text-center', cellTransformation: CellTemplate.checkIcon }, { prop: 'update', name: $localize`Update`, flexGrow: 1, cellClass: 'text-center', cellTransformation: CellTemplate.checkIcon }, { prop: 'delete', name: $localize`Delete`, flexGrow: 1, cellClass: 'text-center', cellTransformation: CellTemplate.checkIcon } ]; } ngOnChanges() { if (this.selection) { this.selectedItem = this.selection; // Build the scopes/permissions data used by the data table. const scopes_permissions: any[] = []; _.each(this.scopes, (scope) => { const scope_permission: any = { read: false, create: false, update: false, delete: false }; scope_permission['scope'] = scope; if (scope in this.selectedItem['scopes_permissions']) { _.each(this.selectedItem['scopes_permissions'][scope], (permission) => { scope_permission[permission] = true; }); } scopes_permissions.push(scope_permission); }); this.scopes_permissions = scopes_permissions; } } }
2,175
26.2
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/role-form/role-form-mode.enum.ts
export enum RoleFormMode { editing = 'editing' }
51
12
26
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/role-form/role-form.component.html
<div class="cd-col-form" *cdFormLoading="loading"> <form name="roleForm" #formDir="ngForm" [formGroup]="roleForm" novalidate> <div class="card"> <div i18n="form title" class="card-header">{{ action | titlecase }} {{ resource | upperFirst }}</div> <div class="card-body"> <!-- Name --> <div class="form-group row"> <label class="cd-col-form-label" [ngClass]="{'required': mode !== roleFormMode.editing}" for="name" i18n>Name</label> <div class="cd-col-form-input"> <input class="form-control" type="text" i18n-placeholder placeholder="Name..." id="name" name="name" formControlName="name" autofocus> <span class="invalid-feedback" *ngIf="roleForm.showError('name', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="roleForm.showError('name', formDir, 'notUnique')" i18n>The chosen name is already in use.</span> </div> </div> <!-- Description --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="description">Description</label> <div class="cd-col-form-input"> <input class="form-control" type="text" i18n-placeholder placeholder="Description..." id="description" name="description" formControlName="description"> </div> </div> <!-- Permissions --> <div class="form-group row"> <label i18n class="cd-col-form-label">Permissions</label> <div class="cd-col-form-input"> <cd-table [data]="scopes_permissions" [columns]="columns" columnMode="flex" [toolHeader]="false" [autoReload]="false" [autoSave]="false" [footer]="false" [limit]="0"> </cd-table> </div> </div> </div> <div class="card-footer"> <cd-form-button-panel (submitActionEvent)="submit()" [form]="roleForm" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)" wrappingClass="text-right"></cd-form-button-panel> </div> </div> </form> </div> <ng-template #cellScopeCheckboxTpl let-column="column" let-row="row" let-value="value"> <div class="custom-control custom-checkbox"> <input class="custom-control-input" id="scope_{{ row.scope }}" type="checkbox" [checked]="isRowChecked(row.scope)" (change)="onClickCellCheckbox(row.scope, column.prop, $event)"> <label class="datatable-permissions-scope-cell-label custom-control-label" for="scope_{{ row.scope }}">{{ value }}</label> </div> </ng-template> <ng-template #cellPermissionCheckboxTpl let-column="column" let-row="row" let-value="value"> <div class="custom-control custom-checkbox"> <input class="custom-control-input" type="checkbox" [checked]="value" [id]="row.scope + '-' + column.prop" (change)="onClickCellCheckbox(row.scope, column.prop, $event)"> <label class="custom-control-label" [for]="row.scope + '-' + column.prop"></label> </div> </ng-template> <ng-template #headerPermissionCheckboxTpl let-column="column"> <div class="custom-control custom-checkbox"> <input class="custom-control-input" id="header_{{ column.prop }}" type="checkbox" [checked]="isHeaderChecked(column.prop)" (change)="onClickHeaderCheckbox(column.prop, $event)"> <label class="datatable-permissions-header-cell-label custom-control-label" for="header_{{ column.prop }}">{{ column.name }}</label> </div> </ng-template>
4,381
34.918033
97
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/role-form/role-form.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { Component } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { Router, Routes } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { RoleService } from '~/app/shared/api/role.service'; import { ScopeService } from '~/app/shared/api/scope.service'; import { LoadingPanelComponent } from '~/app/shared/components/loading-panel/loading-panel.component'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FormHelper } from '~/testing/unit-test-helper'; import { RoleFormComponent } from './role-form.component'; import { RoleFormModel } from './role-form.model'; describe('RoleFormComponent', () => { let component: RoleFormComponent; let form: CdFormGroup; let fixture: ComponentFixture<RoleFormComponent>; let httpTesting: HttpTestingController; let roleService: RoleService; let router: Router; const setUrl = (url: string) => Object.defineProperty(router, 'url', { value: url }); @Component({ selector: 'cd-fake', template: '' }) class FakeComponent {} const routes: Routes = [{ path: 'roles', component: FakeComponent }]; configureTestBed( { imports: [ RouterTestingModule.withRoutes(routes), HttpClientTestingModule, ReactiveFormsModule, ToastrModule.forRoot(), SharedModule ], declarations: [RoleFormComponent, FakeComponent] }, [LoadingPanelComponent] ); beforeEach(() => { fixture = TestBed.createComponent(RoleFormComponent); component = fixture.componentInstance; form = component.roleForm; httpTesting = TestBed.inject(HttpTestingController); roleService = TestBed.inject(RoleService); router = TestBed.inject(Router); spyOn(router, 'navigate'); fixture.detectChanges(); const notify = TestBed.inject(NotificationService); spyOn(notify, 'show'); }); it('should create', () => { expect(component).toBeTruthy(); expect(form).toBeTruthy(); }); describe('create mode', () => { let formHelper: FormHelper; beforeEach(() => { setUrl('/user-management/roles/add'); component.ngOnInit(); formHelper = new FormHelper(form); }); it('should not disable fields', () => { ['name', 'description', 'scopes_permissions'].forEach((key) => expect(form.get(key).disabled).toBeFalsy() ); }); it('should validate name required', () => { formHelper.expectErrorChange('name', '', 'required'); }); it('should set mode', () => { expect(component.mode).toBeUndefined(); }); it('should submit', () => { const role: RoleFormModel = { name: 'role1', description: 'Role 1', scopes_permissions: { osd: ['read'] } }; formHelper.setMultipleValues(role); component.submit(); const roleReq = httpTesting.expectOne('api/role'); expect(roleReq.request.method).toBe('POST'); expect(roleReq.request.body).toEqual(role); roleReq.flush({}); expect(router.navigate).toHaveBeenCalledWith(['/user-management/roles']); }); it('should check all perms for a scope', () => { formHelper.setValue('scopes_permissions', { cephfs: ['read'] }); component.onClickCellCheckbox('grafana', 'scope'); const scopes_permissions = form.getValue('scopes_permissions'); expect(Object.keys(scopes_permissions)).toContain('grafana'); expect(scopes_permissions['grafana']).toEqual(['create', 'delete', 'read', 'update']); }); it('should uncheck all perms for a scope', () => { formHelper.setValue('scopes_permissions', { cephfs: ['read', 'create', 'update', 'delete'] }); component.onClickCellCheckbox('cephfs', 'scope'); const scopes_permissions = form.getValue('scopes_permissions'); expect(Object.keys(scopes_permissions)).not.toContain('cephfs'); }); it('should uncheck all scopes and perms', () => { component.scopes = ['cephfs', 'grafana']; formHelper.setValue('scopes_permissions', { cephfs: ['read', 'delete'], grafana: ['update'] }); component.onClickHeaderCheckbox('scope', ({ target: { checked: false } } as unknown) as Event); const scopes_permissions = form.getValue('scopes_permissions'); expect(scopes_permissions).toEqual({}); }); it('should check all scopes and perms', () => { component.scopes = ['cephfs', 'grafana']; formHelper.setValue('scopes_permissions', { cephfs: ['create', 'update'], grafana: ['delete'] }); component.onClickHeaderCheckbox('scope', ({ target: { checked: true } } as unknown) as Event); const scopes_permissions = form.getValue('scopes_permissions'); const keys = Object.keys(scopes_permissions); expect(keys).toEqual(['cephfs', 'grafana']); keys.forEach((key) => { expect(scopes_permissions[key].sort()).toEqual(['create', 'delete', 'read', 'update']); }); }); it('should check if column is checked', () => { component.scopes_permissions = [ { scope: 'a', read: true, create: true, update: true, delete: true }, { scope: 'b', read: false, create: true, update: false, delete: true } ]; expect(component.isRowChecked('a')).toBeTruthy(); expect(component.isRowChecked('b')).toBeFalsy(); expect(component.isRowChecked('c')).toBeFalsy(); }); it('should check if header is checked', () => { component.scopes_permissions = [ { scope: 'a', read: true, create: true, update: false, delete: true }, { scope: 'b', read: false, create: true, update: false, delete: true } ]; expect(component.isHeaderChecked('read')).toBeFalsy(); expect(component.isHeaderChecked('create')).toBeTruthy(); expect(component.isHeaderChecked('update')).toBeFalsy(); }); }); describe('edit mode', () => { const role: RoleFormModel = { name: 'role1', description: 'Role 1', scopes_permissions: { osd: ['read', 'create'] } }; const scopes = ['osd', 'user']; beforeEach(() => { spyOn(roleService, 'get').and.callFake(() => of(role)); spyOn(TestBed.inject(ScopeService), 'list').and.callFake(() => of(scopes)); setUrl('/user-management/roles/edit/role1'); component.ngOnInit(); const reqScopes = httpTesting.expectOne('ui-api/scope'); expect(reqScopes.request.method).toBe('GET'); }); afterEach(() => { httpTesting.verify(); }); it('should disable fields if editing', () => { expect(form.get('name').disabled).toBeTruthy(); ['description', 'scopes_permissions'].forEach((key) => expect(form.get(key).disabled).toBeFalsy() ); }); it('should set control values', () => { ['name', 'description', 'scopes_permissions'].forEach((key) => expect(form.getValue(key)).toBe(role[key]) ); }); it('should set mode', () => { expect(component.mode).toBe('editing'); }); it('should submit', () => { component.onClickCellCheckbox('osd', 'update'); component.onClickCellCheckbox('osd', 'create'); component.onClickCellCheckbox('user', 'read'); component.submit(); const roleReq = httpTesting.expectOne(`api/role/${role.name}`); expect(roleReq.request.method).toBe('PUT'); expect(roleReq.request.body).toEqual({ name: 'role1', description: 'Role 1', scopes_permissions: { osd: ['read', 'update'], user: ['read'] } }); roleReq.flush({}); expect(router.navigate).toHaveBeenCalledWith(['/user-management/roles']); }); }); });
8,104
35.345291
102
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/role-form/role-form.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import _ from 'lodash'; import { forkJoin as observableForkJoin } from 'rxjs'; import { RoleService } from '~/app/shared/api/role.service'; import { ScopeService } from '~/app/shared/api/scope.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdForm } from '~/app/shared/forms/cd-form'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { CdValidators } from '~/app/shared/forms/cd-validators'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { NotificationService } from '~/app/shared/services/notification.service'; import { RoleFormMode } from './role-form-mode.enum'; import { RoleFormModel } from './role-form.model'; @Component({ selector: 'cd-role-form', templateUrl: './role-form.component.html', styleUrls: ['./role-form.component.scss'] }) export class RoleFormComponent extends CdForm implements OnInit { @ViewChild('headerPermissionCheckboxTpl', { static: true }) headerPermissionCheckboxTpl: TemplateRef<any>; @ViewChild('cellScopeCheckboxTpl', { static: true }) cellScopeCheckboxTpl: TemplateRef<any>; @ViewChild('cellPermissionCheckboxTpl', { static: true }) cellPermissionCheckboxTpl: TemplateRef<any>; roleForm: CdFormGroup; response: RoleFormModel; columns: CdTableColumn[]; scopes: Array<string> = []; scopes_permissions: Array<any> = []; roleFormMode = RoleFormMode; mode: RoleFormMode; action: string; resource: string; constructor( private route: ActivatedRoute, private router: Router, private roleService: RoleService, private scopeService: ScopeService, private notificationService: NotificationService, public actionLabels: ActionLabelsI18n ) { super(); this.resource = $localize`role`; this.createForm(); this.listenToChanges(); } createForm() { this.roleForm = new CdFormGroup({ name: new FormControl('', { validators: [Validators.required], asyncValidators: [CdValidators.unique(this.roleService.exists, this.roleService)] }), description: new FormControl(''), scopes_permissions: new FormControl({}) }); } ngOnInit() { this.columns = [ { prop: 'scope', name: $localize`All`, flexGrow: 2, cellTemplate: this.cellScopeCheckboxTpl, headerTemplate: this.headerPermissionCheckboxTpl }, { prop: 'read', name: $localize`Read`, flexGrow: 1, cellClass: 'text-center', cellTemplate: this.cellPermissionCheckboxTpl, headerTemplate: this.headerPermissionCheckboxTpl }, { prop: 'create', name: $localize`Create`, flexGrow: 1, cellClass: 'text-center', cellTemplate: this.cellPermissionCheckboxTpl, headerTemplate: this.headerPermissionCheckboxTpl }, { prop: 'update', name: $localize`Update`, flexGrow: 1, cellClass: 'text-center', cellTemplate: this.cellPermissionCheckboxTpl, headerTemplate: this.headerPermissionCheckboxTpl }, { prop: 'delete', name: $localize`Delete`, flexGrow: 1, cellClass: 'text-center', cellTemplate: this.cellPermissionCheckboxTpl, headerTemplate: this.headerPermissionCheckboxTpl } ]; if (this.router.url.startsWith('/user-management/roles/edit')) { this.mode = this.roleFormMode.editing; this.action = this.actionLabels.EDIT; } else { this.action = this.actionLabels.CREATE; } if (this.mode === this.roleFormMode.editing) { this.initEdit(); } else { this.initCreate(); } } initCreate() { // Load the scopes and initialize the default scopes/permissions data. this.scopeService.list().subscribe((scopes: Array<string>) => { this.scopes = scopes; this.roleForm.get('scopes_permissions').setValue({}); this.loadingReady(); }); } initEdit() { // Disable the 'Name' input field. this.roleForm.get('name').disable(); // Load the scopes and the role data. this.route.params.subscribe((params: { name: string }) => { const observables = []; observables.push(this.scopeService.list()); observables.push(this.roleService.get(params.name)); observableForkJoin(observables).subscribe((resp: any[]) => { this.scopes = resp[0]; ['name', 'description', 'scopes_permissions'].forEach((key) => this.roleForm.get(key).setValue(resp[1][key]) ); this.loadingReady(); }); }); } listenToChanges() { // Create/Update the data which is used by the data table to display the // scopes/permissions every time the form field value has been changed. this.roleForm.get('scopes_permissions').valueChanges.subscribe((value) => { const scopes_permissions: any[] = []; _.each(this.scopes, (scope) => { // Set the defaults values. const scope_permission: any = { read: false, create: false, update: false, delete: false }; scope_permission['scope'] = scope; // Apply settings from the given value if they exist. if (scope in value) { _.each(value[scope], (permission) => { scope_permission[permission] = true; }); } scopes_permissions.push(scope_permission); }); this.scopes_permissions = scopes_permissions; }); } /** * Checks if the specified row checkbox needs to be rendered as checked. * @param {string} scope The scope to be checked, e.g. 'cephfs', 'grafana', * 'osd', 'pool' ... * @return Returns true if all permissions (read, create, update, delete) * are checked for the specified scope, otherwise false. */ isRowChecked(scope: string) { const scope_permission = _.find(this.scopes_permissions, (o) => { return o['scope'] === scope; }); if (_.isUndefined(scope_permission)) { return false; } return ( scope_permission['read'] && scope_permission['create'] && scope_permission['update'] && scope_permission['delete'] ); } /** * Checks if the specified header checkbox needs to be rendered as checked. * @param {string} property The property/permission (read, create, * update, delete) to be checked. If 'scope' is given, all permissions * are checked. * @return Returns true if specified property/permission is selected * for all scopes, otherwise false. */ isHeaderChecked(property: string) { let permissions = [property]; if ('scope' === property) { permissions = ['read', 'create', 'update', 'delete']; } return permissions.every((permission) => { return this.scopes_permissions.every((scope_permission) => { return scope_permission[permission]; }); }); } onClickCellCheckbox(scope: string, property: string, event: any = null) { // Use a copy of the form field data to do not trigger the redrawing of the // data table with every change. const scopes_permissions = _.cloneDeep(this.roleForm.getValue('scopes_permissions')); let permissions = [property]; if ('scope' === property) { permissions = ['read', 'create', 'update', 'delete']; } if (!(scope in scopes_permissions)) { scopes_permissions[scope] = []; } // Add or remove the given permission(s) depending on the click event or if no // click event is given then add/remove them if they are absent/exist. if ( (event && event.target['checked']) || !_.isEqual(permissions.sort(), _.intersection(scopes_permissions[scope], permissions).sort()) ) { scopes_permissions[scope] = _.union(scopes_permissions[scope], permissions); } else { scopes_permissions[scope] = _.difference(scopes_permissions[scope], permissions); if (_.isEmpty(scopes_permissions[scope])) { _.unset(scopes_permissions, scope); } } this.roleForm.get('scopes_permissions').setValue(scopes_permissions); } onClickHeaderCheckbox(property: 'scope' | 'read' | 'create' | 'update' | 'delete', event: any) { // Use a copy of the form field data to do not trigger the redrawing of the // data table with every change. const scopes_permissions = _.cloneDeep(this.roleForm.getValue('scopes_permissions')); let permissions = [property]; if ('scope' === property) { permissions = ['read', 'create', 'update', 'delete']; } _.each(permissions, (permission) => { _.each(this.scopes, (scope) => { if (event.target['checked']) { scopes_permissions[scope] = _.union(scopes_permissions[scope], [permission]); } else { scopes_permissions[scope] = _.difference(scopes_permissions[scope], [permission]); if (_.isEmpty(scopes_permissions[scope])) { _.unset(scopes_permissions, scope); } } }); }); this.roleForm.get('scopes_permissions').setValue(scopes_permissions); } getRequest(): RoleFormModel { const roleFormModel = new RoleFormModel(); ['name', 'description', 'scopes_permissions'].forEach( (key) => (roleFormModel[key] = this.roleForm.get(key).value) ); return roleFormModel; } createAction() { const roleFormModel = this.getRequest(); this.roleService.create(roleFormModel).subscribe( () => { this.notificationService.show( NotificationType.success, $localize`Created role '${roleFormModel.name}'` ); this.router.navigate(['/user-management/roles']); }, () => { this.roleForm.setErrors({ cdSubmitButton: true }); } ); } editAction() { const roleFormModel = this.getRequest(); this.roleService.update(roleFormModel).subscribe( () => { this.notificationService.show( NotificationType.success, $localize`Updated role '${roleFormModel.name}'` ); this.router.navigate(['/user-management/roles']); }, () => { this.roleForm.setErrors({ cdSubmitButton: true }); } ); } submit() { if (this.mode === this.roleFormMode.editing) { this.editAction(); } else { this.createAction(); } } }
10,599
32.544304
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/role-form/role-form.model.ts
export class RoleFormModel { name: string; description: string; scopes_permissions: any; }
97
15.333333
28
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/role-list/role-list.component.html
<cd-user-tabs></cd-user-tabs> <cd-table [data]="roles" columnMode="flex" [columns]="columns" identifier="name" selectionType="single" [hasDetails]="true" (setExpandedRow)="setExpandedRow($event)" (fetchData)="getRoles()" (updateSelection)="updateSelection($event)"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> <cd-role-details cdTableDetail [selection]="expandedRow" [scopes]="scopes"> </cd-role-details> </cd-table>
701
30.909091
54
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/role-list/role-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, PermissionHelper } from '~/testing/unit-test-helper'; import { RoleDetailsComponent } from '../role-details/role-details.component'; import { UserTabsComponent } from '../user-tabs/user-tabs.component'; import { RoleListComponent } from './role-list.component'; describe('RoleListComponent', () => { let component: RoleListComponent; let fixture: ComponentFixture<RoleListComponent>; configureTestBed({ declarations: [RoleListComponent, RoleDetailsComponent, UserTabsComponent], imports: [ BrowserAnimationsModule, SharedModule, ToastrModule.forRoot(), NgbNavModule, RouterTestingModule, HttpClientTestingModule ] }); beforeEach(() => { fixture = TestBed.createComponent(RoleListComponent); component = fixture.componentInstance; }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should test all TableActions combinations', () => { const permissionHelper: PermissionHelper = new PermissionHelper(component.permission); const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions( component.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: ['Create', 'Clone', 'Edit', 'Delete'], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,update': { actions: ['Create', 'Clone', 'Edit'], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,delete': { actions: ['Create', 'Clone', 'Delete'], primary: { multiple: 'Create', executing: 'Delete', single: 'Delete', no: 'Create' } }, create: { actions: ['Create', 'Clone'], primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' } }, 'update,delete': { actions: ['Edit', 'Delete'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, update: { actions: ['Edit'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, delete: { actions: ['Delete'], primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); });
3,065
35.5
101
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/role-list/role-list.component.ts
import { Component, OnInit } from '@angular/core'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { forkJoin } from 'rxjs'; import { RoleService } from '~/app/shared/api/role.service'; import { ScopeService } from '~/app/shared/api/scope.service'; import { ListWithDetails } from '~/app/shared/classes/list-with-details.class'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { FormModalComponent } from '~/app/shared/components/form-modal/form-modal.component'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { Permission } from '~/app/shared/models/permissions'; import { EmptyPipe } from '~/app/shared/pipes/empty.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { URLBuilderService } from '~/app/shared/services/url-builder.service'; const BASE_URL = 'user-management/roles'; @Component({ selector: 'cd-role-list', templateUrl: './role-list.component.html', styleUrls: ['./role-list.component.scss'], providers: [{ provide: URLBuilderService, useValue: new URLBuilderService(BASE_URL) }] }) export class RoleListComponent extends ListWithDetails implements OnInit { permission: Permission; tableActions: CdTableAction[]; columns: CdTableColumn[]; roles: Array<any>; scopes: Array<string>; selection = new CdTableSelection(); modalRef: NgbModalRef; constructor( private roleService: RoleService, private scopeService: ScopeService, private emptyPipe: EmptyPipe, private authStorageService: AuthStorageService, private modalService: ModalService, private notificationService: NotificationService, private urlBuilder: URLBuilderService, public actionLabels: ActionLabelsI18n ) { super(); this.permission = this.authStorageService.getPermissions().user; const addAction: CdTableAction = { permission: 'create', icon: Icons.add, routerLink: () => this.urlBuilder.getCreate(), name: this.actionLabels.CREATE }; const cloneAction: CdTableAction = { permission: 'create', icon: Icons.clone, name: this.actionLabels.CLONE, disable: () => !this.selection.hasSingleSelection, click: () => this.cloneRole() }; const editAction: CdTableAction = { permission: 'update', icon: Icons.edit, disable: () => !this.selection.hasSingleSelection || this.selection.first().system, routerLink: () => this.selection.first() && this.urlBuilder.getEdit(this.selection.first().name), name: this.actionLabels.EDIT }; const deleteAction: CdTableAction = { permission: 'delete', icon: Icons.destroy, disable: () => !this.selection.hasSingleSelection || this.selection.first().system, click: () => this.deleteRoleModal(), name: this.actionLabels.DELETE }; this.tableActions = [addAction, cloneAction, editAction, deleteAction]; } ngOnInit() { this.columns = [ { name: $localize`Name`, prop: 'name', flexGrow: 3 }, { name: $localize`Description`, prop: 'description', flexGrow: 5, pipe: this.emptyPipe }, { name: $localize`System Role`, prop: 'system', cellClass: 'text-center', flexGrow: 1, cellTransformation: CellTemplate.checkIcon } ]; } getRoles() { forkJoin([this.roleService.list(), this.scopeService.list()]).subscribe( (data: [Array<any>, Array<string>]) => { this.roles = data[0]; this.scopes = data[1]; } ); } updateSelection(selection: CdTableSelection) { this.selection = selection; } deleteRole(role: string) { this.roleService.delete(role).subscribe( () => { this.getRoles(); this.modalRef.close(); this.notificationService.show(NotificationType.success, $localize`Deleted role '${role}'`); }, () => { this.modalRef.componentInstance.stopLoadingSpinner(); } ); } deleteRoleModal() { const name = this.selection.first().name; this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: 'Role', itemNames: [name], submitAction: () => this.deleteRole(name) }); } cloneRole() { const name = this.selection.first().name; this.modalRef = this.modalService.show(FormModalComponent, { fields: [ { type: 'text', name: 'newName', value: `${name}_clone`, label: $localize`New name`, required: true } ], titleText: $localize`Clone Role`, submitButtonText: $localize`Clone Role`, onSubmit: (values: object) => { this.roleService.clone(name, values['newName']).subscribe(() => { this.getRoles(); this.notificationService.show( NotificationType.success, $localize`Cloned role '${values['newName']}' from '${name}'` ); }); } }); } }
5,720
32.652941
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-form/user-form-mode.enum.ts
export enum UserFormMode { editing = 'editing' }
51
12
26
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-form/user-form-role.model.ts
import { SelectOption } from '~/app/shared/components/select/select-option.model'; export class UserFormRoleModel implements SelectOption { name: string; description: string; selected = false; scopes_permissions: object; enabled = true; constructor(name: string, description: string) { this.name = name; this.description = description; } }
364
23.333333
82
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-form/user-form.component.html
<div class="cd-col-form" *cdFormLoading="loading"> <form name="userForm" #formDir="ngForm" [formGroup]="userForm" novalidate> <div class="card"> <div i18n="form title" class="card-header">{{ action | titlecase }} {{ resource | upperFirst }}</div> <div class="card-body"> <!-- Username --> <div class="form-group row"> <label class="cd-col-form-label" [ngClass]="{'required': mode !== userFormMode.editing}" for="username" i18n>Username</label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Username..." id="username" name="username" formControlName="username" autocomplete="off" autofocus> <span class="invalid-feedback" *ngIf="userForm.showError('username', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="userForm.showError('username', formDir, 'notUnique')" i18n>The username already exists.</span> </div> </div> <!-- Password --> <div class="form-group row" *ngIf="!authStorageService.isSSO()"> <label class="cd-col-form-label" for="password"> <ng-container i18n>Password</ng-container> <cd-helper *ngIf="passwordPolicyHelpText.length > 0" class="text-pre-wrap" html="{{ passwordPolicyHelpText }}"> </cd-helper> </label> <div class="cd-col-form-input"> <div class="input-group"> <input class="form-control" type="password" placeholder="Password..." id="password" name="password" autocomplete="new-password" formControlName="password"> <button type="button" class="btn btn-light" cdPasswordButton="password"> </button> </div> <div class="password-strength-level"> <div class="{{ passwordStrengthLevelClass }}" data-toggle="tooltip" title="{{ passwordValuation }}"> </div> </div> <span class="invalid-feedback" *ngIf="userForm.showError('password', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="userForm.showError('password', formDir, 'passwordPolicy')"> {{ passwordValuation }} </span> </div> </div> <!-- Confirm password --> <div class="form-group row" *ngIf="!authStorageService.isSSO()"> <label i18n class="cd-col-form-label" for="confirmpassword">Confirm password</label> <div class="cd-col-form-input"> <div class="input-group"> <input class="form-control" type="password" placeholder="Confirm password..." id="confirmpassword" name="confirmpassword" autocomplete="new-password" formControlName="confirmpassword"> <button type="button" class="btn btn-light" cdPasswordButton="confirmpassword"> </button> <span class="invalid-feedback" *ngIf="userForm.showError('confirmpassword', formDir, 'match')" i18n>Password confirmation doesn't match the password.</span> </div> <span class="invalid-feedback" *ngIf="userForm.showError('confirmpassword', formDir, 'required')" i18n>This field is required.</span> </div> </div> <!-- Password expiration date --> <div class="form-group row" *ngIf="!authStorageService.isSSO()"> <label class="cd-col-form-label" [ngClass]="{'required': pwdExpirationSettings.pwdExpirationSpan > 0}" for="pwdExpirationDate"> <ng-container i18n>Password expiration date</ng-container> <cd-helper class="text-pre-wrap" *ngIf="pwdExpirationSettings.pwdExpirationSpan == 0"> <p> The Dashboard setting defining the expiration interval of passwords is currently set to <strong>0</strong>. This means if a date is set, the user password will only expire once. </p> <p> Consider configuring the Dashboard setting <a routerLink="/mgr-modules/edit/dashboard" class="alert-link">USER_PWD_EXPIRATION_SPAN</a> in order to let passwords expire periodically. </p> </cd-helper> </label> <div class="cd-col-form-input"> <div class="input-group"> <input class="form-control" i18n-placeholder placeholder="Password expiration date..." id="pwdExpirationDate" name="pwdExpirationDate" formControlName="pwdExpirationDate" [ngbPopover]="popContent" triggers="manual" #p="ngbPopover" (click)="p.open()" (keypress)="p.close()"> <button type="button" class="btn btn-light" (click)="clearExpirationDate()"> <i class="icon-prepend {{ icons.destroy }}"></i> </button> <span class="invalid-feedback" *ngIf="userForm.showError('pwdExpirationDate', formDir, 'required')" i18n>This field is required.</span> </div> </div> </div> <!-- Name --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="name">Full name</label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Full name..." id="name" name="name" formControlName="name"> </div> </div> <!-- Email --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="email">Email</label> <div class="cd-col-form-input"> <input class="form-control" type="email" placeholder="Email..." id="email" name="email" formControlName="email"> <span class="invalid-feedback" *ngIf="userForm.showError('email', formDir, 'email')" i18n>Invalid email.</span> </div> </div> <!-- Roles --> <div class="form-group row"> <label class="cd-col-form-label" i18n>Roles</label> <div class="cd-col-form-input"> <span class="no-border full-height" *ngIf="allRoles"> <cd-select-badges [data]="userForm.controls.roles.value" [options]="allRoles" [messages]="messages"></cd-select-badges> </span> </div> </div> <!-- Enabled --> <div class="form-group row" *ngIf="!isCurrentUser()"> <div class="cd-col-form-offset"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="enabled" name="enabled" formControlName="enabled"> <label class="custom-control-label" for="enabled" i18n>Enabled</label> </div> </div> </div> <!-- Force change password --> <div class="form-group row" *ngIf="!isCurrentUser() && !authStorageService.isSSO()"> <div class="cd-col-form-offset"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="pwdUpdateRequired" name="pwdUpdateRequired" formControlName="pwdUpdateRequired"> <label class="custom-control-label" for="pwdUpdateRequired" i18n>User must change password at next logon</label> </div> </div> </div> </div> <div class="card-footer"> <cd-form-button-panel (submitActionEvent)="submit()" [form]="userForm" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)" wrappingClass="text-right"></cd-form-button-panel> </div> </div> </form> </div> <ng-template #removeSelfUserReadUpdatePermissionTpl> <p><strong i18n>You are about to remove "user read / update" permissions from your own user.</strong></p> <br> <p i18n>If you continue, you will no longer be able to add or remove roles from any user.</p> <ng-container i18n>Are you sure you want to continue?</ng-container> </ng-template> <ng-template #popContent> <cd-date-time-picker [control]="userForm.get('pwdExpirationDate')" [hasTime]="false"></cd-date-time-picker> </ng-template>
10,135
38.286822
107
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-form/user-form.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { Component } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { Router, Routes } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { RoleService } from '~/app/shared/api/role.service'; import { SettingsService } from '~/app/shared/api/settings.service'; import { UserService } from '~/app/shared/api/user.service'; import { ComponentsModule } from '~/app/shared/components/components.module'; import { LoadingPanelComponent } from '~/app/shared/components/loading-panel/loading-panel.component'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { PasswordPolicyService } from '~/app/shared/services/password-policy.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FormHelper } from '~/testing/unit-test-helper'; import { UserFormComponent } from './user-form.component'; import { UserFormModel } from './user-form.model'; describe('UserFormComponent', () => { let component: UserFormComponent; let form: CdFormGroup; let fixture: ComponentFixture<UserFormComponent>; let httpTesting: HttpTestingController; let userService: UserService; let modalService: ModalService; let router: Router; let formHelper: FormHelper; const setUrl = (url: string) => Object.defineProperty(router, 'url', { value: url }); @Component({ selector: 'cd-fake', template: '' }) class FakeComponent {} const routes: Routes = [ { path: 'login', component: FakeComponent }, { path: 'users', component: FakeComponent } ]; configureTestBed( { imports: [ RouterTestingModule.withRoutes(routes), HttpClientTestingModule, ReactiveFormsModule, ComponentsModule, ToastrModule.forRoot(), SharedModule, NgbPopoverModule ], declarations: [UserFormComponent, FakeComponent] }, [LoadingPanelComponent] ); beforeEach(() => { spyOn(TestBed.inject(PasswordPolicyService), 'getHelpText').and.callFake(() => of('')); fixture = TestBed.createComponent(UserFormComponent); component = fixture.componentInstance; form = component.userForm; httpTesting = TestBed.inject(HttpTestingController); userService = TestBed.inject(UserService); modalService = TestBed.inject(ModalService); router = TestBed.inject(Router); spyOn(router, 'navigate'); fixture.detectChanges(); const notify = TestBed.inject(NotificationService); spyOn(notify, 'show'); formHelper = new FormHelper(form); }); it('should create', () => { expect(component).toBeTruthy(); expect(form).toBeTruthy(); }); describe('create mode', () => { beforeEach(() => { setUrl('/user-management/users/add'); component.ngOnInit(); }); it('should not disable fields', () => { [ 'username', 'name', 'password', 'confirmpassword', 'email', 'roles', 'pwdExpirationDate' ].forEach((key) => expect(form.get(key).disabled).toBeFalsy()); }); it('should validate username required', () => { formHelper.expectErrorChange('username', '', 'required'); formHelper.expectValidChange('username', 'user1'); }); it('should validate password match', () => { formHelper.setValue('password', 'aaa'); formHelper.expectErrorChange('confirmpassword', 'bbb', 'match'); formHelper.expectValidChange('confirmpassword', 'aaa'); }); it('should validate email', () => { formHelper.expectErrorChange('email', 'aaa', 'email'); }); it('should set mode', () => { expect(component.mode).toBeUndefined(); }); it('should submit', () => { const user: UserFormModel = { username: 'user0', password: 'pass0', name: 'User 0', email: '[email protected]', roles: ['administrator'], enabled: true, pwdExpirationDate: undefined, pwdUpdateRequired: true }; formHelper.setMultipleValues(user); formHelper.setValue('confirmpassword', user.password); component.submit(); const userReq = httpTesting.expectOne('api/user'); expect(userReq.request.method).toBe('POST'); expect(userReq.request.body).toEqual(user); userReq.flush({}); expect(router.navigate).toHaveBeenCalledWith(['/user-management/users']); }); }); describe('edit mode', () => { const user: UserFormModel = { username: 'user1', password: undefined, name: 'User 1', email: '[email protected]', roles: ['administrator'], enabled: true, pwdExpirationDate: undefined, pwdUpdateRequired: true }; const roles = [ { name: 'administrator', description: 'Administrator', scopes_permissions: { user: ['create', 'delete', 'read', 'update'] } }, { name: 'read-only', description: 'Read-Only', scopes_permissions: { user: ['read'] } }, { name: 'user-manager', description: 'User Manager', scopes_permissions: { user: ['create', 'delete', 'read', 'update'] } } ]; beforeEach(() => { spyOn(userService, 'get').and.callFake(() => of(user)); spyOn(TestBed.inject(RoleService), 'list').and.callFake(() => of(roles)); setUrl('/user-management/users/edit/user1'); spyOn(TestBed.inject(SettingsService), 'getStandardSettings').and.callFake(() => of({ user_pwd_expiration_warning_1: 10, user_pwd_expiration_warning_2: 5, user_pwd_expiration_span: 90 }) ); component.ngOnInit(); const req = httpTesting.expectOne('api/role'); expect(req.request.method).toBe('GET'); req.flush(roles); httpTesting.expectOne('ui-api/standard_settings'); }); afterEach(() => { httpTesting.verify(); }); it('should disable fields if editing', () => { expect(form.get('username').disabled).toBeTruthy(); ['name', 'password', 'confirmpassword', 'email', 'roles'].forEach((key) => expect(form.get(key).disabled).toBeFalsy() ); }); it('should set control values', () => { ['username', 'name', 'email', 'roles'].forEach((key) => expect(form.getValue(key)).toBe(user[key]) ); ['password', 'confirmpassword'].forEach((key) => expect(form.getValue(key)).toBeFalsy()); }); it('should set mode', () => { expect(component.mode).toBe('editing'); }); it('should alert if user is removing needed role permission', () => { spyOn(TestBed.inject(AuthStorageService), 'getUsername').and.callFake(() => user.username); let modalBodyTpl = null; spyOn(modalService, 'show').and.callFake((_content, initialState) => { modalBodyTpl = initialState.bodyTpl; }); formHelper.setValue('roles', ['read-only']); component.submit(); expect(modalBodyTpl).toEqual(component.removeSelfUserReadUpdatePermissionTpl); }); it('should logout if current user roles have been changed', () => { spyOn(TestBed.inject(AuthStorageService), 'getUsername').and.callFake(() => user.username); formHelper.setValue('roles', ['user-manager']); component.submit(); const userReq = httpTesting.expectOne(`api/user/${user.username}`); expect(userReq.request.method).toBe('PUT'); userReq.flush({}); const authReq = httpTesting.expectOne('api/auth/logout'); expect(authReq.request.method).toBe('POST'); }); it('should submit', () => { spyOn(TestBed.inject(AuthStorageService), 'getUsername').and.callFake(() => user.username); component.submit(); const userReq = httpTesting.expectOne(`api/user/${user.username}`); expect(userReq.request.method).toBe('PUT'); expect(userReq.request.body).toEqual({ username: 'user1', password: '', pwdUpdateRequired: true, name: 'User 1', email: '[email protected]', roles: ['administrator'], enabled: true }); userReq.flush({}); expect(router.navigate).toHaveBeenCalledWith(['/user-management/users']); }); }); });
8,831
33.100386
102
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-form/user-form.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import moment from 'moment'; import { forkJoin as observableForkJoin } from 'rxjs'; import { AuthService } from '~/app/shared/api/auth.service'; import { RoleService } from '~/app/shared/api/role.service'; import { SettingsService } from '~/app/shared/api/settings.service'; import { UserService } from '~/app/shared/api/user.service'; import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component'; import { SelectMessages } from '~/app/shared/components/select/select-messages.model'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdForm } from '~/app/shared/forms/cd-form'; import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { CdValidators } from '~/app/shared/forms/cd-validators'; import { CdPwdExpirationSettings } from '~/app/shared/models/cd-pwd-expiration-settings'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { PasswordPolicyService } from '~/app/shared/services/password-policy.service'; import { UserFormMode } from './user-form-mode.enum'; import { UserFormRoleModel } from './user-form-role.model'; import { UserFormModel } from './user-form.model'; @Component({ selector: 'cd-user-form', templateUrl: './user-form.component.html', styleUrls: ['./user-form.component.scss'] }) export class UserFormComponent extends CdForm implements OnInit { @ViewChild('removeSelfUserReadUpdatePermissionTpl', { static: true }) removeSelfUserReadUpdatePermissionTpl: TemplateRef<any>; modalRef: NgbModalRef; userForm: CdFormGroup; response: UserFormModel; userFormMode = UserFormMode; mode: UserFormMode; allRoles: Array<UserFormRoleModel>; messages = new SelectMessages({ empty: $localize`There are no roles.` }); action: string; resource: string; passwordPolicyHelpText = ''; passwordStrengthLevelClass: string; passwordValuation: string; icons = Icons; pwdExpirationSettings: CdPwdExpirationSettings; pwdExpirationFormat = 'YYYY-MM-DD'; constructor( private authService: AuthService, private authStorageService: AuthStorageService, private route: ActivatedRoute, public router: Router, private modalService: ModalService, private roleService: RoleService, private userService: UserService, private notificationService: NotificationService, public actionLabels: ActionLabelsI18n, private passwordPolicyService: PasswordPolicyService, private formBuilder: CdFormBuilder, private settingsService: SettingsService ) { super(); this.resource = $localize`user`; this.createForm(); this.messages = new SelectMessages({ empty: $localize`There are no roles.` }); } createForm() { this.passwordPolicyService.getHelpText().subscribe((helpText: string) => { this.passwordPolicyHelpText = helpText; }); this.userForm = this.formBuilder.group( { username: [ '', [Validators.required], [CdValidators.unique(this.userService.validateUserName, this.userService)] ], name: [''], password: [ '', [], [ CdValidators.passwordPolicy( this.userService, () => this.userForm.getValue('username'), (_valid: boolean, credits: number, valuation: string) => { this.passwordStrengthLevelClass = this.passwordPolicyService.mapCreditsToCssClass( credits ); this.passwordValuation = _.defaultTo(valuation, ''); } ) ] ], confirmpassword: [''], pwdExpirationDate: [undefined], email: ['', [CdValidators.email]], roles: [[]], enabled: [true, [Validators.required]], pwdUpdateRequired: [true] }, { validators: [CdValidators.match('password', 'confirmpassword')] } ); } ngOnInit() { if (this.router.url.startsWith('/user-management/users/edit')) { this.mode = this.userFormMode.editing; this.action = this.actionLabels.EDIT; } else { this.action = this.actionLabels.CREATE; } const observables = [this.roleService.list(), this.settingsService.getStandardSettings()]; observableForkJoin(observables).subscribe( (result: [UserFormRoleModel[], CdPwdExpirationSettings]) => { this.allRoles = _.map(result[0], (role) => { role.enabled = true; return role; }); this.pwdExpirationSettings = new CdPwdExpirationSettings(result[1]); if (this.mode === this.userFormMode.editing) { this.initEdit(); } else { if (this.pwdExpirationSettings.pwdExpirationSpan > 0) { const pwdExpirationDateField = this.userForm.get('pwdExpirationDate'); const expirationDate = moment(); expirationDate.add(this.pwdExpirationSettings.pwdExpirationSpan, 'day'); pwdExpirationDateField.setValue(expirationDate.format(this.pwdExpirationFormat)); pwdExpirationDateField.setValidators([Validators.required]); } this.loadingReady(); } } ); } initEdit() { this.disableForEdit(); this.route.params.subscribe((params: { username: string }) => { const username = params.username; this.userService.get(username).subscribe((userFormModel: UserFormModel) => { this.response = _.cloneDeep(userFormModel); this.setResponse(userFormModel); this.loadingReady(); }); }); } disableForEdit() { this.userForm.get('username').disable(); } setResponse(response: UserFormModel) { ['username', 'name', 'email', 'roles', 'enabled', 'pwdUpdateRequired'].forEach((key) => this.userForm.get(key).setValue(response[key]) ); const expirationDate = response['pwdExpirationDate']; if (expirationDate) { this.userForm .get('pwdExpirationDate') .setValue(moment(expirationDate * 1000).format(this.pwdExpirationFormat)); } } getRequest(): UserFormModel { const userFormModel = new UserFormModel(); ['username', 'password', 'name', 'email', 'roles', 'enabled', 'pwdUpdateRequired'].forEach( (key) => (userFormModel[key] = this.userForm.get(key).value) ); const expirationDate = this.userForm.get('pwdExpirationDate').value; if (expirationDate) { const mom = moment(expirationDate, this.pwdExpirationFormat); if ( this.mode !== this.userFormMode.editing || this.response.pwdExpirationDate !== mom.unix() ) { mom.set({ hour: 23, minute: 59, second: 59 }); } userFormModel['pwdExpirationDate'] = mom.unix(); } return userFormModel; } createAction() { const userFormModel = this.getRequest(); this.userService.create(userFormModel).subscribe( () => { this.notificationService.show( NotificationType.success, $localize`Created user '${userFormModel.username}'` ); this.router.navigate(['/user-management/users']); }, () => { this.userForm.setErrors({ cdSubmitButton: true }); } ); } editAction() { if (this.isUserRemovingNeededRolePermissions()) { const initialState = { titleText: $localize`Update user`, buttonText: $localize`Continue`, bodyTpl: this.removeSelfUserReadUpdatePermissionTpl, onSubmit: () => { this.modalRef.close(); this.doEditAction(); }, onCancel: () => { this.userForm.setErrors({ cdSubmitButton: true }); this.userForm.get('roles').reset(this.userForm.get('roles').value); } }; this.modalRef = this.modalService.show(ConfirmationModalComponent, initialState); } else { this.doEditAction(); } } public isCurrentUser(): boolean { return this.authStorageService.getUsername() === this.userForm.getValue('username'); } private isUserChangingRoles(): boolean { const isCurrentUser = this.isCurrentUser(); return ( isCurrentUser && this.response && !_.isEqual(this.response.roles, this.userForm.getValue('roles')) ); } private isUserRemovingNeededRolePermissions(): boolean { const isCurrentUser = this.isCurrentUser(); return isCurrentUser && !this.hasUserReadUpdatePermissions(this.userForm.getValue('roles')); } private hasUserReadUpdatePermissions(roles: Array<string> = []) { for (const role of this.allRoles) { if (roles.indexOf(role.name) !== -1 && role.scopes_permissions['user']) { const userPermissions = role.scopes_permissions['user']; return ['read', 'update'].every((permission) => { return userPermissions.indexOf(permission) !== -1; }); } } return false; } private doEditAction() { const userFormModel = this.getRequest(); this.userService.update(userFormModel).subscribe( () => { if (this.isUserChangingRoles()) { this.authService.logout(() => { this.notificationService.show( NotificationType.info, $localize`You were automatically logged out because your roles have been changed.` ); }); } else { this.notificationService.show( NotificationType.success, $localize`Updated user '${userFormModel.username}'` ); this.router.navigate(['/user-management/users']); } }, () => { this.userForm.setErrors({ cdSubmitButton: true }); } ); } clearExpirationDate() { this.userForm.get('pwdExpirationDate').setValue(undefined); } submit() { if (this.mode === this.userFormMode.editing) { this.editAction(); } else { this.createAction(); } } }
10,530
33.415033
117
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-form/user-form.model.ts
export class UserFormModel { username: string; password: string; pwdExpirationDate: number; name: string; email: string; roles: Array<string>; enabled: boolean; pwdUpdateRequired: boolean; }
207
17.909091
29
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-list/user-list.component.html
<cd-user-tabs></cd-user-tabs> <cd-table [data]="users" columnMode="flex" [columns]="columns" identifier="username" selectionType="single" (fetchData)="getUsers()" (updateSelection)="updateSelection($event)"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> </cd-table> <ng-template #userRolesTpl let-value="value"> <span *ngFor="let role of value; last as isLast"> {{ role }}{{ !isLast ? ", " : "" }} </span> </ng-template> <ng-template #warningTpl let-column="column" let-value="value" let-row="row"> <div [class.border-danger]="row.remainingDays < this.expirationDangerAlert" [class.border-warning]="row.remainingDays < this.expirationWarningAlert && row.remainingDays >= this.expirationDangerAlert" class="border-margin"> <div class="warning-content"> {{ value }} </div> </div> </ng-template> <ng-template #durationTpl let-column="column" let-value="value" let-row="row"> <i *ngIf="row.remainingDays < this.expirationWarningAlert" i18n-title title="User's password is about to expire" [class.icon-danger-color]="row.remainingDays < this.expirationDangerAlert" [class.icon-warning-color]="row.remainingDays < this.expirationWarningAlert && row.remainingDays >= this.expirationDangerAlert" class="{{ icons.warning }}"></i> <span title="{{ value | cdDate }}">{{ row.remainingTimeWithoutSeconds / 1000 | duration }}</span> </ng-template>
1,707
35.340426
132
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-list/user-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, PermissionHelper } from '~/testing/unit-test-helper'; import { UserTabsComponent } from '../user-tabs/user-tabs.component'; import { UserListComponent } from './user-list.component'; describe('UserListComponent', () => { let component: UserListComponent; let fixture: ComponentFixture<UserListComponent>; configureTestBed({ imports: [ BrowserAnimationsModule, SharedModule, ToastrModule.forRoot(), NgbNavModule, RouterTestingModule, HttpClientTestingModule ], declarations: [UserListComponent, UserTabsComponent] }); beforeEach(() => { fixture = TestBed.createComponent(UserListComponent); component = fixture.componentInstance; }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should test all TableActions combinations', () => { const permissionHelper: PermissionHelper = new PermissionHelper(component.permission); const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions( component.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: ['Create', 'Edit', 'Delete'], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,update': { actions: ['Create', 'Edit'], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,delete': { actions: ['Create', 'Delete'], primary: { multiple: 'Create', executing: 'Delete', single: 'Delete', no: 'Create' } }, create: { actions: ['Create'], primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' } }, 'update,delete': { actions: ['Edit', 'Delete'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, update: { actions: ['Edit'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, delete: { actions: ['Delete'], primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); it('should calculate remaining days', () => { const day = 60 * 60 * 24 * 1000; let today = Date.now(); expect(component.getRemainingDays(today + day * 2 + 1000)).toBe(2); today = Date.now(); expect(component.getRemainingDays(today + day * 2 - 1000)).toBe(1); today = Date.now(); expect(component.getRemainingDays(today + day + 1000)).toBe(1); today = Date.now(); expect(component.getRemainingDays(today + 1)).toBe(0); today = Date.now(); expect(component.getRemainingDays(today - (day + 1))).toBe(0); expect(component.getRemainingDays(null)).toBe(undefined); expect(component.getRemainingDays(undefined)).toBe(undefined); }); });
3,610
35.846939
101
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-list/user-list.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { SettingsService } from '~/app/shared/api/settings.service'; import { UserService } from '~/app/shared/api/user.service'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { Permission } from '~/app/shared/models/permissions'; import { EmptyPipe } from '~/app/shared/pipes/empty.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { URLBuilderService } from '~/app/shared/services/url-builder.service'; const BASE_URL = 'user-management/users'; @Component({ selector: 'cd-user-list', templateUrl: './user-list.component.html', styleUrls: ['./user-list.component.scss'], providers: [{ provide: URLBuilderService, useValue: new URLBuilderService(BASE_URL) }] }) export class UserListComponent implements OnInit { @ViewChild('userRolesTpl', { static: true }) userRolesTpl: TemplateRef<any>; @ViewChild('warningTpl', { static: true }) warningTpl: TemplateRef<any>; @ViewChild('durationTpl', { static: true }) durationTpl: TemplateRef<any>; permission: Permission; tableActions: CdTableAction[]; columns: CdTableColumn[]; users: Array<any>; expirationWarningAlert: number; expirationDangerAlert: number; selection = new CdTableSelection(); icons = Icons; modalRef: NgbModalRef; constructor( private userService: UserService, private emptyPipe: EmptyPipe, private modalService: ModalService, private notificationService: NotificationService, private authStorageService: AuthStorageService, private urlBuilder: URLBuilderService, private settingsService: SettingsService, public actionLabels: ActionLabelsI18n ) { this.permission = this.authStorageService.getPermissions().user; const addAction: CdTableAction = { permission: 'create', icon: Icons.add, routerLink: () => this.urlBuilder.getCreate(), name: this.actionLabels.CREATE }; const editAction: CdTableAction = { permission: 'update', icon: Icons.edit, routerLink: () => this.selection.first() && this.urlBuilder.getEdit(this.selection.first().username), name: this.actionLabels.EDIT }; const deleteAction: CdTableAction = { permission: 'delete', icon: Icons.destroy, click: () => this.deleteUserModal(), name: this.actionLabels.DELETE }; this.tableActions = [addAction, editAction, deleteAction]; } ngOnInit() { this.columns = [ { name: $localize`Username`, prop: 'username', flexGrow: 1, cellTemplate: this.warningTpl }, { name: $localize`Name`, prop: 'name', flexGrow: 1, pipe: this.emptyPipe }, { name: $localize`Email`, prop: 'email', flexGrow: 1, pipe: this.emptyPipe }, { name: $localize`Roles`, prop: 'roles', flexGrow: 1, cellTemplate: this.userRolesTpl }, { name: $localize`Enabled`, prop: 'enabled', flexGrow: 1, cellTransformation: CellTemplate.checkIcon }, { name: $localize`Password expires`, prop: 'pwdExpirationDate', flexGrow: 1, cellTemplate: this.durationTpl } ]; const settings: string[] = ['USER_PWD_EXPIRATION_WARNING_1', 'USER_PWD_EXPIRATION_WARNING_2']; this.settingsService.getValues(settings).subscribe((data) => { this.expirationWarningAlert = data['USER_PWD_EXPIRATION_WARNING_1']; this.expirationDangerAlert = data['USER_PWD_EXPIRATION_WARNING_2']; }); } getUsers() { this.userService.list().subscribe((users: Array<any>) => { users.forEach((user) => { user['remainingTimeWithoutSeconds'] = 0; if (user['pwdExpirationDate'] && user['pwdExpirationDate'] > 0) { user['pwdExpirationDate'] = user['pwdExpirationDate'] * 1000; user['remainingTimeWithoutSeconds'] = this.getRemainingTimeWithoutSeconds( user.pwdExpirationDate ); user['remainingDays'] = this.getRemainingDays(user.pwdExpirationDate); } }); this.users = users; }); } updateSelection(selection: CdTableSelection) { this.selection = selection; } deleteUser(username: string) { this.userService.delete(username).subscribe( () => { this.getUsers(); this.modalRef.close(); this.notificationService.show( NotificationType.success, $localize`Deleted user '${username}'` ); }, () => { this.modalRef.componentInstance.stopLoadingSpinner(); } ); } deleteUserModal() { const sessionUsername = this.authStorageService.getUsername(); const username = this.selection.first().username; if (sessionUsername === username) { this.notificationService.show( NotificationType.error, $localize`Failed to delete user '${username}'`, $localize`You are currently logged in as '${username}'.` ); return; } this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: 'User', itemNames: [username], submitAction: () => this.deleteUser(username) }); } getWarningIconClass(expirationDays: number): any { if (expirationDays === null || this.expirationWarningAlert > 10) { return ''; } const remainingDays = this.getRemainingDays(expirationDays); if (remainingDays <= this.expirationDangerAlert) { return 'icon-danger-color'; } else { return 'icon-warning-color'; } } getWarningClass(expirationDays: number): any { if (expirationDays === null || this.expirationWarningAlert > 10) { return ''; } const remainingDays = this.getRemainingDays(expirationDays); if (remainingDays <= this.expirationDangerAlert) { return 'border-danger'; } else { return 'border-warning'; } } getRemainingDays(time: number): number { if (time === undefined || time == null) { return undefined; } if (time < 0) { return 0; } const toDays = 1000 * 60 * 60 * 24; return Math.max(0, Math.floor(this.getRemainingTime(time) / toDays)); } getRemainingTimeWithoutSeconds(time: number): number { const withSeconds = this.getRemainingTime(time); return Math.floor(withSeconds / (1000 * 60)) * 60 * 1000; } getRemainingTime(time: number): number { return time - Date.now(); } }
7,360
31.427313
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-password-form/user-password-form.component.html
<div class="cd-col-form"> <form #frm="ngForm" [formGroup]="userForm" novalidate> <div class="card"> <div i18n="form title" class="card-header">{{ action | titlecase }} {{ resource | upperFirst }}</div> <div class="card-body"> <!-- Old password --> <div class="form-group row"> <label class="cd-col-form-label required" for="oldpassword" i18n>Old password</label> <div class="cd-col-form-input"> <div class="input-group"> <input class="form-control" type="password" placeholder="Old password..." id="oldpassword" formControlName="oldpassword" autocomplete="new-password" autofocus> <button class="btn btn-light" cdPasswordButton="oldpassword"> </button> </div> <span class="invalid-feedback" *ngIf="userForm.showError('oldpassword', frm, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="userForm.showError('oldpassword', frm, 'notmatch')" i18n>The old and new passwords must be different.</span> </div> </div> <!-- New password --> <div class="form-group row"> <label class="cd-col-form-label" for="newpassword"> <span class="required" i18n>New password</span> <cd-helper *ngIf="passwordPolicyHelpText.length > 0" class="text-pre-wrap" html="{{ passwordPolicyHelpText }}"> </cd-helper> </label> <div class="cd-col-form-input"> <div class="input-group"> <input class="form-control" type="password" placeholder="Password..." id="newpassword" autocomplete="new-password" formControlName="newpassword"> <button type="button" class="btn btn-light" cdPasswordButton="newpassword"> </button> </div> <div class="password-strength-level"> <div class="{{ passwordStrengthLevelClass }}" data-toggle="tooltip" title="{{ passwordValuation }}"> </div> </div> <span class="invalid-feedback" *ngIf="userForm.showError('newpassword', frm, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="userForm.showError('newpassword', frm, 'notmatch')" i18n>The old and new passwords must be different.</span> <span class="invalid-feedback" *ngIf="userForm.showError('newpassword', frm, 'passwordPolicy')"> {{ passwordValuation }} </span> </div> </div> <!-- Confirm new password --> <div class="form-group row"> <label class="cd-col-form-label required" for="confirmnewpassword" i18n>Confirm new password</label> <div class="cd-col-form-input"> <div class="input-group"> <input class="form-control" type="password" autocomplete="new-password" placeholder="Confirm new password..." id="confirmnewpassword" formControlName="confirmnewpassword"> <button class="btn btn-light" cdPasswordButton="confirmnewpassword"> </button> </div> <span class="invalid-feedback" *ngIf="userForm.showError('confirmnewpassword', frm, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="userForm.showError('confirmnewpassword', frm, 'match')" i18n>Password confirmation doesn't match the new password.</span> </div> </div> </div> <div class="card-footer"> <cd-form-button-panel (submitActionEvent)="onSubmit()" [form]="userForm" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)" wrappingClass="text-right"></cd-form-button-panel> </div> </div> </form> </div>
4,719
39.689655
97
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-password-form/user-password-form.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { ComponentsModule } from '~/app/shared/components/components.module'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FormHelper } from '~/testing/unit-test-helper'; import { UserPasswordFormComponent } from './user-password-form.component'; describe('UserPasswordFormComponent', () => { let component: UserPasswordFormComponent; let fixture: ComponentFixture<UserPasswordFormComponent>; let form: CdFormGroup; let formHelper: FormHelper; let httpTesting: HttpTestingController; let router: Router; let authStorageService: AuthStorageService; configureTestBed({ imports: [ HttpClientTestingModule, RouterTestingModule, ReactiveFormsModule, ComponentsModule, ToastrModule.forRoot(), SharedModule ], declarations: [UserPasswordFormComponent] }); beforeEach(() => { fixture = TestBed.createComponent(UserPasswordFormComponent); component = fixture.componentInstance; form = component.userForm; httpTesting = TestBed.inject(HttpTestingController); router = TestBed.inject(Router); authStorageService = TestBed.inject(AuthStorageService); spyOn(router, 'navigate'); fixture.detectChanges(); formHelper = new FormHelper(form); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should validate old password required', () => { formHelper.expectErrorChange('oldpassword', '', 'required'); formHelper.expectValidChange('oldpassword', 'foo'); }); it('should validate password match', () => { formHelper.setValue('newpassword', 'aaa'); formHelper.expectErrorChange('confirmnewpassword', 'bbb', 'match'); formHelper.expectValidChange('confirmnewpassword', 'aaa'); }); it('should submit', () => { spyOn(component, 'onPasswordChange').and.callThrough(); spyOn(authStorageService, 'getUsername').and.returnValue('xyz'); formHelper.setMultipleValues({ oldpassword: 'foo', newpassword: 'bar' }); formHelper.setValue('confirmnewpassword', 'bar', true); component.onSubmit(); const request = httpTesting.expectOne('api/user/xyz/change_password'); expect(request.request.method).toBe('POST'); expect(request.request.body).toEqual({ old_password: 'foo', new_password: 'bar' }); request.flush({}); expect(component.onPasswordChange).toHaveBeenCalled(); expect(router.navigate).toHaveBeenCalledWith(['/login']); }); });
3,004
34.77381
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-password-form/user-password-form.component.ts
import { Component } from '@angular/core'; import { Validators } from '@angular/forms'; import { Router } from '@angular/router'; import _ from 'lodash'; import { UserService } from '~/app/shared/api/user.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { CdValidators } from '~/app/shared/forms/cd-validators'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { PasswordPolicyService } from '~/app/shared/services/password-policy.service'; @Component({ selector: 'cd-user-password-form', templateUrl: './user-password-form.component.html', styleUrls: ['./user-password-form.component.scss'] }) export class UserPasswordFormComponent { userForm: CdFormGroup; action: string; resource: string; passwordPolicyHelpText = ''; passwordStrengthLevelClass: string; passwordValuation: string; icons = Icons; constructor( public actionLabels: ActionLabelsI18n, public notificationService: NotificationService, public userService: UserService, public authStorageService: AuthStorageService, public formBuilder: CdFormBuilder, public router: Router, public passwordPolicyService: PasswordPolicyService ) { this.action = this.actionLabels.CHANGE; this.resource = $localize`password`; this.createForm(); } createForm() { this.passwordPolicyService.getHelpText().subscribe((helpText: string) => { this.passwordPolicyHelpText = helpText; }); this.userForm = this.formBuilder.group( { oldpassword: [ null, [ Validators.required, CdValidators.custom('notmatch', () => { return ( this.userForm && this.userForm.getValue('newpassword') === this.userForm.getValue('oldpassword') ); }) ] ], newpassword: [ null, [ Validators.required, CdValidators.custom('notmatch', () => { return ( this.userForm && this.userForm.getValue('oldpassword') === this.userForm.getValue('newpassword') ); }) ], [ CdValidators.passwordPolicy( this.userService, () => this.authStorageService.getUsername(), (_valid: boolean, credits: number, valuation: string) => { this.passwordStrengthLevelClass = this.passwordPolicyService.mapCreditsToCssClass( credits ); this.passwordValuation = _.defaultTo(valuation, ''); } ) ] ], confirmnewpassword: [null, [Validators.required]] }, { validators: [CdValidators.match('newpassword', 'confirmnewpassword')] } ); } onSubmit() { if (this.userForm.pristine) { return; } const username = this.authStorageService.getUsername(); const oldPassword = this.userForm.getValue('oldpassword'); const newPassword = this.userForm.getValue('newpassword'); this.userService.changePassword(username, oldPassword, newPassword).subscribe( () => this.onPasswordChange(), () => { this.userForm.setErrors({ cdSubmitButton: true }); } ); } /** * The function that is called after the password has been changed. * Override this in derived classes to change the behaviour. */ onPasswordChange() { this.notificationService.show(NotificationType.success, $localize`Updated user password"`); this.router.navigate(['/login']); } }
3,999
32.333333
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-tabs/user-tabs.component.html
<ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link" routerLink="/user-management/users" routerLinkActive="active" ariaCurrentWhenActive="page" [routerLinkActiveOptions]="{exact: true}" i18n>Users</a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/user-management/roles" routerLinkActive="active" ariaCurrentWhenActive="page" [routerLinkActiveOptions]="{exact: true}" i18n>Roles</a> </li> </ul>
510
25.894737
48
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-tabs/user-tabs.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { UserTabsComponent } from './user-tabs.component'; describe('UserTabsComponent', () => { let component: UserTabsComponent; let fixture: ComponentFixture<UserTabsComponent>; configureTestBed({ imports: [SharedModule, RouterTestingModule, HttpClientTestingModule, NgbNavModule], declarations: [UserTabsComponent] }); beforeEach(() => { fixture = TestBed.createComponent(UserTabsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
961
31.066667
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/user-tabs/user-tabs.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'cd-user-tabs', templateUrl: './user-tabs.component.html', styleUrls: ['./user-tabs.component.scss'] }) export class UserTabsComponent { url: string; constructor(public router: Router) {} }
310
21.214286
44
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/context/context.component.html
<ng-container *ngIf="{ ftMap: featureToggleMap$ | async, daemons: rgwDaemonService.daemons$ | async, selectedDaemon: rgwDaemonService.selectedDaemon$ | async } as data"> <ng-container *ngIf="data.ftMap && data.ftMap.rgw && permissions.rgw.read && isRgwRoute && data.daemons.length > 1"> <div class="cd-context-bar pt-3 pb-3"> <span class="me-1" i18n>Selected Object Gateway:</span> <div ngbDropdown placement="bottom-left" class="d-inline-block ms-2"> <button ngbDropdownToggle class="btn btn-outline-info ctx-bar-selected-rgw-daemon" i18n-title title="Select Object Gateway"> {{ data.selectedDaemon.id }} ( {{ data.selectedDaemon.zonegroup_name }} ) </button> <div ngbDropdownMenu> <ng-container *ngFor="let daemon of data.daemons"> <button ngbDropdownItem class="ctx-bar-available-rgw-daemon" (click)="onDaemonSelection(daemon)"> {{ daemon.id }} ( {{ daemon.zonegroup_name }} ) </button> </ng-container> </div> </div> </div> </ng-container> </ng-container>
1,211
42.285714
169
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/context/context.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of } from 'rxjs'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { FeatureTogglesMap, FeatureTogglesService } from '~/app/shared/services/feature-toggles.service'; import { configureTestBed, RgwHelper } from '~/testing/unit-test-helper'; import { ContextComponent } from './context.component'; describe('ContextComponent', () => { let component: ContextComponent; let fixture: ComponentFixture<ContextComponent>; let router: Router; let routerNavigateByUrlSpy: jasmine.Spy; let routerNavigateSpy: jasmine.Spy; let getPermissionsSpy: jasmine.Spy; let getFeatureTogglesSpy: jasmine.Spy; let ftMap: FeatureTogglesMap; let httpTesting: HttpTestingController; const daemonList = RgwHelper.getDaemonList(); configureTestBed({ declarations: [ContextComponent], imports: [HttpClientTestingModule, RouterTestingModule] }); beforeEach(() => { httpTesting = TestBed.inject(HttpTestingController); router = TestBed.inject(Router); routerNavigateByUrlSpy = spyOn(router, 'navigateByUrl'); routerNavigateByUrlSpy.and.returnValue(Promise.resolve(undefined)); routerNavigateSpy = spyOn(router, 'navigate'); getPermissionsSpy = spyOn(TestBed.inject(AuthStorageService), 'getPermissions'); getPermissionsSpy.and.returnValue( new Permissions({ rgw: ['read', 'update', 'create', 'delete'] }) ); getFeatureTogglesSpy = spyOn(TestBed.inject(FeatureTogglesService), 'get'); ftMap = new FeatureTogglesMap(); ftMap.rgw = true; getFeatureTogglesSpy.and.returnValue(of(ftMap)); fixture = TestBed.createComponent(ContextComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); it('should not show any info if not in RGW route', () => { component.isRgwRoute = false; expect(fixture.debugElement.nativeElement.textContent).toEqual(''); }); it('should select the default daemon', fakeAsync(() => { component.isRgwRoute = true; fixture.detectChanges(); tick(); const req = httpTesting.expectOne('api/rgw/daemon'); req.flush(daemonList); fixture.detectChanges(); const selectedDaemon = fixture.debugElement.nativeElement.querySelector( '.ctx-bar-selected-rgw-daemon' ); expect(selectedDaemon.textContent).toEqual(' daemon2 ( zonegroup2 ) '); const availableDaemons = fixture.debugElement.nativeElement.querySelectorAll( '.ctx-bar-available-rgw-daemon' ); expect(availableDaemons.length).toEqual(daemonList.length); expect(availableDaemons[0].textContent).toEqual(' daemon1 ( zonegroup1 ) '); component.ngOnDestroy(); })); it('should select the chosen daemon', fakeAsync(() => { component.isRgwRoute = true; fixture.detectChanges(); tick(); const req = httpTesting.expectOne('api/rgw/daemon'); req.flush(daemonList); fixture.detectChanges(); component.onDaemonSelection(daemonList[2]); expect(routerNavigateByUrlSpy).toHaveBeenCalledTimes(1); fixture.detectChanges(); tick(); expect(routerNavigateSpy).toHaveBeenCalledTimes(1); const selectedDaemon = fixture.debugElement.nativeElement.querySelector( '.ctx-bar-selected-rgw-daemon' ); expect(selectedDaemon.textContent).toEqual(' daemon3 ( zonegroup3 ) '); component.ngOnDestroy(); })); });
3,741
36.049505
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/context/context.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Event, NavigationEnd, Router } from '@angular/router'; import { NEVER, Subscription } from 'rxjs'; import { filter } from 'rxjs/operators'; import { RgwDaemon } from '~/app/ceph/rgw/models/rgw-daemon'; import { RgwDaemonService } from '~/app/shared/api/rgw-daemon.service'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { FeatureTogglesMap$, FeatureTogglesService } from '~/app/shared/services/feature-toggles.service'; import { TimerService } from '~/app/shared/services/timer.service'; @Component({ selector: 'cd-context', templateUrl: './context.component.html', styleUrls: ['./context.component.scss'] }) export class ContextComponent implements OnInit, OnDestroy { readonly REFRESH_INTERVAL = 5000; private subs = new Subscription(); private rgwUrlPrefix = '/rgw'; private rgwUserUrlPrefix = '/rgw/user'; private rgwBuckerUrlPrefix = '/rgw/bucket'; permissions: Permissions; featureToggleMap$: FeatureTogglesMap$; isRgwRoute = document.location.href.includes(this.rgwUserUrlPrefix) || document.location.href.includes(this.rgwBuckerUrlPrefix); constructor( private authStorageService: AuthStorageService, private featureToggles: FeatureTogglesService, private router: Router, private timerService: TimerService, public rgwDaemonService: RgwDaemonService ) {} ngOnInit() { this.permissions = this.authStorageService.getPermissions(); this.featureToggleMap$ = this.featureToggles.get(); // Check if route belongs to RGW: this.subs.add( this.router.events .pipe(filter((event: Event) => event instanceof NavigationEnd)) .subscribe( () => (this.isRgwRoute = [this.rgwBuckerUrlPrefix, this.rgwUserUrlPrefix].some((urlPrefix) => this.router.url.startsWith(urlPrefix) )) ) ); // Set daemon list polling only when in RGW route: this.subs.add( this.timerService .get(() => (this.isRgwRoute ? this.rgwDaemonService.list() : NEVER), this.REFRESH_INTERVAL) .subscribe() ); } ngOnDestroy() { this.subs.unsubscribe(); } onDaemonSelection(daemon: RgwDaemon) { this.rgwDaemonService.selectDaemon(daemon); this.reloadData(); } private reloadData() { const currentUrl = this.router.url; this.router.navigateByUrl(this.rgwUrlPrefix, { skipLocationChange: true }).finally(() => { this.router.navigate([currentUrl]); }); } }
2,628
31.8625
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/error/error.component.html
<head> <title>Error Page</title> <base target="_blank"> </head> <div class="container h-75"> <div class="row h-100 justify-content-center align-items-center"> <div class="blank-page"> <div *ngIf="header && message; else elseBlock"> <i [ngClass]="icon" class="mx-auto d-block"></i> <div class="mt-4 text-center"> <h3><b>{{ header }}</b></h3> <h4 class="mt-3" *ngIf="header !== message">{{ message }}</h4> <h4 *ngIf="section" i18n>Please consult the <a href="{{ docUrl }}">documentation</a> on how to configure and enable the {{ sectionInfo }} management functionality. </h4> </div> </div> <div class="mt-4"> <div class="text-center" *ngIf="(buttonName && buttonRoute) || uiConfig; else dashboardButton"> <button class="btn btn-primary ms-1" [routerLink]="buttonRoute" *ngIf="!uiConfig; else configureButtonTpl" i18n>{{ buttonName }}</button> <button class="btn btn-light ms-1" [routerLink]="secondaryButtonRoute" *ngIf="secondaryButtonName && secondaryButtonRoute" i18n>{{ secondaryButtonName }}</button> </div> </div> </div> </div> </div> <ng-template #configureButtonTpl> <button class="btn btn-primary" (click)="doConfigure()" [attr.title]="buttonTitle" *ngIf="uiConfig" i18n>{{ buttonName }}</button> </ng-template> <ng-template #elseBlock> <i class="fa fa-exclamation-triangle mx-auto d-block text-danger"></i> <div class="mt-4 text-center"> <h3 i18n><b>Page not Found</b></h3> <h4 class="mt-4" i18n>Sorry, we couldn’t find what you were looking for. The page you requested may have been changed or moved.</h4> </div> </ng-template> <ng-template #dashboardButton> <div class="mt-4 text-center"> <button class="btn btn-primary" [routerLink]="'/dashboard'" i18n>Go To Dashboard</button> </div> </ng-template>
2,147
30.588235
109
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/error/error.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ErrorComponent } from './error.component'; describe('ErrorComponent', () => { let component: ErrorComponent; let fixture: ComponentFixture<ErrorComponent>; configureTestBed({ declarations: [ErrorComponent], imports: [HttpClientTestingModule, RouterTestingModule, SharedModule, ToastrModule.forRoot()] }); beforeEach(() => { fixture = TestBed.createComponent(ErrorComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should show error message and header', () => { window.history.pushState({ message: 'Access Forbidden', header: 'User Denied' }, 'Errors'); component.fetchData(); fixture.detectChanges(); const header = fixture.debugElement.nativeElement.querySelector('h3'); expect(header.innerHTML).toContain('User Denied'); const message = fixture.debugElement.nativeElement.querySelector('h4'); expect(message.innerHTML).toContain('Access Forbidden'); }); it('should show 404 Page not Found if message and header are blank', () => { window.history.pushState({ message: '', header: '' }, 'Errors'); component.fetchData(); fixture.detectChanges(); const header = fixture.debugElement.nativeElement.querySelector('h3'); expect(header.innerHTML).toContain('Page not Found'); const message = fixture.debugElement.nativeElement.querySelector('h4'); expect(message.innerHTML).toContain('Sorry, we couldn’t find what you were looking for.'); }); });
1,927
37.56
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/error/error.component.ts
import { HttpClient } from '@angular/common/http'; import { Component, HostListener, OnDestroy, OnInit } from '@angular/core'; import { NavigationEnd, Router, RouterEvent } from '@angular/router'; import { Subscription } from 'rxjs'; import { filter } from 'rxjs/operators'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { DocService } from '~/app/shared/services/doc.service'; import { NotificationService } from '~/app/shared/services/notification.service'; @Component({ selector: 'cd-error', templateUrl: './error.component.html', styleUrls: ['./error.component.scss'] }) export class ErrorComponent implements OnDestroy, OnInit { header: string; message: string; section: string; sectionInfo: string; icon: string; docUrl: string; source: string; routerSubscription: Subscription; uiConfig: string; uiApiPath: string; buttonRoute: string; buttonName: string; buttonTitle: string; secondaryButtonRoute: string; secondaryButtonName: string; secondaryButtonTitle: string; component: string; constructor( private router: Router, private docService: DocService, private http: HttpClient, private notificationService: NotificationService ) {} ngOnInit() { this.fetchData(); this.routerSubscription = this.router.events .pipe(filter((event: RouterEvent) => event instanceof NavigationEnd)) .subscribe(() => { this.fetchData(); }); } doConfigure() { this.http.post(`ui-api/${this.uiApiPath}/configure`, {}).subscribe({ next: () => { this.notificationService.show(NotificationType.info, `Configuring ${this.component}`); }, error: (error: any) => { this.notificationService.show(NotificationType.error, error); }, complete: () => { setTimeout(() => { this.router.navigate([this.uiApiPath]); this.notificationService.show(NotificationType.success, `Configured ${this.component}`); }, 3000); } }); } @HostListener('window:beforeunload', ['$event']) unloadHandler(event: Event) { event.returnValue = false; } fetchData() { try { this.router.onSameUrlNavigation = 'reload'; this.message = history.state.message; this.header = history.state.header; this.section = history.state.section; this.sectionInfo = history.state.section_info; this.icon = history.state.icon; this.source = history.state.source; this.uiConfig = history.state.uiConfig; this.uiApiPath = history.state.uiApiPath; this.buttonRoute = history.state.button_route; this.buttonName = history.state.button_name; this.buttonTitle = history.state.button_title; this.secondaryButtonRoute = history.state.secondary_button_route; this.secondaryButtonName = history.state.secondary_button_name; this.secondaryButtonTitle = history.state.secondary_button_title; this.component = history.state.component; this.docUrl = this.docService.urlGenerator(this.section); } catch (error) { this.router.navigate(['/error']); } } ngOnDestroy() { if (this.routerSubscription) { this.routerSubscription.unsubscribe(); } } }
3,252
30.582524
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/error/error.ts
import { Icons } from '~/app/shared/enum/icons.enum'; export class DashboardError extends Error { header: string; message: string; icon: string; } export class DashboardNotFoundError extends DashboardError { header = $localize`Page Not Found`; message = $localize`Sorry, we couldn’t find what you were looking for. The page you requested may have been changed or moved.`; icon = Icons.warning; } export class DashboardForbiddenError extends DashboardError { header = $localize`Access Denied`; message = $localize`Sorry, you don’t have permission to view this page or resource.`; icon = Icons.lock; } export class DashboardUserDeniedError extends DashboardError { header = $localize`User Denied`; message = $localize`Sorry, the user does not exist in Ceph. You'll be logged out from the Identity Provider when you retry logging in.`; icon = Icons.warning; }
889
30.785714
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/layouts/blank-layout/blank-layout.component.html
<router-outlet></router-outlet>
32
15.5
31
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/layouts/blank-layout/blank-layout.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { BlankLayoutComponent } from './blank-layout.component'; describe('DefaultLayoutComponent', () => { let component: BlankLayoutComponent; let fixture: ComponentFixture<BlankLayoutComponent>; configureTestBed({ declarations: [BlankLayoutComponent], imports: [RouterTestingModule] }); beforeEach(() => { fixture = TestBed.createComponent(BlankLayoutComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
740
27.5
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/layouts/blank-layout/blank-layout.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'cd-blank-layout', templateUrl: './blank-layout.component.html', styleUrls: ['./blank-layout.component.scss'] }) export class BlankLayoutComponent {}
223
23.888889
47
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/layouts/login-layout/login-layout.component.html
<main class="login full-height"> <header> <nav class="navbar p-4"> <a class="navbar-brand"></a> <div class="form-inline"> <cd-language-selector></cd-language-selector> </div> </nav> </header> <section> <div class="container"> <div class="row full-height"> <div class="col-sm-12 col-md-6 d-sm-block login-form"> <router-outlet></router-outlet> </div> <div class="col-sm-12 col-md-6 d-sm-block branding-info"> <img src="assets/Ceph_Ceph_Logo_with_text_white.svg" alt="Ceph" class="img-fluid pb-3"> <ul class="list-inline"> <li class="list-inline-item p-3" *ngFor="let docItem of docItems"> <cd-doc section="{{ docItem.section }}" docText="{{ docItem.text }}" noSubscribe="true" i18n-docText></cd-doc> </li> </ul> <cd-custom-login-banner></cd-custom-login-banner> </div> </div> </div> </section> </main>
1,095
30.314286
65
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/layouts/login-layout/login-layout.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { LoginLayoutComponent } from './login-layout.component'; describe('LoginLayoutComponent', () => { let component: LoginLayoutComponent; let fixture: ComponentFixture<LoginLayoutComponent>; configureTestBed({ declarations: [LoginLayoutComponent], imports: [BrowserAnimationsModule, HttpClientTestingModule, RouterTestingModule, SharedModule] }); beforeEach(() => { fixture = TestBed.createComponent(LoginLayoutComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,013
33.965517
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/layouts/login-layout/login-layout.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'cd-login-layout', templateUrl: './login-layout.component.html', styleUrls: ['./login-layout.component.scss'] }) export class LoginLayoutComponent { docItems: any[] = [ { section: 'help', text: $localize`Help` }, { section: 'security', text: $localize`Security` }, { section: 'trademarks', text: $localize`Trademarks` } ]; }
414
26.666667
58
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/layouts/workbench-layout/workbench-layout.component.html
<block-ui> <cd-navigation> <div class="container-fluid h-100" [ngClass]="{'dashboard': (router.url == '/dashboard' || router.url == '/dashboard_3')}"> <cd-context></cd-context> <cd-breadcrumbs></cd-breadcrumbs> <router-outlet></router-outlet> </div> </cd-navigation> </block-ui>
316
27.818182
97
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/layouts/workbench-layout/workbench-layout.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { RbdService } from '~/app/shared/api/rbd.service'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { PipesModule } from '~/app/shared/pipes/pipes.module'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { configureTestBed } from '~/testing/unit-test-helper'; import { WorkbenchLayoutComponent } from './workbench-layout.component'; describe('WorkbenchLayoutComponent', () => { let component: WorkbenchLayoutComponent; let fixture: ComponentFixture<WorkbenchLayoutComponent>; configureTestBed({ imports: [RouterTestingModule, ToastrModule.forRoot(), PipesModule, HttpClientTestingModule], declarations: [WorkbenchLayoutComponent], schemas: [NO_ERRORS_SCHEMA], providers: [AuthStorageService, CssHelper, RbdService] }); beforeEach(() => { fixture = TestBed.createComponent(WorkbenchLayoutComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,351
36.555556
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/layouts/workbench-layout/workbench-layout.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { FaviconService } from '~/app/shared/services/favicon.service'; import { SummaryService } from '~/app/shared/services/summary.service'; import { TaskManagerService } from '~/app/shared/services/task-manager.service'; @Component({ selector: 'cd-workbench-layout', templateUrl: './workbench-layout.component.html', styleUrls: ['./workbench-layout.component.scss'], providers: [FaviconService] }) export class WorkbenchLayoutComponent implements OnInit, OnDestroy { private subs = new Subscription(); constructor( public router: Router, private summaryService: SummaryService, private taskManagerService: TaskManagerService, private faviconService: FaviconService ) {} ngOnInit() { this.subs.add(this.summaryService.startPolling()); this.subs.add(this.taskManagerService.init(this.summaryService)); this.faviconService.init(); } ngOnDestroy() { this.subs.unsubscribe(); } }
1,080
29.027778
80
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/navigation.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { NgbCollapseModule, NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'; import { SimplebarAngularModule } from 'simplebar-angular'; import { AppRoutingModule } from '~/app/app-routing.module'; import { SharedModule } from '~/app/shared/shared.module'; import { AuthModule } from '../auth/auth.module'; import { AboutComponent } from './about/about.component'; import { AdministrationComponent } from './administration/administration.component'; import { ApiDocsComponent } from './api-docs/api-docs.component'; import { BreadcrumbsComponent } from './breadcrumbs/breadcrumbs.component'; import { DashboardHelpComponent } from './dashboard-help/dashboard-help.component'; import { IdentityComponent } from './identity/identity.component'; import { NavigationComponent } from './navigation/navigation.component'; import { NotificationsComponent } from './notifications/notifications.component'; @NgModule({ imports: [ CommonModule, AuthModule, NgbCollapseModule, NgbDropdownModule, AppRoutingModule, SharedModule, SimplebarAngularModule, RouterModule ], declarations: [ AboutComponent, ApiDocsComponent, BreadcrumbsComponent, NavigationComponent, NotificationsComponent, DashboardHelpComponent, AdministrationComponent, IdentityComponent ], exports: [NavigationComponent, BreadcrumbsComponent] }) export class NavigationModule {}
1,554
34.340909
84
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/about/about.component.html
<div class="about-container"> <div class="modal-header"> <button type="button" class="btn-close float-end" aria-label="Close" (click)="activeModal.close()"> </button> </div> <div class="modal-body"> <img src="assets/Ceph_Ceph_Logo_with_text_red_white.svg" class="ceph-logo" alt="{{ projectConstants.organization }}"> <h3> <strong>{{ projectConstants.projectName }}</strong> </h3> <div class="product-versions"> <strong>Version</strong> <br> {{ versionNumber }} {{ versionHash }} <br> {{ versionName }} </div> <br> <dl> <dt>Ceph Manager</dt> <dd>{{ hostAddr }}</dd> <dt>User</dt> <dd>{{ modalVariables.user }}</dd> <dt>User Role</dt> <dd>{{ modalVariables.role }}</dd> <dt>Browser</dt> <dd>{{ modalVariables.browserName }}</dd> <dt>Browser Version</dt> <dd>{{ modalVariables.browserVersion }}</dd> <dt>Browser OS</dt> <dd>{{ modalVariables.browserOS }}</dd> </dl> </div> <div class="modal-footer"> <div class="text-left"> {{ projectConstants.copyright }} {{ projectConstants.license }} </div> </div> </div>
1,246
25.531915
60
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/about/about.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { BehaviorSubject } from 'rxjs'; import { SummaryService } from '~/app/shared/services/summary.service'; import { SharedModule } from '~/app/shared/shared.module'; import { environment } from '~/environments/environment'; import { configureTestBed } from '~/testing/unit-test-helper'; import { AboutComponent } from './about.component'; export class SummaryServiceMock { summaryDataSource = new BehaviorSubject({ version: 'ceph version 14.0.0-855-gb8193bb4cd ' + '(b8193bb4cda16ccc5b028c3e1df62bc72350a15d) nautilus (dev)', mgr_host: 'http://localhost:11000/' }); summaryData$ = this.summaryDataSource.asObservable(); subscribe(call: any) { return this.summaryData$.subscribe(call); } } describe('AboutComponent', () => { let component: AboutComponent; let fixture: ComponentFixture<AboutComponent>; configureTestBed({ imports: [SharedModule, HttpClientTestingModule], declarations: [AboutComponent], providers: [NgbActiveModal, { provide: SummaryService, useClass: SummaryServiceMock }] }); beforeEach(() => { fixture = TestBed.createComponent(AboutComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should parse version', () => { expect(component.versionNumber).toBe('14.0.0-855-gb8193bb4cd'); expect(component.versionHash).toBe('(b8193bb4cda16ccc5b028c3e1df62bc72350a15d)'); expect(component.versionName).toBe('nautilus (dev)'); }); it('should get host', () => { expect(component.hostAddr).toBe('localhost:11000'); }); it('should display copyright', () => { expect(component.projectConstants.copyright).toContain(environment.year); }); });
1,968
31.278689
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/about/about.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { detect } from 'detect-browser'; import { Subscription } from 'rxjs'; import { UserService } from '~/app/shared/api/user.service'; import { AppConstants } from '~/app/shared/constants/app.constants'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { SummaryService } from '~/app/shared/services/summary.service'; @Component({ selector: 'cd-about', templateUrl: './about.component.html', styleUrls: ['./about.component.scss'] }) export class AboutComponent implements OnInit, OnDestroy { modalVariables: any; versionNumber: string; versionHash: string; versionName: string; subs: Subscription; userPermission: Permission; projectConstants: typeof AppConstants; hostAddr: string; copyright: string; constructor( public activeModal: NgbActiveModal, private summaryService: SummaryService, private userService: UserService, private authStorageService: AuthStorageService ) { this.userPermission = this.authStorageService.getPermissions().user; } ngOnInit() { this.projectConstants = AppConstants; this.hostAddr = window.location.hostname; this.modalVariables = this.setVariables(); this.subs = this.summaryService.subscribe((summary) => { const version = summary.version.replace('ceph version ', '').split(' '); this.hostAddr = summary.mgr_host.replace(/(^\w+:|^)\/\//, '').replace(/\/$/, ''); this.versionNumber = version[0]; this.versionHash = version[1]; this.versionName = version.slice(2, version.length).join(' '); }); } ngOnDestroy(): void { this.subs.unsubscribe(); } setVariables() { const project = {} as any; project.user = localStorage.getItem('dashboard_username'); project.role = 'user'; if (this.userPermission.read) { this.userService.get(project.user).subscribe((data: any) => { project.role = data.roles; }); } const browser = detect(); project.browserName = browser && browser.name ? browser.name : 'Not detected'; project.browserVersion = browser && browser.version ? browser.version : 'Not detected'; project.browserOS = browser && browser.os ? browser.os : 'Not detected'; return project; } }
2,427
33.197183
91
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/administration/administration.component.html
<div ngbDropdown placement="bottom-right" *ngIf="userPermission.read"> <a ngbDropdownToggle class="dropdown-toggle" i18n-title title="Dashboard Settings" role="button"> <i [ngClass]="[icons.deepCheck]"></i> <span i18n class="d-md-none">Dashboard Settings</span> </a> <div ngbDropdownMenu> <button ngbDropdownItem *ngIf="userPermission.read" routerLink="/user-management" i18n>User management</button> <button ngbDropdownItem *ngIf="configOptPermission.read" routerLink="/telemetry" i18n>Telemetry configuration</button> </div> </div>
670
26.958333
53
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/administration/administration.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { AdministrationComponent } from './administration.component'; describe('AdministrationComponent', () => { let component: AdministrationComponent; let fixture: ComponentFixture<AdministrationComponent>; configureTestBed({ imports: [SharedModule], declarations: [AdministrationComponent] }); beforeEach(() => { fixture = TestBed.createComponent(AdministrationComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
747
27.769231
69
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/administration/administration.component.ts
import { Component } from '@angular/core'; import { Icons } from '~/app/shared/enum/icons.enum'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; @Component({ selector: 'cd-administration', templateUrl: './administration.component.html', styleUrls: ['./administration.component.scss'] }) export class AdministrationComponent { userPermission: Permission; configOptPermission: Permission; icons = Icons; constructor(private authStorageService: AuthStorageService) { const permissions = this.authStorageService.getPermissions(); this.userPermission = permissions.user; this.configOptPermission = permissions.configOpt; } }
746
31.478261
80
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/api-docs/api-docs.component.html
<div id="swagger-ui" class="apiDocs"></div>
50
11.75
27
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/api-docs/api-docs.component.ts
import { Component, OnInit } from '@angular/core'; import SwaggerUI from 'swagger-ui'; @Component({ selector: 'cd-api-docs', templateUrl: './api-docs.component.html', styleUrls: ['./api-docs.component.scss'] }) export class ApiDocsComponent implements OnInit { ngOnInit(): void { SwaggerUI({ url: window.location.origin + '/docs/openapi.json', dom_id: '#swagger-ui', layout: 'BaseLayout' }); } }
434
21.894737
57
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/breadcrumbs/breadcrumbs.component.html
<ol *ngIf="crumbs.length" class="breadcrumb"> <li *ngFor="let crumb of crumbs; let last = last" [ngClass]="{ 'active': last && finished }" class="breadcrumb-item"> <a *ngIf="!last && crumb.path !== null" [routerLink]="crumb.path" preserveFragment>{{ crumb.text }}</a> <span *ngIf="last || crumb.path === null">{{ crumb.text }}</span> </li> </ol>
388
31.416667
69
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/breadcrumbs/breadcrumbs.component.spec.ts
import { CommonModule } from '@angular/common'; import { Component } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { Title } from '@angular/platform-browser'; import { Router, Routes } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { PerformanceCounterBreadcrumbsResolver } from '~/app/app-routing.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { BreadcrumbsComponent } from './breadcrumbs.component'; describe('BreadcrumbsComponent', () => { let component: BreadcrumbsComponent; let fixture: ComponentFixture<BreadcrumbsComponent>; let router: Router; let titleService: Title; @Component({ selector: 'cd-fake', template: '' }) class FakeComponent {} const routes: Routes = [ { path: 'hosts', component: FakeComponent, data: { breadcrumbs: 'Cluster/Hosts' } }, { path: 'perf_counters', component: FakeComponent, data: { breadcrumbs: PerformanceCounterBreadcrumbsResolver } }, { path: 'block', data: { breadcrumbs: true, text: 'Block', path: null }, children: [ { path: 'rbd', data: { breadcrumbs: 'Images' }, children: [ { path: '', component: FakeComponent }, { path: 'add', component: FakeComponent, data: { breadcrumbs: 'Add' } } ] } ] }, { path: 'error', component: FakeComponent, data: { breadcrumbs: '' } } ]; configureTestBed({ declarations: [BreadcrumbsComponent, FakeComponent], imports: [CommonModule, RouterTestingModule.withRoutes(routes)], providers: [PerformanceCounterBreadcrumbsResolver] }); beforeEach(() => { fixture = TestBed.createComponent(BreadcrumbsComponent); router = TestBed.inject(Router); titleService = TestBed.inject(Title); component = fixture.componentInstance; fixture.detectChanges(); expect(component.crumbs).toEqual([]); }); it('should create', () => { expect(component).toBeTruthy(); expect(component.subscription).toBeDefined(); }); it('should run postProcess and split the breadcrumbs when navigating to hosts', fakeAsync(() => { fixture.ngZone.run(() => { router.navigateByUrl('/hosts'); }); tick(); expect(component.crumbs).toEqual([ { path: null, text: 'Cluster' }, { path: '/hosts', text: 'Hosts' } ]); })); it('should display empty breadcrumb when navigating to perf_counters from unknown path', fakeAsync(() => { fixture.ngZone.run(() => { router.navigateByUrl('/perf_counters'); }); tick(); expect(component.crumbs).toEqual([ { path: null, text: 'Cluster' }, { path: null, text: '' }, { path: '', text: 'Performance Counters' } ]); })); it('should display Monitor breadcrumb when navigating to perf_counters from Monitors', fakeAsync(() => { fixture.ngZone.run(() => { router.navigate(['/perf_counters'], { queryParams: { fromLink: '/monitor' } }); }); tick(); expect(component.crumbs).toEqual([ { path: null, text: 'Cluster' }, { path: '/monitor', text: 'Monitors' }, { path: '', text: 'Performance Counters' } ]); })); it('should display Hosts breadcrumb when navigating to perf_counters from Hosts', fakeAsync(() => { fixture.ngZone.run(() => { router.navigate(['/perf_counters'], { queryParams: { fromLink: '/hosts' } }); }); tick(); expect(component.crumbs).toEqual([ { path: null, text: 'Cluster' }, { path: '/hosts', text: 'Hosts' }, { path: '', text: 'Performance Counters' } ]); })); it('should show all 3 breadcrumbs when navigating to RBD Add', fakeAsync(() => { fixture.ngZone.run(() => { router.navigateByUrl('/block/rbd/add'); }); tick(); expect(component.crumbs).toEqual([ { path: null, text: 'Block' }, { path: '/block/rbd', text: 'Images' }, { path: '/block/rbd/add', text: 'Add' } ]); })); it('should unsubscribe on ngOnDestroy', () => { expect(component.subscription.closed).toBeFalsy(); component.ngOnDestroy(); expect(component.subscription.closed).toBeTruthy(); }); it('should display no breadcrumbs in page title when navigating to dashboard', fakeAsync(() => { fixture.ngZone.run(() => { router.navigateByUrl(''); }); tick(); expect(titleService.getTitle()).toEqual('Ceph'); })); it('should display no breadcrumbs in page title when a page is not found', fakeAsync(() => { fixture.ngZone.run(() => { router.navigateByUrl('/error'); }); tick(); expect(titleService.getTitle()).toEqual('Ceph'); })); it('should display 2 breadcrumbs in page title when navigating to hosts', fakeAsync(() => { fixture.ngZone.run(() => { router.navigateByUrl('/hosts'); }); tick(); expect(titleService.getTitle()).toEqual('Ceph: Cluster > Hosts'); })); it('should display 3 breadcrumbs in page title when navigating to RBD Add', fakeAsync(() => { fixture.ngZone.run(() => { router.navigateByUrl('/block/rbd/add'); }); tick(); expect(titleService.getTitle()).toEqual('Ceph: Block > Images > Add'); })); });
5,348
30.098837
108
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/breadcrumbs/breadcrumbs.component.ts
/* The MIT License Copyright (c) 2017 (null) McNull https://github.com/McNull Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { Component, Injector, OnDestroy } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { ActivatedRouteSnapshot, NavigationEnd, NavigationStart, Router } from '@angular/router'; import { concat, from, Observable, of, Subscription } from 'rxjs'; import { distinct, filter, first, mergeMap, toArray } from 'rxjs/operators'; import { BreadcrumbsResolver, IBreadcrumb } from '~/app/shared/models/breadcrumbs'; @Component({ selector: 'cd-breadcrumbs', templateUrl: './breadcrumbs.component.html', styleUrls: ['./breadcrumbs.component.scss'] }) export class BreadcrumbsComponent implements OnDestroy { crumbs: IBreadcrumb[] = []; /** * Useful for e2e tests. * This allow us to mark the breadcrumb as pending during the navigation from * one page to another. * This resolves the problem of validating the breadcrumb of a new page and * still get the value from the previous */ finished = false; subscription: Subscription; private defaultResolver = new BreadcrumbsResolver(); constructor(private router: Router, private injector: Injector, private titleService: Title) { this.subscription = this.router.events .pipe(filter((x) => x instanceof NavigationStart)) .subscribe(() => { this.finished = false; }); this.subscription = this.router.events .pipe(filter((x) => x instanceof NavigationEnd)) .subscribe(() => { const currentRoot = router.routerState.snapshot.root; this._resolveCrumbs(currentRoot) .pipe( mergeMap((x) => x), distinct((x) => x.text), toArray(), mergeMap((x) => { const y = this.postProcess(x); return this.wrapIntoObservable<IBreadcrumb[]>(y).pipe(first()); }) ) .subscribe((x) => { this.finished = true; this.crumbs = x; const title = this.getTitleFromCrumbs(this.crumbs); this.titleService.setTitle(title); }); }); } ngOnDestroy(): void { this.subscription.unsubscribe(); } private _resolveCrumbs(route: ActivatedRouteSnapshot): Observable<IBreadcrumb[]> { let crumbs$: Observable<IBreadcrumb[]>; const data = route.routeConfig && route.routeConfig.data; if (data && data.breadcrumbs) { let resolver: BreadcrumbsResolver; if (data.breadcrumbs.prototype instanceof BreadcrumbsResolver) { resolver = this.injector.get<BreadcrumbsResolver>(data.breadcrumbs); } else { resolver = this.defaultResolver; } const result = resolver.resolve(route); crumbs$ = this.wrapIntoObservable<IBreadcrumb[]>(result).pipe(first()); } else { crumbs$ = of([]); } if (route.firstChild) { crumbs$ = concat<IBreadcrumb[]>(crumbs$, this._resolveCrumbs(route.firstChild)); } return crumbs$; } postProcess(breadcrumbs: IBreadcrumb[]) { const result: IBreadcrumb[] = []; breadcrumbs.forEach((element) => { const split = element.text.split('/'); if (split.length > 1) { element.text = split[split.length - 1]; for (let i = 0; i < split.length - 1; i++) { result.push({ text: split[i], path: null }); } } result.push(element); }); return result; } isPromise(value: any): boolean { return value && typeof value.then === 'function'; } wrapIntoObservable<T>(value: T | Promise<T> | Observable<T>): Observable<T> { if (value instanceof Observable) { return value; } if (this.isPromise(value)) { return from(Promise.resolve(value)); } return of(value as T); } private getTitleFromCrumbs(crumbs: IBreadcrumb[]): string { const currentLocation = crumbs .map((crumb: IBreadcrumb) => { return crumb.text || ''; }) .join(' > '); if (currentLocation.length > 0) { return `Ceph: ${currentLocation}`; } else { return 'Ceph'; } } }
5,134
31.5
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/dashboard-help/dashboard-help.component.html
<div ngbDropdown placement="bottom-right"> <a ngbDropdownToggle i18n-title title="Help" role="button"> <i [ngClass]="[icons.questionCircle]"></i> <span i18n class="d-md-none">Help</span> </a> <div ngbDropdownMenu> <a ngbDropdownItem class="text-capitalize" [ngClass]="{'disabled': !docsUrl}" href="{{ docsUrl }}" target="_blank" i18n>documentation</a> <button ngbDropdownItem routerLink="/api-docs" target="_blank" i18n>API</button> <button ngbDropdownItem (click)="openAboutModal()" i18n>About</button> <button ngbDropdownItem (click)="openFeedbackModal()" i18n>Report an issue...</button> </div> </div>
786
25.233333
46
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/dashboard-help/dashboard-help.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { DashboardHelpComponent } from './dashboard-help.component'; describe('DashboardHelpComponent', () => { let component: DashboardHelpComponent; let fixture: ComponentFixture<DashboardHelpComponent>; configureTestBed({ imports: [HttpClientTestingModule, SharedModule, RouterTestingModule], declarations: [DashboardHelpComponent] }); beforeEach(() => { fixture = TestBed.createComponent(DashboardHelpComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
922
31.964286
74
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/dashboard-help/dashboard-help.component.ts
import { Component, OnInit } from '@angular/core'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { FeedbackComponent } from '~/app/ceph/shared/feedback/feedback.component'; import { Icons } from '~/app/shared/enum/icons.enum'; import { DocService } from '~/app/shared/services/doc.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { AboutComponent } from '../about/about.component'; @Component({ selector: 'cd-dashboard-help', templateUrl: './dashboard-help.component.html', styleUrls: ['./dashboard-help.component.scss'] }) export class DashboardHelpComponent implements OnInit { docsUrl: string; modalRef: NgbModalRef; icons = Icons; bsModalRef: NgbModalRef; constructor(private modalService: ModalService, private docService: DocService) {} ngOnInit() { this.docService.subscribeOnce('dashboard', (url: string) => { this.docsUrl = url; }); } openAboutModal() { this.modalRef = this.modalService.show(AboutComponent, null, { size: 'lg' }); } openFeedbackModal() { this.bsModalRef = this.modalService.show(FeedbackComponent, null, { size: 'lg' }); } }
1,164
29.657895
86
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/identity/identity.component.html
<div ngbDropdown placement="bottom-right"> <a ngbDropdownToggle i18n-title title="Logged in user" role="button"> <i [ngClass]="[icons.user]"></i> <span i18n class="d-md-none">Logged in user</span> </a> <div ngbDropdownMenu> <button ngbDropdownItem disabled i18n>Signed in as <strong>{{ username }}</strong></button> <hr class="dropdown-divider" /> <button ngbDropdownItem *ngIf="!sso" routerLink="/user-profile/edit"> <i [ngClass]="[icons.lock]"></i> <span i18n>Change password</span> </button> <button ngbDropdownItem (click)="logout()"> <i [ngClass]="[icons.signOut]"></i> <span i18n>Sign out</span> </button> </div> </div>
780
25.931034
70
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/identity/identity.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { IdentityComponent } from './identity.component'; describe('IdentityComponent', () => { let component: IdentityComponent; let fixture: ComponentFixture<IdentityComponent>; configureTestBed({ imports: [HttpClientTestingModule, SharedModule, RouterTestingModule], declarations: [IdentityComponent] }); beforeEach(() => { fixture = TestBed.createComponent(IdentityComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
886
30.678571
74
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/identity/identity.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthService } from '~/app/shared/api/auth.service'; import { Icons } from '~/app/shared/enum/icons.enum'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; @Component({ selector: 'cd-identity', templateUrl: './identity.component.html', styleUrls: ['./identity.component.scss'] }) export class IdentityComponent implements OnInit { sso: boolean; username: string; icons = Icons; constructor(private authStorageService: AuthStorageService, private authService: AuthService) {} ngOnInit() { this.username = this.authStorageService.getUsername(); this.sso = this.authStorageService.isSSO(); } logout() { this.authService.logout(); } }
761
26.214286
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/navigation/navigation.component.html
<div class="cd-navbar-main"> <cd-pwd-expiration-notification></cd-pwd-expiration-notification> <cd-telemetry-notification></cd-telemetry-notification> <cd-motd></cd-motd> <cd-notifications-sidebar></cd-notifications-sidebar> <div class="cd-navbar-top"> <nav class="navbar navbar-expand-md navbar-dark cd-navbar-brand"> <button class="btn btn-link py-0 ms-3" (click)="showMenuSidebar = !showMenuSidebar" aria-label="toggle sidebar visibility"> <i class="fa fa-bars fa-2x" aria-hidden="true"></i> </button> <a class="navbar-brand ms-2" href="#"> <img src="assets/Ceph_Ceph_Logo_with_text_white.svg" alt="Ceph" /> </a> <button type="button" class="navbar-toggler" (click)="toggleRightSidebar()"> <span i18n class="sr-only">Toggle navigation</span> <span class=""> <i class="fa fa-navicon fa-lg"></i> </span> </button> <div class="collapse navbar-collapse" [ngClass]="{'show': rightSidebarOpen}"> <ul class="nav navbar-nav cd-navbar-utility my-2 my-md-0"> <ng-container *ngTemplateOutlet="cd_utilities"> </ng-container> </ul> </div> </nav> </div> <div class="wrapper"> <!-- Content --> <nav id="sidebar" [ngClass]="{'active': !showMenuSidebar}"> <ngx-simplebar [options]="simplebar"> <ul class="list-unstyled components cd-navbar-primary"> <ng-container *ngTemplateOutlet="cd_menu"> </ng-container> </ul> </ngx-simplebar> </nav> <!-- Page Content --> <div id="content" [ngClass]="{'active': !showMenuSidebar}"> <ng-content></ng-content> </div> </div> <ng-template #cd_utilities> <li class="nav-item"> <cd-language-selector class="cd-navbar"></cd-language-selector> </li> <li class="nav-item"> <cd-notifications class="cd-navbar" (click)="toggleRightSidebar()"></cd-notifications> </li> <li class="nav-item"> <cd-dashboard-help class="cd-navbar"></cd-dashboard-help> </li> <li class="nav-item"> <cd-administration class="cd-navbar"></cd-administration> </li> <li class="nav-item"> <cd-identity class="cd-navbar"></cd-identity> </li> </ng-template> <ng-template #cd_menu> <ng-container *ngIf="enabledFeature$ | async as enabledFeature"> <!-- Dashboard --> <li routerLinkActive="active" class="nav-item tc_menuitem_dashboard"> <a routerLink="/dashboard" class="nav-link"> <span i18n>Dashboard</span>&nbsp; <i [ngClass]="[icons.health]" [ngStyle]="summaryData?.health_status | healthColor"></i> </a> </li> <!-- Cluster --> <li routerLinkActive="active" class="nav-item tc_menuitem_cluster" *ngIf="permissions.hosts.read || permissions.monitor.read || permissions.osd.read || permissions.configOpt.read || permissions.log.read || permissions.prometheus.read"> <a (click)="toggleSubMenu('cluster')" class="nav-link dropdown-toggle" [attr.aria-expanded]="displayedSubMenu === 'cluster'" aria-controls="cluster-nav" role="button"> <ng-container i18n>Cluster</ng-container> </a> <ul class="list-unstyled" id="cluster-nav" [ngbCollapse]="displayedSubMenu !== 'cluster'"> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_hosts" *ngIf="permissions.hosts.read"> <a i18n routerLink="/hosts">Hosts</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_cluster_inventory" *ngIf="permissions.hosts.read"> <a i18n routerLink="/inventory">Physical Disks</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_cluster_monitor" *ngIf="permissions.monitor.read"> <a i18n routerLink="/monitor/">Monitors</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_cluster_services" *ngIf="permissions.hosts.read"> <a i18n routerLink="/services/">Services</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_osds" *ngIf="permissions.osd.read"> <a i18n routerLink="/osd">OSDs</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_configuration" *ngIf="permissions.configOpt.read"> <a i18n routerLink="/configuration">Configuration</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_crush" *ngIf="permissions.osd.read"> <a i18n routerLink="/crush-map">CRUSH map</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_modules" *ngIf="permissions.configOpt.read"> <a i18n routerLink="/mgr-modules">Manager Modules</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_users" *ngIf="permissions.configOpt.read"> <a i18n routerLink="/ceph-users">Ceph Users</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_log" *ngIf="permissions.log.read"> <a i18n routerLink="/logs">Logs</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_monitoring" *ngIf="permissions.prometheus.read"> <a routerLink="/monitoring"> <ng-container i18n>Alerts</ng-container> <small *ngIf="prometheusAlertService.activeCriticalAlerts > 0" class="badge badge-danger ms-1">{{ prometheusAlertService.activeCriticalAlerts }}</small> <small *ngIf="prometheusAlertService.activeWarningAlerts > 0" class="badge badge-warning ms-1">{{ prometheusAlertService.activeWarningAlerts }}</small> </a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_upgrade" *ngIf="permissions.configOpt.read"> <a i18n routerLink="/upgrade">Upgrade</a> </li> </ul> </li> <!-- Pools --> <li routerLinkActive="active" class="nav-item tc_menuitem_pool" *ngIf="permissions.pool.read"> <a class="nav-link" i18n routerLink="/pool">Pools</a> </li> <!-- Block --> <li routerLinkActive="active" class="nav-item tc_menuitem_block" *ngIf="(permissions.rbdImage.read || permissions.rbdMirroring.read || permissions.iscsi.read) && (enabledFeature.rbd || enabledFeature.mirroring || enabledFeature.iscsi)"> <a class="nav-link dropdown-toggle" (click)="toggleSubMenu('block')" [attr.aria-expanded]="displayedSubMenu === 'block'" aria-controls="block-nav" role="button" [ngStyle]="blockHealthColor()"> <ng-container i18n>Block</ng-container> </a> <ul class="list-unstyled" id="block-nav" [ngbCollapse]="displayedSubMenu !== 'block'"> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_block_images" *ngIf="permissions.rbdImage.read && enabledFeature.rbd"> <a i18n routerLink="/block/rbd">Images</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_block_mirroring" *ngIf="permissions.rbdMirroring.read && enabledFeature.mirroring"> <a routerLink="/block/mirroring"> <ng-container i18n>Mirroring</ng-container> <small *ngIf="summaryData?.rbd_mirroring?.warnings !== 0" class="badge badge-warning">{{ summaryData?.rbd_mirroring?.warnings }}</small> <small *ngIf="summaryData?.rbd_mirroring?.errors !== 0" class="badge badge-danger">{{ summaryData?.rbd_mirroring?.errors }}</small> </a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_block_iscsi" *ngIf="permissions.iscsi.read && enabledFeature.iscsi"> <a i18n routerLink="/block/iscsi">iSCSI</a> </li> </ul> </li> <!-- NFS --> <li routerLinkActive="active" class="nav-item tc_menuitem_nfs" *ngIf="permissions.nfs.read && enabledFeature.nfs"> <a i18n class="nav-link" routerLink="/nfs">NFS</a> </li> <!-- Filesystem --> <li routerLinkActive="active" class="nav-item tc_menuitem_cephfs" *ngIf="permissions.cephfs.read && enabledFeature.cephfs"> <a i18n class="nav-link" routerLink="/cephfs">File Systems</a> </li> <!-- Object Gateway --> <li routerLinkActive="active" class="nav-item tc_menuitem_rgw" *ngIf="permissions.rgw.read && enabledFeature.rgw"> <a class="nav-link dropdown-toggle" (click)="toggleSubMenu('rgw')" [attr.aria-expanded]="displayedSubMenu === 'rgw'" aria-controls="gateway-nav" role="button"> <ng-container i18n>Object Gateway</ng-container> </a> <ul class="list-unstyled" id="gateway-nav" [ngbCollapse]="displayedSubMenu !== 'rgw'"> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_rgw_daemons"> <a i18n routerLink="/rgw/daemon">Gateways</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_rgw_users"> <a i18n routerLink="/rgw/user">Users</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_rgw_buckets"> <a i18n routerLink="/rgw/bucket">Buckets</a> </li> <li routerLinkActive="active" class="tc_submenuitem tc_submenuitem_rgw_buckets"> <a i18n routerLink="/rgw/multisite">Multisite</a> </li> </ul> </li> </ng-container> </ng-template> </div>
10,990
35.88255
110
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/navigation/navigation.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { SimplebarAngularModule } from 'simplebar-angular'; import { of } from 'rxjs'; import { Permission, Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { Features, FeatureTogglesMap, FeatureTogglesService } from '~/app/shared/services/feature-toggles.service'; import { PrometheusAlertService } from '~/app/shared/services/prometheus-alert.service'; import { SummaryService } from '~/app/shared/services/summary.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { NavigationComponent } from './navigation.component'; import { NotificationsComponent } from '../notifications/notifications.component'; import { AdministrationComponent } from '../administration/administration.component'; import { IdentityComponent } from '../identity/identity.component'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { DashboardHelpComponent } from '../dashboard-help/dashboard-help.component'; function everythingPermittedExcept(disabledPermissions: string[] = []): any { const permissions: Permissions = new Permissions({}); Object.keys(permissions).forEach( (key) => (permissions[key] = new Permission(disabledPermissions.includes(key) ? [] : ['read'])) ); return permissions; } function onlyPermitted(enabledPermissions: string[] = []): any { const permissions: Permissions = new Permissions({}); enabledPermissions.forEach((key) => (permissions[key] = new Permission(['read']))); return permissions; } function everythingEnabledExcept(features: Features[] = []): FeatureTogglesMap { const featureTogglesMap: FeatureTogglesMap = new FeatureTogglesMap(); features.forEach((key) => (featureTogglesMap[key] = false)); return featureTogglesMap; } function onlyEnabled(features: Features[] = []): FeatureTogglesMap { const featureTogglesMap: FeatureTogglesMap = new FeatureTogglesMap(); Object.keys(featureTogglesMap).forEach( (key) => (featureTogglesMap[key] = features.includes(<Features>key)) ); return featureTogglesMap; } describe('NavigationComponent', () => { let component: NavigationComponent; let fixture: ComponentFixture<NavigationComponent>; configureTestBed({ declarations: [ NavigationComponent, NotificationsComponent, AdministrationComponent, DashboardHelpComponent, IdentityComponent ], imports: [ HttpClientTestingModule, SharedModule, ToastrModule.forRoot(), RouterTestingModule, SimplebarAngularModule, NgbModule ], providers: [AuthStorageService, SummaryService, FeatureTogglesService, PrometheusAlertService] }); beforeEach(() => { spyOn(TestBed.inject(AuthStorageService), 'getPermissions').and.callFake(() => everythingPermittedExcept() ); spyOn(TestBed.inject(FeatureTogglesService), 'get').and.callFake(() => of(everythingEnabledExcept()) ); spyOn(TestBed.inject(SummaryService), 'subscribe').and.callFake(() => of({ health: { status: 'HEALTH_OK' } }) ); spyOn(TestBed.inject(PrometheusAlertService), 'getAlerts').and.callFake(() => of([])); fixture = TestBed.createComponent(NavigationComponent); component = fixture.componentInstance; fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); }); describe('Test Permissions', () => { const testCases: [string[], string[]][] = [ [ ['hosts'], [ '.tc_submenuitem_hosts', '.tc_submenuitem_cluster_inventory', '.tc_submenuitem_cluster_services' ] ], [['monitor'], ['.tc_submenuitem_cluster_monitor']], [['osd'], ['.tc_submenuitem_osds', '.tc_submenuitem_crush']], [ ['configOpt'], [ '.tc_submenuitem_configuration', '.tc_submenuitem_modules', '.tc_submenuitem_users', '.tc_submenuitem_upgrade' ] ], [['log'], ['.tc_submenuitem_log']], [['prometheus'], ['.tc_submenuitem_monitoring']], [['pool'], ['.tc_menuitem_pool']], [['rbdImage'], ['.tc_submenuitem_block_images']], [['rbdMirroring'], ['.tc_submenuitem_block_mirroring']], [['iscsi'], ['.tc_submenuitem_block_iscsi']], [['rbdImage', 'rbdMirroring', 'iscsi'], ['.tc_menuitem_block']], [['nfs'], ['.tc_menuitem_nfs']], [['cephfs'], ['.tc_menuitem_cephfs']], [ ['rgw'], [ '.tc_menuitem_rgw', '.tc_submenuitem_rgw_daemons', '.tc_submenuitem_rgw_buckets', '.tc_submenuitem_rgw_users' ] ] ]; for (const [disabledPermissions, selectors] of testCases) { it(`When disabled permissions: ${JSON.stringify( disabledPermissions )} => hidden: "${selectors}"`, () => { component.permissions = everythingPermittedExcept(disabledPermissions); component.enabledFeature$ = of(everythingEnabledExcept()); fixture.detectChanges(); for (const selector of selectors) { expect(fixture.debugElement.query(By.css(selector))).toBeFalsy(); } }); } for (const [enabledPermissions, selectors] of testCases) { it(`When enabled permissions: ${JSON.stringify( enabledPermissions )} => visible: "${selectors}"`, () => { component.permissions = onlyPermitted(enabledPermissions); component.enabledFeature$ = of(everythingEnabledExcept()); fixture.detectChanges(); for (const selector of selectors) { expect(fixture.debugElement.query(By.css(selector))).toBeTruthy(); } }); } }); describe('Test FeatureToggles', () => { const testCases: [Features[], string[]][] = [ [['rbd'], ['.tc_submenuitem_block_images']], [['mirroring'], ['.tc_submenuitem_block_mirroring']], [['iscsi'], ['.tc_submenuitem_block_iscsi']], [['rbd', 'mirroring', 'iscsi'], ['.tc_menuitem_block']], [['nfs'], ['.tc_menuitem_nfs']], [['cephfs'], ['.tc_menuitem_cephfs']], [ ['rgw'], [ '.tc_menuitem_rgw', '.tc_submenuitem_rgw_daemons', '.tc_submenuitem_rgw_buckets', '.tc_submenuitem_rgw_users' ] ] ]; for (const [disabledFeatures, selectors] of testCases) { it(`When disabled features: ${JSON.stringify( disabledFeatures )} => hidden: "${selectors}"`, () => { component.enabledFeature$ = of(everythingEnabledExcept(disabledFeatures)); component.permissions = everythingPermittedExcept(); fixture.detectChanges(); for (const selector of selectors) { expect(fixture.debugElement.query(By.css(selector))).toBeFalsy(); } }); } for (const [enabledFeatures, selectors] of testCases) { it(`When enabled features: ${JSON.stringify( enabledFeatures )} => visible: "${selectors}"`, () => { component.enabledFeature$ = of(onlyEnabled(enabledFeatures)); component.permissions = everythingPermittedExcept(); fixture.detectChanges(); for (const selector of selectors) { expect(fixture.debugElement.query(By.css(selector))).toBeTruthy(); } }); } }); describe('showTopNotification', () => { const notification1 = 'notificationName1'; const notification2 = 'notificationName2'; beforeEach(() => { component.notifications = []; }); it('should show notification', () => { component.showTopNotification(notification1, true); expect(component.notifications.includes(notification1)).toBeTruthy(); expect(component.notifications.length).toBe(1); }); it('should not add a second notification if it is already shown', () => { component.showTopNotification(notification1, true); component.showTopNotification(notification1, true); expect(component.notifications.includes(notification1)).toBeTruthy(); expect(component.notifications.length).toBe(1); }); it('should add a second notification if the first one is different', () => { component.showTopNotification(notification1, true); component.showTopNotification(notification2, true); expect(component.notifications.includes(notification1)).toBeTruthy(); expect(component.notifications.includes(notification2)).toBeTruthy(); expect(component.notifications.length).toBe(2); }); it('should hide an active notification', () => { component.showTopNotification(notification1, true); expect(component.notifications.includes(notification1)).toBeTruthy(); expect(component.notifications.length).toBe(1); component.showTopNotification(notification1, false); expect(component.notifications.length).toBe(0); }); it('should not fail if it tries to hide an inactive notification', () => { expect(() => component.showTopNotification(notification1, false)).not.toThrow(); expect(component.notifications.length).toBe(0); }); it('should keep other notifications if it hides one', () => { component.showTopNotification(notification1, true); component.showTopNotification(notification2, true); expect(component.notifications.length).toBe(2); component.showTopNotification(notification2, false); expect(component.notifications.length).toBe(1); expect(component.notifications.includes(notification1)).toBeTruthy(); }); }); });
9,892
35.640741
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/navigation/navigation.component.ts
import { Component, HostBinding, OnDestroy, OnInit } from '@angular/core'; import * as _ from 'lodash'; import { Subscription } from 'rxjs'; import { Icons } from '~/app/shared/enum/icons.enum'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { FeatureTogglesMap$, FeatureTogglesService } from '~/app/shared/services/feature-toggles.service'; import { MotdNotificationService } from '~/app/shared/services/motd-notification.service'; import { PrometheusAlertService } from '~/app/shared/services/prometheus-alert.service'; import { SummaryService } from '~/app/shared/services/summary.service'; import { TelemetryNotificationService } from '~/app/shared/services/telemetry-notification.service'; @Component({ selector: 'cd-navigation', templateUrl: './navigation.component.html', styleUrls: ['./navigation.component.scss'] }) export class NavigationComponent implements OnInit, OnDestroy { notifications: string[] = []; @HostBinding('class') get class(): string { return 'top-notification-' + this.notifications.length; } permissions: Permissions; enabledFeature$: FeatureTogglesMap$; summaryData: any; icons = Icons; rightSidebarOpen = false; // rightSidebar only opens when width is less than 768px showMenuSidebar = true; displayedSubMenu = ''; simplebar = { autoHide: false }; private subs = new Subscription(); constructor( private authStorageService: AuthStorageService, private summaryService: SummaryService, private featureToggles: FeatureTogglesService, private telemetryNotificationService: TelemetryNotificationService, public prometheusAlertService: PrometheusAlertService, private motdNotificationService: MotdNotificationService ) { this.permissions = this.authStorageService.getPermissions(); this.enabledFeature$ = this.featureToggles.get(); } ngOnInit() { this.subs.add( this.summaryService.subscribe((summary) => { this.summaryData = summary; }) ); /* Note: If you're going to add more top notifications please do not forget to increase the number of generated css-classes in section topNotification settings in the scss file. */ this.subs.add( this.authStorageService.isPwdDisplayed$.subscribe((isDisplayed) => { this.showTopNotification('isPwdDisplayed', isDisplayed); }) ); this.subs.add( this.telemetryNotificationService.update.subscribe((visible: boolean) => { this.showTopNotification('telemetryNotificationEnabled', visible); }) ); this.subs.add( this.motdNotificationService.motd$.subscribe((motd: any) => { this.showTopNotification('motdNotificationEnabled', _.isPlainObject(motd)); }) ); } ngOnDestroy(): void { this.subs.unsubscribe(); } blockHealthColor() { if (this.summaryData && this.summaryData.rbd_mirroring) { if (this.summaryData.rbd_mirroring.errors > 0) { return { color: '#f4926c' }; } else if (this.summaryData.rbd_mirroring.warnings > 0) { return { color: '#f0ad4e' }; } } return undefined; } toggleSubMenu(menu: string) { if (this.displayedSubMenu === menu) { this.displayedSubMenu = ''; } else { this.displayedSubMenu = menu; } } toggleRightSidebar() { this.rightSidebarOpen = !this.rightSidebarOpen; } showTopNotification(name: string, isDisplayed: boolean) { if (isDisplayed) { if (!this.notifications.includes(name)) { this.notifications.push(name); } } else { const index = this.notifications.indexOf(name); if (index >= 0) { this.notifications.splice(index, 1); } } } }
3,816
29.782258
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/notifications/notifications.component.html
<a i18n-title title="Tasks and Notifications" [ngClass]="{ 'running': hasRunningTasks }" (click)="toggleSidebar()"> <i [ngClass]="[icons.bell]"></i> <span class="dot" *ngIf="hasNotifications"> </span> <span class="d-md-none" i18n>Tasks and Notifications</span> </a>
299
24
45
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/notifications/notifications.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { CdNotification, CdNotificationConfig } from '~/app/shared/models/cd-notification'; import { ExecutingTask } from '~/app/shared/models/executing-task'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SummaryService } from '~/app/shared/services/summary.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { NotificationsComponent } from './notifications.component'; describe('NotificationsComponent', () => { let component: NotificationsComponent; let fixture: ComponentFixture<NotificationsComponent>; let summaryService: SummaryService; let notificationService: NotificationService; configureTestBed({ imports: [HttpClientTestingModule, SharedModule, ToastrModule.forRoot(), RouterTestingModule], declarations: [NotificationsComponent] }); beforeEach(() => { fixture = TestBed.createComponent(NotificationsComponent); component = fixture.componentInstance; summaryService = TestBed.inject(SummaryService); notificationService = TestBed.inject(NotificationService); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should subscribe and check if there are running tasks', () => { expect(component.hasRunningTasks).toBeFalsy(); const task = new ExecutingTask('task', { name: 'name' }); summaryService['summaryDataSource'].next({ executing_tasks: [task] }); expect(component.hasRunningTasks).toBeTruthy(); }); it('should create a dot if there are running notifications', () => { const notification = new CdNotification(new CdNotificationConfig()); const recent = notificationService['dataSource'].getValue(); recent.push(notification); notificationService['dataSource'].next(recent); expect(component.hasNotifications).toBeTruthy(); fixture.detectChanges(); const dot = fixture.debugElement.nativeElement.querySelector('.dot'); expect(dot).not.toBe(''); }); });
2,310
38.169492
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/navigation/notifications/notifications.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdNotification } from '~/app/shared/models/cd-notification'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SummaryService } from '~/app/shared/services/summary.service'; @Component({ selector: 'cd-notifications', templateUrl: './notifications.component.html', styleUrls: ['./notifications.component.scss'] }) export class NotificationsComponent implements OnInit, OnDestroy { icons = Icons; hasRunningTasks = false; hasNotifications = false; private subs = new Subscription(); constructor( public notificationService: NotificationService, private summaryService: SummaryService ) {} ngOnInit() { this.subs.add( this.summaryService.subscribe((summary) => { this.hasRunningTasks = summary.executing_tasks.length > 0; }) ); this.subs.add( this.notificationService.data$.subscribe((notifications: CdNotification[]) => { this.hasNotifications = notifications.length > 0; }) ); } ngOnDestroy(): void { this.subs.unsubscribe(); } toggleSidebar() { this.notificationService.toggleSidebar(); } }
1,304
26.1875
85
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/shared.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { FormlyModule } from '@ngx-formly/core'; import { FormlyBootstrapModule } from '@ngx-formly/bootstrap'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { ComponentsModule } from './components/components.module'; import { DataTableModule } from './datatable/datatable.module'; import { DirectivesModule } from './directives/directives.module'; import { PipesModule } from './pipes/pipes.module'; import { AuthGuardService } from './services/auth-guard.service'; import { AuthStorageService } from './services/auth-storage.service'; import { FormatterService } from './services/formatter.service'; import { FormlyArrayTypeComponent } from './forms/crud-form/formly-array-type/formly-array-type.component'; import { FormlyObjectTypeComponent } from './forms/crud-form/formly-object-type/formly-object-type.component'; import { FormlyInputTypeComponent } from './forms/crud-form/formly-input-type/formly-input-type.component'; import { FormlyTextareaTypeComponent } from './forms/crud-form/formly-textarea-type/formly-textarea-type.component'; @NgModule({ imports: [ CommonModule, PipesModule, ComponentsModule, DataTableModule, DirectivesModule, ReactiveFormsModule, FormlyModule.forRoot({ types: [ { name: 'array', component: FormlyArrayTypeComponent }, { name: 'object', component: FormlyObjectTypeComponent }, { name: 'input', component: FormlyInputTypeComponent } ], validationMessages: [{ name: 'required', message: 'This field is required' }] }), FormlyBootstrapModule ], declarations: [FormlyTextareaTypeComponent], exports: [ComponentsModule, PipesModule, DataTableModule, DirectivesModule], providers: [AuthStorageService, AuthGuardService, FormatterService, CssHelper] }) export class SharedModule {}
1,971
43.818182
116
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/api-client.spec.ts
import { ApiClient } from '~/app/shared/api/api-client'; class MockApiClient extends ApiClient {} describe('ApiClient', () => { const service = new MockApiClient(); it('should get the version header value', () => { expect(service.getVersionHeaderValue(1, 2)).toBe('application/vnd.ceph.api.v1.2+json'); }); });
324
26.083333
91
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/api-client.ts
export abstract class ApiClient { getVersionHeaderValue(major: number, minor: number) { return `application/vnd.ceph.api.v${major}.${minor}+json`; } }
159
25.666667
62
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/auth.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { Router, Routes } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { AuthStorageService } from '../services/auth-storage.service'; import { AuthService } from './auth.service'; describe('AuthService', () => { let service: AuthService; let httpTesting: HttpTestingController; const routes: Routes = [{ path: 'login', children: [] }]; configureTestBed({ providers: [AuthService, AuthStorageService], imports: [HttpClientTestingModule, RouterTestingModule.withRoutes(routes)] }); beforeEach(() => { service = TestBed.inject(AuthService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should login and save the user', fakeAsync(() => { const fakeCredentials = { username: 'foo', password: 'bar' }; const fakeResponse = { username: 'foo' }; service.login(fakeCredentials).subscribe(); const req = httpTesting.expectOne('api/auth'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual(fakeCredentials); req.flush(fakeResponse); tick(); expect(localStorage.getItem('dashboard_username')).toBe('foo'); })); it('should logout and remove the user', () => { const router = TestBed.inject(Router); spyOn(router, 'navigate').and.stub(); service.logout(); const req = httpTesting.expectOne('api/auth/logout'); expect(req.request.method).toBe('POST'); req.flush({ redirect_url: '#/login' }); expect(localStorage.getItem('dashboard_username')).toBe(null); expect(router.navigate).toBeCalledTimes(1); }); });
1,948
32.603448
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/auth.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import * as _ from 'lodash'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { Credentials } from '../models/credentials'; import { LoginResponse } from '../models/login-response'; import { AuthStorageService } from '../services/auth-storage.service'; @Injectable({ providedIn: 'root' }) export class AuthService { constructor( private authStorageService: AuthStorageService, private http: HttpClient, private router: Router, private route: ActivatedRoute ) {} check(token: string) { return this.http.post('api/auth/check', { token: token }); } login(credentials: Credentials): Observable<LoginResponse> { return this.http.post('api/auth', credentials).pipe( tap((resp: LoginResponse) => { this.authStorageService.set( resp.username, resp.permissions, resp.sso, resp.pwdExpirationDate, resp.pwdUpdateRequired ); }) ); } logout(callback: Function = null) { return this.http.post('api/auth/logout', null).subscribe((resp: any) => { this.authStorageService.remove(); const url = _.get(this.route.snapshot.queryParams, 'returnUrl', '/login'); this.router.navigate([url], { skipLocationChange: true }); if (callback) { callback(); } window.location.replace(resp.redirect_url); }); } }
1,547
27.666667
80
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/ceph-service.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { ApiClient } from '~/app/shared/api/api-client'; import { Daemon } from '../models/daemon.interface'; import { CephServiceSpec } from '../models/service.interface'; import { PaginateObservable } from './paginate.model'; @Injectable({ providedIn: 'root' }) export class CephServiceService extends ApiClient { private url = 'api/service'; constructor(private http: HttpClient) { super(); } list(httpParams: HttpParams, serviceName?: string): PaginateObservable<CephServiceSpec[]> { const options = { headers: { Accept: this.getVersionHeaderValue(2, 0) }, params: httpParams }; options['observe'] = 'response'; if (serviceName) { options.params = options.params.append('service_name', serviceName); } return new PaginateObservable<CephServiceSpec[]>( this.http.get<CephServiceSpec[]>(this.url, options) ); } getDaemons(serviceName?: string): Observable<Daemon[]> { return this.http.get<Daemon[]>(`${this.url}/${serviceName}/daemons`); } create(serviceSpec: { [key: string]: any }) { const serviceName = serviceSpec['service_id'] ? `${serviceSpec['service_type']}.${serviceSpec['service_id']}` : serviceSpec['service_type']; return this.http.post( this.url, { service_name: serviceName, service_spec: serviceSpec }, { observe: 'response' } ); } update(serviceSpec: { [key: string]: any }) { const serviceName = serviceSpec['service_id'] ? `${serviceSpec['service_type']}.${serviceSpec['service_id']}` : serviceSpec['service_type']; return this.http.put( `${this.url}/${serviceName}`, { service_name: serviceName, service_spec: serviceSpec }, { observe: 'response' } ); } delete(serviceName: string) { return this.http.delete(`${this.url}/${serviceName}`, { observe: 'response' }); } getKnownTypes(): Observable<string[]> { return this.http.get<string[]>(`${this.url}/known_types`); } }
2,170
27.946667
93
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/ceph-user.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CephUserService { constructor(private http: HttpClient) {} export(entities: string[]) { return this.http.post('api/cluster/user/export', { entities: entities }); } }
324
22.214286
77
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/cephfs.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CephfsService } from './cephfs.service'; describe('CephfsService', () => { let service: CephfsService; let httpTesting: HttpTestingController; configureTestBed({ imports: [HttpClientTestingModule], providers: [CephfsService] }); beforeEach(() => { service = TestBed.inject(CephfsService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call list', () => { service.list().subscribe(); const req = httpTesting.expectOne('api/cephfs'); expect(req.request.method).toBe('GET'); }); it('should call getCephfs', () => { service.getCephfs(1).subscribe(); const req = httpTesting.expectOne('api/cephfs/1'); expect(req.request.method).toBe('GET'); }); it('should call getClients', () => { service.getClients(1).subscribe(); const req = httpTesting.expectOne('api/cephfs/1/clients'); expect(req.request.method).toBe('GET'); }); it('should call getTabs', () => { service.getTabs(2).subscribe(); const req = httpTesting.expectOne('ui-api/cephfs/2/tabs'); expect(req.request.method).toBe('GET'); }); it('should call getMdsCounters', () => { service.getMdsCounters('1').subscribe(); const req = httpTesting.expectOne('api/cephfs/1/mds_counters'); expect(req.request.method).toBe('GET'); }); it('should call lsDir', () => { service.lsDir(1).subscribe(); const req = httpTesting.expectOne('ui-api/cephfs/1/ls_dir?depth=2'); expect(req.request.method).toBe('GET'); service.lsDir(2, '/some/path').subscribe(); httpTesting.expectOne('ui-api/cephfs/2/ls_dir?depth=2&path=%252Fsome%252Fpath'); }); it('should call mkSnapshot', () => { service.mkSnapshot(3, '/some/path').subscribe(); const req = httpTesting.expectOne('api/cephfs/3/snapshot?path=%252Fsome%252Fpath'); expect(req.request.method).toBe('POST'); service.mkSnapshot(4, '/some/other/path', 'snap').subscribe(); httpTesting.expectOne('api/cephfs/4/snapshot?path=%252Fsome%252Fother%252Fpath&name=snap'); }); it('should call rmSnapshot', () => { service.rmSnapshot(1, '/some/path', 'snap').subscribe(); const req = httpTesting.expectOne('api/cephfs/1/snapshot?path=%252Fsome%252Fpath&name=snap'); expect(req.request.method).toBe('DELETE'); }); it('should call updateQuota', () => { service.quota(1, '/some/path', { max_bytes: 1024 }).subscribe(); let req = httpTesting.expectOne('api/cephfs/1/quota?path=%252Fsome%252Fpath'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ max_bytes: 1024 }); service.quota(1, '/some/path', { max_files: 10 }).subscribe(); req = httpTesting.expectOne('api/cephfs/1/quota?path=%252Fsome%252Fpath'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ max_files: 10 }); service.quota(1, '/some/path', { max_bytes: 1024, max_files: 10 }).subscribe(); req = httpTesting.expectOne('api/cephfs/1/quota?path=%252Fsome%252Fpath'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ max_bytes: 1024, max_files: 10 }); }); });
3,467
34.030303
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/cephfs.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import _ from 'lodash'; import { Observable } from 'rxjs'; import { cdEncode } from '../decorators/cd-encode'; import { CephfsDir, CephfsQuotas } from '../models/cephfs-directory-models'; @cdEncode @Injectable({ providedIn: 'root' }) export class CephfsService { baseURL = 'api/cephfs'; baseUiURL = 'ui-api/cephfs'; constructor(private http: HttpClient) {} list() { return this.http.get(`${this.baseURL}`); } lsDir(id: number, path?: string): Observable<CephfsDir[]> { let apiPath = `${this.baseUiURL}/${id}/ls_dir?depth=2`; if (path) { apiPath += `&path=${encodeURIComponent(path)}`; } return this.http.get<CephfsDir[]>(apiPath); } getCephfs(id: number) { return this.http.get(`${this.baseURL}/${id}`); } getTabs(id: number) { return this.http.get(`ui-api/cephfs/${id}/tabs`); } getClients(id: number) { return this.http.get(`${this.baseURL}/${id}/clients`); } evictClient(fsId: number, clientId: number) { return this.http.delete(`${this.baseURL}/${fsId}/client/${clientId}`); } getMdsCounters(id: string) { return this.http.get(`${this.baseURL}/${id}/mds_counters`); } mkSnapshot(id: number, path: string, name?: string) { let params = new HttpParams(); params = params.append('path', path); if (!_.isUndefined(name)) { params = params.append('name', name); } return this.http.post(`${this.baseURL}/${id}/snapshot`, null, { params }); } rmSnapshot(id: number, path: string, name: string) { let params = new HttpParams(); params = params.append('path', path); params = params.append('name', name); return this.http.delete(`${this.baseURL}/${id}/snapshot`, { params }); } quota(id: number, path: string, quotas: CephfsQuotas) { let params = new HttpParams(); params = params.append('path', path); return this.http.put(`${this.baseURL}/${id}/quota`, quotas, { observe: 'response', params }); } }
2,081
26.038961
78
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/cluster.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { fakeAsync, TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ClusterService } from './cluster.service'; describe('ClusterService', () => { let service: ClusterService; let httpTesting: HttpTestingController; configureTestBed({ imports: [HttpClientTestingModule], providers: [ClusterService] }); beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(ClusterService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call getStatus', () => { service.getStatus().subscribe(); const req = httpTesting.expectOne('api/cluster'); expect(req.request.method).toBe('GET'); }); it('should update cluster status', fakeAsync(() => { service.updateStatus('fakeStatus').subscribe(); const req = httpTesting.expectOne('api/cluster'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ status: 'fakeStatus' }); })); });
1,240
27.860465
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/cluster.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ClusterService { baseURL = 'api/cluster'; constructor(private http: HttpClient) {} getStatus(): Observable<string> { return this.http.get<string>(`${this.baseURL}`, { headers: { Accept: 'application/vnd.ceph.api.v0.1+json' } }); } updateStatus(status: string) { return this.http.put( `${this.baseURL}`, { status: status }, { headers: { Accept: 'application/vnd.ceph.api.v0.1+json' } } ); } }
630
21.535714
67
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/configuration.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { ConfigFormCreateRequestModel } from '~/app/ceph/cluster/configuration/configuration-form/configuration-form-create-request.model'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ConfigurationService } from './configuration.service'; describe('ConfigurationService', () => { let service: ConfigurationService; let httpTesting: HttpTestingController; configureTestBed({ providers: [ConfigurationService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(ConfigurationService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call getConfigData', () => { service.getConfigData().subscribe(); const req = httpTesting.expectOne('api/cluster_conf/'); expect(req.request.method).toBe('GET'); }); it('should call get', () => { service.get('configOption').subscribe(); const req = httpTesting.expectOne('api/cluster_conf/configOption'); expect(req.request.method).toBe('GET'); }); it('should call create', () => { const configOption = new ConfigFormCreateRequestModel(); configOption.name = 'Test option'; configOption.value = [ { section: 'section1', value: 'value1' }, { section: 'section2', value: 'value2' } ]; service.create(configOption).subscribe(); const req = httpTesting.expectOne('api/cluster_conf/'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual(configOption); }); it('should call bulkCreate', () => { const configOptions = { configOption1: { section: 'section', value: 'value' }, configOption2: { section: 'section', value: 'value' } }; service.bulkCreate(configOptions).subscribe(); const req = httpTesting.expectOne('api/cluster_conf/'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual(configOptions); }); it('should call filter', () => { const configOptions = ['configOption1', 'configOption2', 'configOption3']; service.filter(configOptions).subscribe(); const req = httpTesting.expectOne( 'api/cluster_conf/filter?names=configOption1,configOption2,configOption3' ); expect(req.request.method).toBe('GET'); }); it('should call delete', () => { service.delete('testOption', 'testSection').subscribe(); const reg = httpTesting.expectOne('api/cluster_conf/testOption?section=testSection'); expect(reg.request.method).toBe('DELETE'); }); it('should get value', () => { const config = { default: 'a', value: [ { section: 'global', value: 'b' }, { section: 'mon', value: 'c' }, { section: 'mon.1', value: 'd' }, { section: 'mds', value: 'e' } ] }; expect(service.getValue(config, 'mon.1')).toBe('d'); expect(service.getValue(config, 'mon')).toBe('c'); expect(service.getValue(config, 'mds.1')).toBe('e'); expect(service.getValue(config, 'mds')).toBe('e'); expect(service.getValue(config, 'osd')).toBe('b'); config.value = []; expect(service.getValue(config, 'osd')).toBe('a'); }); });
3,396
32.97
139
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/configuration.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { ConfigFormCreateRequestModel } from '~/app/ceph/cluster/configuration/configuration-form/configuration-form-create-request.model'; @Injectable({ providedIn: 'root' }) export class ConfigurationService { constructor(private http: HttpClient) {} private findValue(config: any, section: string) { if (!config.value) { return undefined; } return config.value.find((v: any) => v.section === section); } getValue(config: any, section: string) { let val = this.findValue(config, section); if (!val) { const indexOfDot = section.indexOf('.'); if (indexOfDot !== -1) { val = this.findValue(config, section.substring(0, indexOfDot)); } } if (!val) { val = this.findValue(config, 'global'); } if (val) { return val.value; } return config.default; } getConfigData() { return this.http.get('api/cluster_conf/'); } get(configOption: string) { return this.http.get(`api/cluster_conf/${configOption}`); } filter(configOptionNames: Array<string>) { return this.http.get(`api/cluster_conf/filter?names=${configOptionNames.join(',')}`); } create(configOption: ConfigFormCreateRequestModel) { return this.http.post('api/cluster_conf/', configOption); } delete(configOption: string, section: string) { return this.http.delete(`api/cluster_conf/${configOption}?section=${section}`); } bulkCreate(configOptions: object) { return this.http.put('api/cluster_conf/', configOptions); } }
1,623
26.066667
139
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/crush-rule.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CrushRuleService } from './crush-rule.service'; describe('CrushRuleService', () => { let service: CrushRuleService; let httpTesting: HttpTestingController; const apiPath = 'api/crush_rule'; configureTestBed({ imports: [HttpClientTestingModule], providers: [CrushRuleService] }); beforeEach(() => { service = TestBed.inject(CrushRuleService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call create', () => { service.create({ root: 'default', name: 'someRule', failure_domain: 'osd' }).subscribe(); const req = httpTesting.expectOne(apiPath); expect(req.request.method).toBe('POST'); }); it('should call delete', () => { service.delete('test').subscribe(); const req = httpTesting.expectOne(`${apiPath}/test`); expect(req.request.method).toBe('DELETE'); }); it('should call getInfo', () => { service.getInfo().subscribe(); const req = httpTesting.expectOne(`ui-${apiPath}/info`); expect(req.request.method).toBe('GET'); }); });
1,380
27.770833
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/crush-rule.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { CrushRuleConfig } from '../models/crush-rule'; @Injectable({ providedIn: 'root' }) export class CrushRuleService { apiPath = 'api/crush_rule'; formTooltips = { // Copied from /doc/rados/operations/crush-map.rst root: $localize`The name of the node under which data should be placed.`, failure_domain: $localize`The type of CRUSH nodes across which we should separate replicas.`, device_class: $localize`The device class data should be placed on.` }; constructor(private http: HttpClient) {} create(rule: CrushRuleConfig) { return this.http.post(this.apiPath, rule, { observe: 'response' }); } delete(name: string) { return this.http.delete(`${this.apiPath}/${name}`, { observe: 'response' }); } getInfo() { return this.http.get(`ui-${this.apiPath}/info`); } }
921
26.939394
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/custom-login-banner.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CustomLoginBannerService } from './custom-login-banner.service'; describe('CustomLoginBannerService', () => { let service: CustomLoginBannerService; let httpTesting: HttpTestingController; const baseUiURL = 'ui-api/login/custom_banner'; configureTestBed({ providers: [CustomLoginBannerService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(CustomLoginBannerService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call getBannerText', () => { service.getBannerText().subscribe(); const req = httpTesting.expectOne(baseUiURL); expect(req.request.method).toBe('GET'); }); });
1,028
27.583333
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/custom-login-banner.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CustomLoginBannerService { baseUiURL = 'ui-api/login/custom_banner'; constructor(private http: HttpClient) {} getBannerText() { return this.http.get<string>(this.baseUiURL); } }
339
20.25
50
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/daemon.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { DaemonService } from './daemon.service'; describe('DaemonService', () => { let service: DaemonService; let httpTesting: HttpTestingController; configureTestBed({ providers: [DaemonService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(DaemonService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call action', () => { const put_data: any = { action: 'start', container_image: null }; service.action('osd.1', 'start').subscribe(); const req = httpTesting.expectOne('api/daemon/osd.1'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual(put_data); }); });
1,055
25.4
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/daemon.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { cdEncode } from '~/app/shared/decorators/cd-encode'; @cdEncode @Injectable({ providedIn: 'root' }) export class DaemonService { private url = 'api/daemon'; constructor(private http: HttpClient) {} action(daemonName: string, actionType: string) { return this.http.put( `${this.url}/${daemonName}`, { action: actionType, container_image: null }, { headers: { Accept: 'application/vnd.ceph.api.v0.1+json' }, observe: 'response' } ); } }
622
20.482759
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/erasure-code-profile.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ErasureCodeProfile } from '../models/erasure-code-profile'; import { ErasureCodeProfileService } from './erasure-code-profile.service'; describe('ErasureCodeProfileService', () => { let service: ErasureCodeProfileService; let httpTesting: HttpTestingController; const apiPath = 'api/erasure_code_profile'; const testProfile: ErasureCodeProfile = { name: 'test', plugin: 'jerasure', k: 2, m: 1 }; configureTestBed({ imports: [HttpClientTestingModule], providers: [ErasureCodeProfileService] }); beforeEach(() => { service = TestBed.inject(ErasureCodeProfileService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call list', () => { service.list().subscribe(); const req = httpTesting.expectOne(apiPath); expect(req.request.method).toBe('GET'); }); it('should call create', () => { service.create(testProfile).subscribe(); const req = httpTesting.expectOne(apiPath); expect(req.request.method).toBe('POST'); }); it('should call delete', () => { service.delete('test').subscribe(); const req = httpTesting.expectOne(`${apiPath}/test`); expect(req.request.method).toBe('DELETE'); }); it('should call getInfo', () => { service.getInfo().subscribe(); const req = httpTesting.expectOne(`ui-${apiPath}/info`); expect(req.request.method).toBe('GET'); }); });
1,721
29.75
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/erasure-code-profile.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { ErasureCodeProfile } from '../models/erasure-code-profile'; @Injectable({ providedIn: 'root' }) export class ErasureCodeProfileService { apiPath = 'api/erasure_code_profile'; formTooltips = { // Copied from /doc/rados/operations/erasure-code.*.rst k: $localize`Each object is split in data-chunks parts, each stored on a different OSD.`, m: $localize`Compute coding chunks for each object and store them on different OSDs. The number of coding chunks is also the number of OSDs that can be down without losing data.`, plugins: { jerasure: { description: $localize`The jerasure plugin is the most generic and flexible plugin, it is also the default for Ceph erasure coded pools.`, technique: $localize`The more flexible technique is reed_sol_van : it is enough to set k and m. The cauchy_good technique can be faster but you need to chose the packetsize carefully. All of reed_sol_r6_op, liberation, blaum_roth, liber8tion are RAID6 equivalents in the sense that they can only be configured with m=2.`, packetSize: $localize`The encoding will be done on packets of bytes size at a time. Choosing the right packet size is difficult. The jerasure documentation contains extensive information on this topic.` }, lrc: { description: $localize`With the jerasure plugin, when an erasure coded object is stored on multiple OSDs, recovering from the loss of one OSD requires reading from all the others. For instance if jerasure is configured with k=8 and m=4, losing one OSD requires reading from the eleven others to repair. The lrc erasure code plugin creates local parity chunks to be able to recover using less OSDs. For instance if lrc is configured with k=8, m=4 and l=4, it will create an additional parity chunk for every four OSDs. When a single OSD is lost, it can be recovered with only four OSDs instead of eleven.`, l: $localize`Group the coding and data chunks into sets of size locality. For instance, for k=4 and m=2, when locality=3 two groups of three are created. Each set can be recovered without reading chunks from another set.`, crushLocality: $localize`The type of the crush bucket in which each set of chunks defined by l will be stored. For instance, if it is set to rack, each group of l chunks will be placed in a different rack. It is used to create a CRUSH rule step such as step choose rack. If it is not set, no such grouping is done.` }, isa: { description: $localize`The isa plugin encapsulates the ISA library. It only runs on Intel processors.`, technique: $localize`The ISA plugin comes in two Reed Solomon forms. If reed_sol_van is set, it is Vandermonde, if cauchy is set, it is Cauchy.` }, shec: { description: $localize`The shec plugin encapsulates the multiple SHEC library. It allows ceph to recover data more efficiently than Reed Solomon codes.`, c: $localize`The number of parity chunks each of which includes each data chunk in its calculation range. The number is used as a durability estimator. For instance, if c=2, 2 OSDs can be down without losing data.` }, clay: { description: $localize`CLAY (short for coupled-layer) codes are erasure codes designed to bring about significant savings in terms of network bandwidth and disk IO when a failed node/OSD/rack is being repaired.`, d: $localize`Number of OSDs requested to send data during recovery of a single chunk. d needs to be chosen such that k+1 <= d <= k+m-1. The larger the d, the better the savings.`, scalar_mds: $localize`scalar_mds specifies the plugin that is used as a building block in the layered construction. It can be one of jerasure, isa, shec.`, technique: $localize`technique specifies the technique that will be picked within the 'scalar_mds' plugin specified. Supported techniques are 'reed_sol_van', 'reed_sol_r6_op', 'cauchy_orig', 'cauchy_good', 'liber8tion' for jerasure, 'reed_sol_van', 'cauchy' for isa and 'single', 'multiple' for shec.` } }, crushRoot: $localize`The name of the crush bucket used for the first step of the CRUSH rule. For instance step take default.`, crushFailureDomain: $localize`Ensure that no two chunks are in a bucket with the same failure domain. For instance, if the failure domain is host no two chunks will be stored on the same host. It is used to create a CRUSH rule step such as step chooseleaf host.`, crushDeviceClass: $localize`Restrict placement to devices of a specific class (e.g., ssd or hdd), using the crush device class names in the CRUSH map.`, directory: $localize`Set the directory name from which the erasure code plugin is loaded.` }; constructor(private http: HttpClient) {} list(): Observable<ErasureCodeProfile[]> { return this.http.get<ErasureCodeProfile[]>(this.apiPath); } create(ecp: ErasureCodeProfile) { return this.http.post(this.apiPath, ecp, { observe: 'response' }); } delete(name: string) { return this.http.delete(`${this.apiPath}/${name}`, { observe: 'response' }); } getInfo() { return this.http.get(`ui-${this.apiPath}/info`); } }
5,663
50.027027
111
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/feedback.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { FeedbackService } from './feedback.service'; describe('FeedbackService', () => { let service: FeedbackService; let httpTesting: HttpTestingController; configureTestBed({ imports: [HttpClientTestingModule], providers: [FeedbackService] }); beforeEach(() => { service = TestBed.inject(FeedbackService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call checkAPIKey', () => { service.isKeyExist().subscribe(); const req = httpTesting.expectOne('ui-api/feedback/api_key/exist'); expect(req.request.method).toBe('GET'); }); it('should call createIssue to create issue tracker', () => { service.createIssue('dashboard', 'bug', 'test', 'test', '').subscribe(); const req = httpTesting.expectOne('api/feedback'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ api_key: '', description: 'test', project: 'dashboard', subject: 'test', tracker: 'bug' }); }); });
1,352
27.1875
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/feedback.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import * as _ from 'lodash'; @Injectable({ providedIn: 'root' }) export class FeedbackService { constructor(private http: HttpClient) {} baseUIURL = 'api/feedback'; isKeyExist() { return this.http.get('ui-api/feedback/api_key/exist'); } createIssue( project: string, tracker: string, subject: string, description: string, apiKey: string ) { return this.http.post( 'api/feedback', { project: project, tracker: tracker, subject: subject, description: description, api_key: apiKey }, { headers: { Accept: 'application/vnd.ceph.api.v0.1+json' } } ); } }
775
18.897436
65
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/health.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { HealthService } from './health.service'; describe('HealthService', () => { let service: HealthService; let httpTesting: HttpTestingController; configureTestBed({ providers: [HealthService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(HealthService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call getFullHealth', () => { service.getFullHealth().subscribe(); const req = httpTesting.expectOne('api/health/full'); expect(req.request.method).toBe('GET'); }); it('should call getMinimalHealth', () => { service.getMinimalHealth().subscribe(); const req = httpTesting.expectOne('api/health/minimal'); expect(req.request.method).toBe('GET'); }); });
1,119
26.317073
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/health.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class HealthService { constructor(private http: HttpClient) {} getFullHealth() { return this.http.get('api/health/full'); } getMinimalHealth() { return this.http.get('api/health/minimal'); } getClusterCapacity() { return this.http.get('api/health/get_cluster_capacity'); } getClusterFsid() { return this.http.get('api/health/get_cluster_fsid'); } getOrchestratorName() { return this.http.get('api/health/get_orchestrator_name'); } }
621
19.733333
61
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/host.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { HostService } from './host.service'; describe('HostService', () => { let service: HostService; let httpTesting: HttpTestingController; configureTestBed({ providers: [HostService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(HostService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call list', fakeAsync(() => { let result; service.list('true').subscribe((resp) => (result = resp)); const req = httpTesting.expectOne('api/host?facts=true'); expect(req.request.method).toBe('GET'); req.flush(['foo', 'bar']); tick(); expect(result).toEqual(['foo', 'bar']); })); it('should make a GET request on the devices endpoint when requesting devices', () => { const hostname = 'hostname'; service.getDevices(hostname).subscribe(); const req = httpTesting.expectOne(`api/host/${hostname}/devices`); expect(req.request.method).toBe('GET'); }); it('should update host', fakeAsync(() => { service.update('mon0', true, ['foo', 'bar'], true, false).subscribe(); const req = httpTesting.expectOne('api/host/mon0'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ force: false, labels: ['foo', 'bar'], maintenance: true, update_labels: true, drain: false }); })); it('should test host drain call', fakeAsync(() => { service.update('host0', false, null, false, false, true).subscribe(); const req = httpTesting.expectOne('api/host/host0'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ force: false, labels: null, maintenance: false, update_labels: false, drain: true }); })); it('should call getInventory', () => { service.getInventory('host-0').subscribe(); let req = httpTesting.expectOne('api/host/host-0/inventory'); expect(req.request.method).toBe('GET'); service.getInventory('host-0', true).subscribe(); req = httpTesting.expectOne('api/host/host-0/inventory?refresh=true'); expect(req.request.method).toBe('GET'); }); it('should call inventoryList', () => { service.inventoryList().subscribe(); let req = httpTesting.expectOne('ui-api/host/inventory'); expect(req.request.method).toBe('GET'); service.inventoryList(true).subscribe(); req = httpTesting.expectOne('ui-api/host/inventory?refresh=true'); expect(req.request.method).toBe('GET'); }); });
2,874
30.25
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/host.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import _ from 'lodash'; import { Observable, of as observableOf } from 'rxjs'; import { map, mergeMap, toArray } from 'rxjs/operators'; import { InventoryDevice } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-device.model'; import { InventoryHost } from '~/app/ceph/cluster/inventory/inventory-host.model'; import { ApiClient } from '~/app/shared/api/api-client'; import { CdHelperClass } from '~/app/shared/classes/cd-helper.class'; import { Daemon } from '../models/daemon.interface'; import { CdDevice } from '../models/devices'; import { SmartDataResponseV1 } from '../models/smart'; import { DeviceService } from '../services/device.service'; @Injectable({ providedIn: 'root' }) export class HostService extends ApiClient { baseURL = 'api/host'; baseUIURL = 'ui-api/host'; predefinedLabels = ['mon', 'mgr', 'osd', 'mds', 'rgw', 'nfs', 'iscsi', 'rbd', 'grafana']; constructor(private http: HttpClient, private deviceService: DeviceService) { super(); } list(facts: string): Observable<object[]> { return this.http.get<object[]>(this.baseURL, { headers: { Accept: this.getVersionHeaderValue(1, 2) }, params: { facts: facts } }); } create(hostname: string, addr: string, labels: string[], status: string) { return this.http.post( this.baseURL, { hostname: hostname, addr: addr, labels: labels, status: status }, { observe: 'response', headers: { Accept: CdHelperClass.cdVersionHeader('0', '1') } } ); } delete(hostname: string) { return this.http.delete(`${this.baseURL}/${hostname}`, { observe: 'response' }); } getDevices(hostname: string): Observable<CdDevice[]> { return this.http .get<CdDevice[]>(`${this.baseURL}/${hostname}/devices`) .pipe(map((devices) => devices.map((device) => this.deviceService.prepareDevice(device)))); } getSmartData(hostname: string) { return this.http.get<SmartDataResponseV1>(`${this.baseURL}/${hostname}/smart`); } getDaemons(hostname: string): Observable<Daemon[]> { return this.http.get<Daemon[]>(`${this.baseURL}/${hostname}/daemons`); } getLabels(): Observable<string[]> { return this.http.get<string[]>(`${this.baseUIURL}/labels`); } update( hostname: string, updateLabels = false, labels: string[] = [], maintenance = false, force = false, drain = false ) { return this.http.put( `${this.baseURL}/${hostname}`, { update_labels: updateLabels, labels: labels, maintenance: maintenance, force: force, drain: drain }, { headers: { Accept: this.getVersionHeaderValue(0, 1) } } ); } identifyDevice(hostname: string, device: string, duration: number) { return this.http.post(`${this.baseURL}/${hostname}/identify_device`, { device, duration }); } private getInventoryParams(refresh?: boolean): HttpParams { let params = new HttpParams(); if (refresh) { params = params.append('refresh', _.toString(refresh)); } return params; } /** * Get inventory of a host. * * @param hostname the host query. * @param refresh true to ask the Orchestrator to refresh inventory. */ getInventory(hostname: string, refresh?: boolean): Observable<InventoryHost> { const params = this.getInventoryParams(refresh); return this.http.get<InventoryHost>(`${this.baseURL}/${hostname}/inventory`, { params: params }); } /** * Get inventories of all hosts. * * @param refresh true to ask the Orchestrator to refresh inventory. */ inventoryList(refresh?: boolean): Observable<InventoryHost[]> { const params = this.getInventoryParams(refresh); return this.http.get<InventoryHost[]>(`${this.baseUIURL}/inventory`, { params: params }); } /** * Get device list via host inventories. * * @param hostname the host to query. undefined for all hosts. * @param refresh true to ask the Orchestrator to refresh inventory. */ inventoryDeviceList(hostname?: string, refresh?: boolean): Observable<InventoryDevice[]> { let observable; if (hostname) { observable = this.getInventory(hostname, refresh).pipe(toArray()); } else { observable = this.inventoryList(refresh); } return observable.pipe( mergeMap((hosts: InventoryHost[]) => { const devices = _.flatMap(hosts, (host) => { return host.devices.map((device) => { device.hostname = host.name; device.uid = device.device_id ? `${device.device_id}-${device.hostname}-${device.path}` : `${device.hostname}-${device.path}`; return device; }); }); return observableOf(devices); }) ); } }
4,889
30.548387
104
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/iscsi.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { IscsiService } from './iscsi.service'; describe('IscsiService', () => { let service: IscsiService; let httpTesting: HttpTestingController; configureTestBed({ providers: [IscsiService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(IscsiService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call listTargets', () => { service.listTargets().subscribe(); const req = httpTesting.expectOne('api/iscsi/target'); expect(req.request.method).toBe('GET'); }); it('should call getTarget', () => { service.getTarget('iqn.foo').subscribe(); const req = httpTesting.expectOne('api/iscsi/target/iqn.foo'); expect(req.request.method).toBe('GET'); }); it('should call status', () => { service.status().subscribe(); const req = httpTesting.expectOne('ui-api/iscsi/status'); expect(req.request.method).toBe('GET'); }); it('should call settings', () => { service.settings().subscribe(); const req = httpTesting.expectOne('ui-api/iscsi/settings'); expect(req.request.method).toBe('GET'); }); it('should call portals', () => { service.portals().subscribe(); const req = httpTesting.expectOne('ui-api/iscsi/portals'); expect(req.request.method).toBe('GET'); }); it('should call createTarget', () => { service.createTarget({ target_iqn: 'foo' }).subscribe(); const req = httpTesting.expectOne('api/iscsi/target'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ target_iqn: 'foo' }); }); it('should call updateTarget', () => { service.updateTarget('iqn.foo', { target_iqn: 'foo' }).subscribe(); const req = httpTesting.expectOne('api/iscsi/target/iqn.foo'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ target_iqn: 'foo' }); }); it('should call deleteTarget', () => { service.deleteTarget('target_iqn').subscribe(); const req = httpTesting.expectOne('api/iscsi/target/target_iqn'); expect(req.request.method).toBe('DELETE'); }); it('should call getDiscovery', () => { service.getDiscovery().subscribe(); const req = httpTesting.expectOne('api/iscsi/discoveryauth'); expect(req.request.method).toBe('GET'); }); it('should call updateDiscovery', () => { service .updateDiscovery({ user: 'foo', password: 'bar', mutual_user: 'mutual_foo', mutual_password: 'mutual_bar' }) .subscribe(); const req = httpTesting.expectOne('api/iscsi/discoveryauth'); expect(req.request.method).toBe('PUT'); }); });
2,993
29.55102
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/iscsi.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { cdEncode } from '../decorators/cd-encode'; @cdEncode @Injectable({ providedIn: 'root' }) export class IscsiService { constructor(private http: HttpClient) {} listTargets() { return this.http.get(`api/iscsi/target`); } getTarget(target_iqn: string) { return this.http.get(`api/iscsi/target/${target_iqn}`); } updateTarget(target_iqn: string, target: any) { return this.http.put(`api/iscsi/target/${target_iqn}`, target, { observe: 'response' }); } status() { return this.http.get(`ui-api/iscsi/status`); } settings() { return this.http.get(`ui-api/iscsi/settings`); } version() { return this.http.get(`ui-api/iscsi/version`); } portals() { return this.http.get(`ui-api/iscsi/portals`); } createTarget(target: any) { return this.http.post(`api/iscsi/target`, target, { observe: 'response' }); } deleteTarget(target_iqn: string) { return this.http.delete(`api/iscsi/target/${target_iqn}`, { observe: 'response' }); } getDiscovery() { return this.http.get(`api/iscsi/discoveryauth`); } updateDiscovery(auth: any) { return this.http.put(`api/iscsi/discoveryauth`, auth); } overview() { return this.http.get(`ui-api/iscsi/overview`); } }
1,350
21.147541
92
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/logging.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { LoggingService } from './logging.service'; describe('LoggingService', () => { let service: LoggingService; let httpTesting: HttpTestingController; configureTestBed({ providers: [LoggingService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(LoggingService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call jsError', () => { service.jsError('foo', 'bar', 'baz').subscribe(); const req = httpTesting.expectOne('ui-api/logging/js-error'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ url: 'foo', message: 'bar', stack: 'baz' }); }); });
1,046
25.175
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/logging.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class LoggingService { constructor(private http: HttpClient) {} jsError(url: string, message: string, stack: any) { const request = { url: url, message: message, stack: stack }; return this.http.post('ui-api/logging/js-error', request); } }
419
21.105263
62
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/logs.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { LogsService } from './logs.service'; describe('LogsService', () => { let service: LogsService; let httpTesting: HttpTestingController; configureTestBed({ providers: [LogsService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(LogsService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call getLogs', () => { service.getLogs().subscribe(); const req = httpTesting.expectOne('api/logs/all'); expect(req.request.method).toBe('GET'); }); });
891
24.485714
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/logs.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class LogsService { constructor(private http: HttpClient) {} getLogs() { return this.http.get('api/logs/all'); } validateDashboardUrl(uid: string) { return this.http.get(`api/grafana/validation/${uid}`); } }
369
19.555556
58
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/mgr-module.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MgrModuleService } from './mgr-module.service'; describe('MgrModuleService', () => { let service: MgrModuleService; let httpTesting: HttpTestingController; configureTestBed({ imports: [HttpClientTestingModule], providers: [MgrModuleService] }); beforeEach(() => { service = TestBed.inject(MgrModuleService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call list', () => { service.list().subscribe(); const req = httpTesting.expectOne('api/mgr/module'); expect(req.request.method).toBe('GET'); }); it('should call getConfig', () => { service.getConfig('foo').subscribe(); const req = httpTesting.expectOne('api/mgr/module/foo'); expect(req.request.method).toBe('GET'); }); it('should call updateConfig', () => { const config = { foo: 'bar' }; service.updateConfig('xyz', config).subscribe(); const req = httpTesting.expectOne('api/mgr/module/xyz'); expect(req.request.method).toBe('PUT'); expect(req.request.body.config).toEqual(config); }); it('should call enable', () => { service.enable('foo').subscribe(); const req = httpTesting.expectOne('api/mgr/module/foo/enable'); expect(req.request.method).toBe('POST'); }); it('should call disable', () => { service.disable('bar').subscribe(); const req = httpTesting.expectOne('api/mgr/module/bar/disable'); expect(req.request.method).toBe('POST'); }); it('should call getOptions', () => { service.getOptions('foo').subscribe(); const req = httpTesting.expectOne('api/mgr/module/foo/options'); expect(req.request.method).toBe('GET'); }); });
1,997
28.820896
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/mgr-module.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class MgrModuleService { private url = 'api/mgr/module'; constructor(private http: HttpClient) {} /** * Get the list of Ceph Mgr modules and their state (enabled/disabled). * @return {Observable<Object[]>} */ list(): Observable<Object[]> { return this.http.get<Object[]>(`${this.url}`); } /** * Get the Ceph Mgr module configuration. * @param {string} module The name of the mgr module. * @return {Observable<Object>} */ getConfig(module: string): Observable<Object> { return this.http.get(`${this.url}/${module}`); } /** * Update the Ceph Mgr module configuration. * @param {string} module The name of the mgr module. * @param {object} config The configuration. * @return {Observable<Object>} */ updateConfig(module: string, config: object): Observable<Object> { return this.http.put(`${this.url}/${module}`, { config: config }); } /** * Enable the Ceph Mgr module. * @param {string} module The name of the mgr module. */ enable(module: string) { return this.http.post(`${this.url}/${module}/enable`, null); } /** * Disable the Ceph Mgr module. * @param {string} module The name of the mgr module. */ disable(module: string) { return this.http.post(`${this.url}/${module}/disable`, null); } /** * Get the Ceph Mgr module options. * @param {string} module The name of the mgr module. * @return {Observable<Object>} */ getOptions(module: string): Observable<Object> { return this.http.get(`${this.url}/${module}/options`); } }
1,740
25.378788
73
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/monitor.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MonitorService } from './monitor.service'; describe('MonitorService', () => { let service: MonitorService; let httpTesting: HttpTestingController; configureTestBed({ providers: [MonitorService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(MonitorService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call getMonitor', () => { service.getMonitor().subscribe(); const req = httpTesting.expectOne('api/monitor'); expect(req.request.method).toBe('GET'); }); });
914
25.142857
94
ts