UNPKG

angular-firebase-authorizator

Version:

Beta version of authorizator for angular linked to firebase, it creates a model in firestore to assign permissions to users an roles, and creates a view to update this permissions

1,371 lines 74 kB
import { __decorate, __metadata, __param, __extends } from 'tslib';
import { ɵɵdefineInjectable, Injectable, InjectionToken, ChangeDetectorRef, Inject, Input, Component, EventEmitter, Output, ViewChild, NgModule } from '@angular/core';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { auth, firestore } from 'firebase';
import { Router } from '@angular/router';
import { take, map, catchError } from 'rxjs/operators';
import { MAT_DIALOG_DATA, MatDialogRef, MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatSnackBarConfig, MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatSelect, MatSelectModule } from '@angular/material/select';
import { MatIconModule } from '@angular/material/icon';
import { MatTabsModule } from '@angular/material/tabs';
import { MatTableModule } from '@angular/material/table';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { CommonModule } from '@angular/common';
import { DataSource } from '@angular/cdk/table';
import { FormGroup, FormControl, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';

var Operation;
(function (Operation) {
    Operation[Operation["Create"] = 0] = "Create";
    Operation[Operation["Read"] = 1] = "Read";
    Operation[Operation["Update"] = 2] = "Update";
    Operation[Operation["Delete"] = 3] = "Delete";
    Operation[Operation["Deny"] = 4] = "Deny";
})(Operation || (Operation = {}));

var ProgressbarService = /** @class */ (function () {
    function ProgressbarService() {
        this.usersWaitBar = new BehaviorSubject(null);
        this.rolesWaitBar = new BehaviorSubject(null);
    }
    ProgressbarService.prototype.showUsersWaitBar = function (show) {
        this.usersWaitBar.next(show);
    };
    ProgressbarService.prototype.showRolesWaitBar = function (show) {
        this.rolesWaitBar.next(show);
    };
    ProgressbarService.ɵprov = ɵɵdefineInjectable({ factory: function ProgressbarService_Factory() { return new ProgressbarService(); }, token: ProgressbarService, providedIn: "root" });
    ProgressbarService = __decorate([
        Injectable({
            providedIn: 'root'
        }),
        __metadata("design:paramtypes", [])
    ], ProgressbarService);
    return ProgressbarService;
}());

var AUTHORIZATOR_CONFIG = new InjectionToken('AUTHORIZATOR_CONFIG');

var AuthGuard = /** @class */ (function () {
    function AuthGuard(router, authorizatorservice) {
        this.router = router;
        this.authorizatorservice = authorizatorservice;
    }
    AuthGuard.prototype.isAuthorized = function (rootFirebasePath, resource) {
        var _this = this;
        return new Observable(function (observer) {
            auth().onAuthStateChanged(function (user) {
                if (user) {
                    if (resource) {
                        Promise.all([
                            _this.authorizatorservice.getUser(rootFirebasePath, user.email),
                            _this.authorizatorservice.getRolesByUser(rootFirebasePath, user.email)
                        ]).then(function (values) {
                            var userDB = values[0];
                            var rolesDB = values[1] || [];
                            var resourcePermissionsByUser = [];
                            var resourcePermissionsByRoles = [];
                            if (userDB && userDB.data.permissions) {
                                userDB.data.permissions.filter(function (permission) { return permission.resource === resource || permission.resource === 'owner'; }).forEach(function (permission) {
                                    resourcePermissionsByUser.push(permission);
                                });
                            }
                            rolesDB.forEach(function (rolDB) {
                                if (rolDB.data.permissions) {
                                    rolDB.data.permissions.filter(function (permission) { return permission.resource === resource; }).forEach(function (permission) {
                                        resourcePermissionsByRoles.push(permission);
                                    });
                                }
                            });
                            if (resourcePermissionsByUser && resourcePermissionsByUser.length > 0 &&
                                resourcePermissionsByUser.findIndex(function (permission) { return permission.operations && permission.operations.findIndex(function (operation) { return operation === Operation.Deny; }) > -1; }) === -1) {
                                observer.next('authorized');
                            }
                            else {
                                if (resourcePermissionsByRoles && resourcePermissionsByRoles.length > 0 &&
                                    resourcePermissionsByRoles.findIndex(function (permission) { return permission.operations.findIndex(function (operation) { return operation === Operation.Deny; }) > -1; }) === -1) {
                                    observer.next('authorized');
                                }
                                else {
                                    console.error('Unauthorized resource');
                                    observer.next('unauthorized');
                                }
                            }
                        }).catch(function (error) {
                            console.error('Error getting permissions from database');
                            console.error(error);
                            observer.next('unauthorized');
                        });
                    }
                    else {
                        console.error('Resource not received');
                        observer.next('unauthorized');
                    }
                }
                else {
                    console.error('Unauthenticated user');
                    observer.next('unauthenticated');
                }
            }, function (err) {
                observer.error(err);
            }, function () {
                observer.complete();
            });
        });
    };
    AuthGuard.prototype.canActivate = function (route, state) {
        var _this = this;
        var rootFirebasePath = route.data.rootFirebasePath;
        var resource = route.data.resource;
        var anonymousRoute = route.data.anonymousRoute || '/';
        var unauthorizedRoute = route.data.unauthorizedRoute || '/';
        var findVariable = rootFirebasePath.indexOf(':');
        if (findVariable > -1) {
            var variableEnd = rootFirebasePath.indexOf('/', findVariable);
            var variableFound_1;
            if (variableEnd > -1) {
                variableFound_1 = rootFirebasePath.substring(findVariable + 1, variableEnd);
            }
            else {
                variableFound_1 = rootFirebasePath.substring(findVariable + 1);
            }
            var existsVariable = Object.keys(route.params).findIndex(function (key) { return key === variableFound_1; });
            if (existsVariable > -1) {
                rootFirebasePath = rootFirebasePath.replace(':' + variableFound_1, route.params[variableFound_1]);
            }
        }
        return this.isAuthorized(rootFirebasePath, resource).pipe(take(1), map(function (isAuth) {
            if (isAuth === 'unauthenticated') {
                _this.router.navigate([anonymousRoute], { queryParams: { returnUrl: state.url } });
                return false;
            }
            if (isAuth === 'unauthorized') {
                _this.router.navigate([unauthorizedRoute], { queryParams: { returnUrl: state.url } });
                return false;
            }
            if (isAuth === 'authorized') {
                return true;
            }
            return false;
        }), catchError(function (err) {
            console.error('Error getting authenticated user');
            console.error(err);
            // not resource sended so redirect to unauthorized page with the return url
            _this.router.navigate([anonymousRoute], { queryParams: { returnUrl: state.url } });
            return of(false);
        }));
    };
    AuthGuard.ctorParameters = function () { return [
        { type: Router },
        { type: AuthorizatorService }
    ]; };
    AuthGuard = __decorate([
        Injectable(),
        __metadata("design:paramtypes", [Router, AuthorizatorService])
    ], AuthGuard);
    return AuthGuard;
}());
var AuthorizatorService = /** @class */ (function () {
    function AuthorizatorService() {
    }
    //#region Users
    AuthorizatorService.prototype.addUser = function (rootFirebasePath, user) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            rootFirebasePath = rootFirebasePath || '';
            var path = (rootFirebasePath + '/users').replace('//', '/');
            firestore$1.collection(path).doc(user.id).get().then(function (userDB) {
                if (userDB.exists) {
                    reject({ key: 'exists', message: 'User already exists' });
                }
                else {
                    firestore$1.collection(path).doc(user.id).set(user.data).then(function () {
                        resolve();
                    }).catch(function (error) {
                        console.error(error);
                        reject({ key: 'defaulterror', message: 'Error adding user' });
                    });
                }
            });
        });
    };
    AuthorizatorService.prototype.removeUser = function (rootFirebasePath, userId) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            rootFirebasePath = rootFirebasePath || '';
            var path = (rootFirebasePath + '/users').replace('//', '/');
            firestore$1.collection(path).doc(userId).delete().then(function () {
                resolve();
            }).catch(function (error) {
                console.error(error);
                reject({ key: 'defaulterror', message: 'Error removing user' });
            });
        });
    };
    AuthorizatorService.prototype.getUser = function (rootFirebasePath, userId) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            var path = (rootFirebasePath + '/users').replace('//', '/');
            firestore$1.collection(path).doc(userId).get().then(function (userDB) {
                resolve({
                    id: userDB.id,
                    data: userDB.data()
                });
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService.prototype.getUsers = function (rootFirebasePath) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            if (!rootFirebasePath) {
                rootFirebasePath = '';
            }
            var path = (rootFirebasePath + '/users').replace('//', '/');
            firestore$1.collection(path).get().then(function (usersDB) {
                if (usersDB.empty) {
                    resolve(null);
                }
                else {
                    resolve(usersDB.docs.map(function (userDB) {
                        return {
                            id: userDB.id,
                            data: userDB.data()
                        };
                    }));
                }
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService.prototype.updateUserPermissions = function (rootFirebasePath, user) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            rootFirebasePath = rootFirebasePath || '';
            var path = (rootFirebasePath + '/users').replace('//', '/');
            firestore$1.collection(path).doc(user.id).get().then(function (userDB) {
                if (!userDB.exists) {
                    reject({ key: 'notexists', message: 'User not exists' });
                }
                else {
                    firestore$1.collection(path).doc(user.id).update({ permissions: user.data.permissions }).then(function () {
                        resolve();
                    }).catch(function (error) {
                        console.error(error);
                        reject({ key: 'defaulterror', message: 'Error updating permissions' });
                    });
                }
            });
        });
    };
    //#endregion
    //#region Resources
    AuthorizatorService.prototype.addResource = function (rootFirebasePath, resource) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            var path = (rootFirebasePath + '/resources').replace('//', '/');
            firestore$1.collection(path).add(resource.data).then(function (resourceCreated) {
                resolve(resourceCreated.id);
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService.prototype.removeResource = function (rootFirebasePath, resourceId) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            var resourcePath = (rootFirebasePath + '/resources').replace('//', '/');
            var usersPath = (rootFirebasePath + '/users').replace('//', '/');
            var rolesPath = (rootFirebasePath + '/roles').replace('//', '/');
            var resourceRef = firestore$1.collection(resourcePath).doc(resourceId);
            Promise.all([
                _this.getUsersByResource(rootFirebasePath, resourceId),
                _this.getRolesByResource(rootFirebasePath, resourceId)
            ]).then(function (values) {
                var batch = firestore$1.batch();
                var usersToUpdate = values[0];
                var rolesToUpdate = values[1];
                usersToUpdate.forEach(function (userToUpdate) {
                    userToUpdate.data.permissions.splice(userToUpdate.data.permissions.findIndex(function (permission) { return permission.resource === resourceId; }), 1);
                    var userRef = firestore$1.collection(usersPath).doc(userToUpdate.id);
                    batch.update(userRef, { data: userToUpdate.data });
                });
                rolesToUpdate.forEach(function (roleToUpdate) {
                    roleToUpdate.data.permissions.splice(roleToUpdate.data.permissions.findIndex(function (permission) { return permission.resource === resourceId; }), 1);
                    var roleRef = firestore$1.collection(rolesPath).doc(roleToUpdate.id);
                    batch.update(roleRef, { data: roleToUpdate.data });
                });
                batch.delete(resourceRef);
                batch.commit().then(function () {
                    resolve();
                }).catch(function (error) {
                    reject(error);
                });
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService.prototype.updateResource = function (rootFirebasePath, resource) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            var path = (rootFirebasePath + '/resources').replace('//', '/');
            firestore$1.collection(path).doc(resource.id).set(resource.data).then(function () {
                resolve();
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService.prototype.getResource = function (rootFirebasePath, resourceId) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            var path = (rootFirebasePath + '/resources').replace('//', '/');
            firestore$1.collection(path).doc(resourceId).get().then(function (resourceDB) {
                resolve({
                    id: resourceDB.id,
                    data: resourceDB.data()
                });
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService.prototype.getResources = function (rootFirebasePath) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            var path = (rootFirebasePath + '/resources').replace('//', '/');
            firestore$1.collection(path).get().then(function (resourcesDB) {
                if (resourcesDB.empty) {
                    resolve(null);
                }
                else {
                    resolve(resourcesDB.docs.map(function (resourceDB) {
                        return {
                            id: resourceDB.id,
                            data: resourceDB.data()
                        };
                    }));
                }
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    // endregion
    //#region Roles
    AuthorizatorService.prototype.addRole = function (rootFirebasePath, role) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            rootFirebasePath = rootFirebasePath || '';
            var path = (rootFirebasePath + '/roles').replace('//', '/');
            firestore$1.collection(path).where('name', '==', role.data.name).get().then(function (roleDB) {
                if (!roleDB.empty) {
                    reject({ key: 'exists', message: 'Role already exists' });
                }
                else {
                    firestore$1.collection(path).add(role.data).then(function () {
                        resolve();
                    }).catch(function (error) {
                        console.error(error);
                        reject({ key: 'defaulterror', message: 'Error adding role' });
                    });
                }
            });
        });
    };
    AuthorizatorService.prototype.removeRole = function (rootFirebasePath, roleId) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            rootFirebasePath = rootFirebasePath || '';
            var path = (rootFirebasePath + '/roles').replace('//', '/');
            firestore$1.collection(path).doc(roleId).delete().then(function () {
                resolve();
            }).catch(function (error) {
                console.error(error);
                reject({ key: 'defaulterror', message: 'Error removing role' });
            });
        });
    };
    AuthorizatorService.prototype.updateRole = function (rootFirebasePath, role) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            rootFirebasePath = rootFirebasePath || '';
            var path = (rootFirebasePath + '/roles').replace('//', '/');
            firestore$1.collection(path).doc(role.id).set(role.data).then(function () {
                resolve();
            }).catch(function (error) {
                console.error(error);
                reject({ key: 'defaulterror', message: 'Error updating role' });
            });
        });
    };
    AuthorizatorService.prototype.getRole = function (rootFirebasePath, roleId) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            var path = (rootFirebasePath + '/roles').replace('//', '/');
            firestore$1.collection(path).doc(roleId).get().then(function (roleDB) {
                resolve({
                    id: roleDB.id,
                    data: roleDB.data()
                });
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService.prototype.getRoles = function (rootFirebasePath) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            if (!rootFirebasePath) {
                rootFirebasePath = '';
            }
            var path = (rootFirebasePath + '/roles').replace('//', '/');
            firestore$1.collection(path).get().then(function (rolesDB) {
                if (rolesDB.empty) {
                    resolve(null);
                }
                else {
                    resolve(rolesDB.docs.map(function (roleDB) {
                        return {
                            id: roleDB.id,
                            data: roleDB.data()
                        };
                    }));
                }
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService.prototype.getRolesByResource = function (rootFirebasePath, resourceId) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            var path = (rootFirebasePath + '/roles').replace('//', '/');
            firestore$1.collection(path).where('data.resources', 'array-contains', resourceId).get().then(function (rolesDB) {
                if (rolesDB.empty) {
                    resolve(null);
                }
                else {
                    resolve(rolesDB.docs.map(function (roleDB) {
                        return {
                            id: roleDB.id,
                            data: roleDB.data()
                        };
                    }));
                }
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService.prototype.getRolesByUser = function (rootFirebasePath, userId) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            var path = (rootFirebasePath + '/roles').replace('//', '/');
            firestore$1.collection(path).where('users', 'array-contains', userId).get().then(function (rolesDB) {
                if (rolesDB.empty) {
                    resolve(null);
                }
                else {
                    resolve(rolesDB.docs.map(function (roleDB) {
                        return {
                            id: roleDB.id,
                            data: roleDB.data()
                        };
                    }));
                }
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService.prototype.updateRolePermissions = function (rootFirebasePath, role) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            rootFirebasePath = rootFirebasePath || '';
            var path = (rootFirebasePath + '/roles').replace('//', '/');
            firestore$1.collection(path).doc(role.id).get().then(function (roleDB) {
                if (!roleDB.exists) {
                    reject({ key: 'notexists', message: 'Role not exists' });
                }
                else {
                    firestore$1.collection(path).doc(role.id).update({ permissions: role.data.permissions }).then(function () {
                        resolve();
                    }).catch(function (error) {
                        console.error(error);
                        reject({ key: 'defaulterror', message: 'Error updating permissions' });
                    });
                }
            });
        });
    };
    // endregion
    //#region Roles
    AuthorizatorService.prototype.removeUserFromRole = function (rootFirebasePath, userId) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            var usersPath = (rootFirebasePath + '/users').replace('//', '/');
            var rolesPath = (rootFirebasePath + '/roles').replace('//', '/');
            _this.getRolesByUser(rootFirebasePath, userId).then(function (rolesDB) {
                var batch = firestore$1.batch();
                var rolesToUpdate = rolesDB;
                rolesToUpdate.forEach(function (roleToUpdate) {
                    roleToUpdate.data.users.splice(roleToUpdate.data.users.findIndex(function (user) { return user === userId; }), 1);
                    var roleRef = firestore$1.collection(rolesPath).doc(roleToUpdate.id);
                    batch.update(roleRef, { data: roleToUpdate.data });
                });
                var userRef = firestore$1.collection(usersPath).doc(userId);
                batch.delete(userRef);
                batch.commit().then(function () {
                    resolve();
                }).catch(function (error) {
                    reject(error);
                });
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService.prototype.getUsersByResource = function (rootFirebasePath, resourceId) {
        return new Promise(function (resolve, reject) {
            var firestore$1 = firestore();
            var path = (rootFirebasePath + '/users').replace('//', '/');
            firestore$1.collection(path).where('data.resources', 'array-contains', resourceId).get().then(function (usersDB) {
                if (usersDB.empty) {
                    resolve(null);
                }
                else {
                    resolve(usersDB.docs.map(function (userDB) {
                        return {
                            id: userDB.id,
                            data: userDB.data()
                        };
                    }));
                }
            }).catch(function (error) {
                reject(error);
            });
        });
    };
    AuthorizatorService = __decorate([
        Injectable(),
        __metadata("design:paramtypes", [])
    ], AuthorizatorService);
    return AuthorizatorService;
}());

var AngularFirebaseAuthotizatorComponent = /** @class */ (function () {
    function AngularFirebaseAuthotizatorComponent(progressbarservice, cd, authorizatorConfig, authroizatorservice) {
        this.progressbarservice = progressbarservice;
        this.cd = cd;
        this.authorizatorConfig = authorizatorConfig;
        this.authroizatorservice = authroizatorservice;
        this.isUsersWaitBarShowing = false;
        this.isRolesWaitBarShowing = false;
    }
    AngularFirebaseAuthotizatorComponent.prototype.ngOnInit = function () {
        var _this = this;
        this.progressbarservice.usersWaitBar.subscribe(function (isShowing) {
            _this.isUsersWaitBarShowing = isShowing;
            _this.cd.detectChanges();
        });
        this.progressbarservice.rolesWaitBar.subscribe(function (isShowing) {
            _this.isRolesWaitBarShowing = isShowing;
            _this.cd.detectChanges();
        });
    };
    AngularFirebaseAuthotizatorComponent.ctorParameters = function () { return [
        { type: ProgressbarService },
        { type: ChangeDetectorRef },
        { type: undefined, decorators: [{ type: Inject, args: [AUTHORIZATOR_CONFIG,] }] },
        { type: AuthorizatorService }
    ]; };
    __decorate([
        Input(),
        __metadata("design:type", String)
    ], AngularFirebaseAuthotizatorComponent.prototype, "rootFirebasePath", void 0);
    AngularFirebaseAuthotizatorComponent = __decorate([
        Component({
            selector: 'angular-firebase-authotizator',
            template: "<mat-tab-group>\n  <mat-tab label=\"Users\">\n    <mat-progress-bar color=\"accent\" mode=\"indeterminate\" *ngIf=\"isUsersWaitBarShowing\"></mat-progress-bar>\n    <lib-users [rootFirebasePath]=\"rootFirebasePath\"></lib-users>\n  </mat-tab>\n  <mat-tab label=\"Roles\">\n    <mat-progress-bar mode=\"indeterminate\" *ngIf=\"isRolesWaitBarShowing\"></mat-progress-bar>\n    <lib-roles [rootFirebasePath]=\"rootFirebasePath\"></lib-roles>\n  </mat-tab>\n</mat-tab-group>",
            styles: ["table{width:100%}::ng-deep .success-bar{background-color:#c8e6c9!important;color:#1b5e20!important}::ng-deep .error-bar{background-color:#ffcdd2!important;color:#b71c1c!important}"]
        }),
        __param(2, Inject(AUTHORIZATOR_CONFIG)),
        __metadata("design:paramtypes", [ProgressbarService, ChangeDetectorRef, Object, AuthorizatorService])
    ], AngularFirebaseAuthotizatorComponent);
    return AngularFirebaseAuthotizatorComponent;
}());

var PermissionManagerComponent = /** @class */ (function () {
    function PermissionManagerComponent(authorizatorConfig, cd, data, authorizatorservice, snackbar) {
        this.authorizatorConfig = authorizatorConfig;
        this.cd = cd;
        this.data = data;
        this.authorizatorservice = authorizatorservice;
        this.snackbar = snackbar;
        this.AllowedOperation = Operation;
        this.resourceCols = 5;
        this.permissionCols = 5;
        this.change = new EventEmitter();
        this.user = data.user;
        this.role = data.role;
    }
    PermissionManagerComponent.prototype.ngOnInit = function () {
        var _this = this;
        if (this.authorizatorConfig && this.authorizatorConfig.permissions) {
            this.permissionsConfig = this.authorizatorConfig.permissions.map(function (permission) {
                return {
                    resource: permission.resource,
                    operations: permission.allowedOperations.map(function (operation) {
                        return {
                            id: operation,
                            value: _this.user ?
                                (_this.user.data.permissions ?
                                    (_this.user.data.permissions.find(function (perm) { return perm.resource === permission.resource.id; }) ?
                                        (_this.user.data.permissions.find(function (perm) { return perm.resource === permission.resource.id; }).operations.findIndex(function (oper) { return oper === operation; }) > -1) : false) : false) :
                                _this.role ?
                                    (_this.role.data.permissions ?
                                        (_this.role.data.permissions.find(function (perm) { return perm.resource === permission.resource.id; }) ?
                                            (_this.role.data.permissions.find(function (perm) { return perm.resource === permission.resource.id; }).operations.findIndex(function (oper) { return oper === operation; }) > -1) : false) : false) : false
                        };
                    })
                };
            });
        }
        else {
            console.error("Configuration of module missing, please add the next code in the Module declaration:\n      AngularFirebaseAuthorizatorModule.forRoot({\n        permissions: [\n          {\n            resource: {\n              id: 'someid',\n              data: {\n                description: 'Resource description'\n              }\n            },\n            allowedOperations: [\n              Operation.Create,\n              Operation.Read,\n              Operation.Update,\n              Operation.Delete,\n              Operation.Deny\n            ]\n          }\n        ]\n      })");
        }
    };
    PermissionManagerComponent.prototype.ngAfterViewInit = function () {
        if (this.permissionsConfig) {
            var permissionManagerWidth = document.getElementById('permission_manager_container').offsetWidth;
            if (permissionManagerWidth <= 400) {
                this.resourceCols = 5;
                this.permissionCols = 5;
            }
            else if (permissionManagerWidth > 400 && permissionManagerWidth <= 600) {
                this.resourceCols = 6;
                this.permissionCols = 4;
            }
            else if (permissionManagerWidth > 600 && permissionManagerWidth <= 800) {
                this.resourceCols = 7;
                this.permissionCols = 3;
            }
            else {
                this.resourceCols = 8;
                this.permissionCols = 2;
            }
        }
        this.cd.detectChanges();
    };
    PermissionManagerComponent.prototype.onPermissionChange = function (resource, operation, event) {
        var _this = this;
        var updatePermissionsMonitor = new BehaviorSubject(null);
        var permissions = this.user ? this.user.data.permissions || [] :
            this.role ? this.role.data.permissions || [] : [];
        var permissionIndex = permissions.findIndex(function (permission) { return permission.resource === resource.id; });
        if (event.checked) {
            if (permissionIndex > -1) {
                var operationIndex = permissions[permissionIndex].operations.findIndex(function (oper) { return oper === operation; });
                if (operationIndex === -1) {
                    permissions[permissionIndex].operations.push(operation);
                    updatePermissionsMonitor.next(permissions);
                }
            }
            else {
                permissions.push({
                    resource: resource.id,
                    operations: [operation]
                });
                updatePermissionsMonitor.next(permissions);
            }
        }
        else {
            if (permissionIndex > -1) {
                var operationIndex = permissions[permissionIndex].operations.findIndex(function (oper) { return oper === operation; });
                if (operationIndex > -1) {
                    if (permissions[permissionIndex].operations.length > 1) {
                        permissions[permissionIndex].operations.splice(operationIndex, 1);
                    }
                    else {
                        permissions.splice(permissionIndex, 1);
                    }
                    updatePermissionsMonitor.next(permissions);
                }
            }
        }
        updatePermissionsMonitor.subscribe(function (permissionsToUpdate) {
            if (permissionsToUpdate) {
                if (_this.user) {
                    var userToUpdate = _this.data.user;
                    userToUpdate.data.permissions = permissionsToUpdate;
                    var config_1 = new MatSnackBarConfig();
                    config_1.duration = 2000;
                    _this.authorizatorservice.updateUserPermissions(_this.data.rootFirebasePath, userToUpdate).then(function () {
                        config_1.panelClass = ['success-bar'];
                        _this.snackbar.open('Permissions updated', null, config_1);
                    }).catch(function (error) {
                        config_1.panelClass = ['error-bar'];
                        _this.snackbar.open(error.message, null, config_1);
                    });
                }
                if (_this.role) {
                    var roleToUpdate = _this.data.role;
                    roleToUpdate.data.permissions = permissionsToUpdate;
                    var config_2 = new MatSnackBarConfig();
                    config_2.duration = 2000;
                    _this.authorizatorservice.updateRolePermissions(_this.data.rootFirebasePath, roleToUpdate).then(function () {
                        config_2.panelClass = ['success-bar'];
                        _this.snackbar.open('Permissions updated', null, config_2);
                    }).catch(function (error) {
                        console.log('ban5');
                        console.log(error);
                        config_2.panelClass = ['error-bar'];
                        _this.snackbar.open(error.message, null, config_2);
                    });
                }
                updatePermissionsMonitor.unsubscribe();
            }
        });
    };
    PermissionManagerComponent.ctorParameters = function () { return [
        { type: undefined, decorators: [{ type: Inject, args: [AUTHORIZATOR_CONFIG,] }] },
        { type: ChangeDetectorRef },
        { type: undefined, decorators: [{ type: Inject, args: [MAT_DIALOG_DATA,] }] },
        { type: AuthorizatorService },
        { type: MatSnackBar }
    ]; };
    __decorate([
        Output(),
        __metadata("design:type", EventEmitter)
    ], PermissionManagerComponent.prototype, "change", void 0);
    PermissionManagerComponent = __decorate([
        Component({
            selector: 'lib-permission-manager',
            template: "<h1 mat-dialog-title>User Permissions</h1>\n<div mat-dialog-content>\n  <div *ngIf=\"permissionsConfig\" id=\"permission_manager_container\">\n    <div>\n      <mat-grid-list cols=\"10\" rowHeight=\"48px\" style=\"width: 100%;\">\n        <mat-grid-tile [colspan]=\"resourceCols\">\n            Resource\n        </mat-grid-tile>\n        <mat-grid-tile [colspan]=\"permissionCols\">\n            Permissions\n        </mat-grid-tile>\n      </mat-grid-list>\n    </div>\n    <div *ngFor=\"let permission of permissionsConfig\">\n      <mat-grid-list cols=\"10\" rowHeight=\"48px\" style=\"width: 100%;\">\n        <mat-grid-tile [rowspan]=\"permission.operations.length\" class=\"permission-grid\" [colspan]=\"resourceCols\">\n            {{permission.resource.data.description}}\n        </mat-grid-tile>\n        <mat-grid-tile *ngFor=\"let operation of permission.operations\" class=\"permission-grid\" [colspan]=\"permissionCols\">\n          <mat-slide-toggle [checked]=\"operation.value\"\n          (change)=\"onPermissionChange(permission.resource, operation.id, $event)\">\n            {{\n              operation.id === AllowedOperation.Create ? 'Create' :\n              operation.id === AllowedOperation.Read ? 'Read':\n              operation.id === AllowedOperation.Update ? 'Update':\n              operation.id === AllowedOperation.Delete ? 'Delete':\n              operation.id === AllowedOperation.Deny ? 'Deny' : ''\n            }}\n          </mat-slide-toggle>\n        </mat-grid-tile>\n      </mat-grid-list>\n    </div>\n  </div>      \n</div>\n<div mat-dialog-actions>\n  <button mat-button cdkFocusInitial [mat-dialog-close]>Close</button>\n</div>\n\n",
            styles: [".permission-grid{background:#f5f5f5;border:1px solid #d3d3d3}.mat-dialog-actions{-webkit-box-pack:end;justify-content:flex-end}div#permission_manager_container{margin-bottom:5px!important}"]
        }),
        __param(0, Inject(AUTHORIZATOR_CONFIG)),
        __param(2, Inject(MAT_DIALOG_DATA)),
        __metadata("design:paramtypes", [Object, ChangeDetectorRef, Object, AuthorizatorService,
            MatSnackBar])
    ], PermissionManagerComponent);
    return PermissionManagerComponent;
}());

var UpsertUserComponent = /** @class */ (function () {
    function UpsertUserComponent(data, authorizatorservice, dialogRef) {
        this.data = data;
        this.authorizatorservice = authorizatorservice;
        this.dialogRef = dialogRef;
        this.userForm = new FormGroup({
            email: new FormControl(null, [Validators.required, Validators.email])
        });
    }
    UpsertUserComponent.prototype.onSubmitUser = function () {
        var _this = this;
        if (this.userForm.valid) {
            var userToAdd_1 = {
                id: this.userForm.controls.email.value,
                data: {
                    name: null,
                    email: this.userForm.controls.email.value,
                    picture: null,
                    permissions: null
                }
            };
            this.authorizatorservice.addUser(this.data.rootFirebasePath, userToAdd_1).then(function () {
                _this.dialogRef.close(userToAdd_1);
            }).catch(function (error) {
                if (error.key === 'exists') {
                    _this.userForm.controls.email.setErrors({ exists: true });
                }
                else {
                    _this.userForm.controls.email.setErrors({ defaulterror: true });
                }
            });
        }
    };
    UpsertUserComponent.ctorParameters = function () { return [
        { type: undefined, decorators: [{ type: Inject, args: [MAT_DIALOG_DATA,] }] },
        { type: AuthorizatorService },
        { type: MatDialogRef }
    ]; };
    UpsertUserComponent = __decorate([
        Component({
            selector: 'lib-upsert-user',
            template: "<form [formGroup]=\"userForm\" (ngSubmit)=\"onSubmitUser()\" method=\"post\">\n  <h1 mat-dialog-title>{{data.type === 'add' ? 'Add User' : 'Edit User'}}</h1>\n  <div mat-dialog-content>\n    <mat-form-field style=\"width: 100%;\">\n        <input matInput cdkFocusInitial type=\"email\" placeholder=\"Email\" formControlName=\"email\" maxlength=\"254\">\n        <mat-error *ngIf=\"userForm.controls['email'].hasError('required')\">Mandatory field</mat-error>\n        <mat-error *ngIf=\"userForm.controls['email'].hasError('email')\">Email format incorrect</mat-error>\n        <mat-error *ngIf=\"userForm.controls['email'].hasError('exists')\">Email already exists</mat-error>\n        <mat-error *ngIf=\"userForm.controls['email'].hasError('defaulterror')\">Error updating user</mat-error>\n    </mat-form-field>\n  </div>\n  <div mat-dialog-actions>\n    <button mat-button [mat-dialog-close]>Close</button>\n    <button mat-raised-button type=\"submit\" [disabled]=\"!userForm.valid\">Add</button>\n  </div>\n</form>\n",
            styles: [".mat-dialog-actions{-webkit-box-pack:end;justify-content:flex-end}"]
        }),
        __param(0, Inject(MAT_DIALOG_DATA)),
        __metadata("design:paramtypes", [Object, AuthorizatorService,
            MatDialogRef])
    ], UpsertUserComponent);
    return UpsertUserComponent;
}());

var DeleteUserWarningComponent = /** @class */ (function () {
    function DeleteUserWarningComponent(data) {
        this.data = data;
    }
    DeleteUserWarningComponent.prototype.ngOnInit = function () {
    };
    DeleteUserWarningComponent.ctorParameters = function () { return [
        { type: undefined, decorators: [{ type: Inject, args: [MAT_DIALOG_DATA,] }] }
    ]; };
    DeleteUserWarningComponent = __decorate([
        Component({
            selector: 'lib-delete-user-warning',
            template: "<h1 mat-dialog-title>Remove User</h1>\n<div mat-dialog-content>\n  <div>Are yo sure you want to remove user?</div>\n  <div>{{data.id}}</div>\n</div>\n<div mat-dialog-actions>\n  <button mat-button cdkFocusInitial [mat-dialog-close]>Close</button>\n  <button mat-raised-button color=\"warn\" [mat-dialog-close]=\"true\">Remove</button>\n</div>",
            styles: [".mat-dialog-actions{-webkit-box-pack:end;justify-content:flex-end}"]
        }),
        __param(0, Inject(MAT_DIALOG_DATA)),
        __metadata("design:paramtypes", [Object])
    ], DeleteUserWarningComponent);
    return DeleteUserWarningComponent;
}());

var UsersDatabase = /** @class */ (function () {
    function UsersDatabase() {
        this.dataChange = new BehaviorSubject([]);
    }
    Object.defineProperty(UsersDatabase.prototype, "data", {
        get: function () { return this.dataChange.value; },
        enumerable: true,
        configurable: true
    });
    return UsersDatabase;
}());
var UsersDataSource = /** @class */ (function (_super) {
    __extends(UsersDataSource, _super);
    function UsersDataSource(usersDatabase) {
        var _this = _super.call(this) || this;
        _this.usersDatabase = usersDatabase;
        return _this;
    }
    UsersDataSource.prototype.connect = function () {
        return this.usersDatabase.dataChange;
    };
    UsersDataSource.prototype.disconnect = function () { };
    return UsersDataSource;
}(DataSource));
var UsersComponent = /** @class */ (function () {
    function UsersComponent(authorizatorservice, dialog, snackbar, progressbarservice) {
        this.authorizatorservice = authorizatorservice;
        this.dialog = dialog;
        this.snackbar = snackbar;
        this.progressbarservice = progressbarservice;
        this.displayedColumns = ['remove', 'user', 'permissions'];
        this.usersDatabase = new UsersDatabase();
        this.users = [];
    }
    UsersComponent.prototype.ngOnInit = function () {
        var _this = this;
        this.progressbarservice.showUsersWaitBar(true);
        this.authorizatorservice.getUsers(this.rootFirebasePath).then(function (users) {
            _this.progressbarservice.showUsersWaitBar(false);
            if (users) {
                _this.users = users.sort(function (prev, curr) {
                    if (prev.data.name > curr.data.name) {
                        return 1;
                    }
                    if (prev.data.name < curr.data.name) {
                        return -1;
                    }
                    return 0;
                });
                _this.usersDataSource = new UsersDataSource(_this.usersDatabase);
                _this.usersDatabase.dataChange.next(users);
            }
        });
    };
    UsersComponent.prototype.addUser = function () {
        var _this = this;
        var dialogRef = this.dialog.open(UpsertUserComponent, {
            width: '300px',
            data: { type: 'add', user: null, rootFirebasePath: this.rootFirebasePath }
        });
        dialogRef.afterClosed().subscribe(function (userAdded) {
            if (userAdded) {
                _this.users.push(userAdded);
                _this.users = _this.users.sort(function (prev, curr) {
                    if (prev.data.name > curr.data.name) {
                        return 1;
                    }
                    if (prev.data.name < curr.data.name) {
                        return -1;
                    }
                    return 0;
                });
                _this.usersDatabase.dataChange.next(_this.users);
                var config = new MatSnackBarConfig();
                config.duration = 3000;
                config.panelClass = ['success-bar'];
                _this.snackbar.open('User added successfully', null, config);
            }
        });
    };
    UsersComponent.prototype.removeUser = function (user) {
        var _this = this;
        var dialogRef = this.dialog.open(DeleteUserWarningComponent, {
            width: '300px',
            data: user
        });
        dialogRef.afterClosed().subscribe(function (response) {
            if (response) {
                _this.progressbarservice.showUsersWaitBar(true);
                _this.authorizatorservice.removeUser(_this.rootFirebasePath, user.id).then(function () {
                    _this.progressbarservice.showUsersWaitBar(false);
                    _this.users.splice(_this.users.findIndex(function (userArr) { return userArr.id === user.id; }), 1);
                    _this.usersDatabase.dataChange.next(_this.users);
                    var config = new MatSnackBarConfig();
                    config.duration = 3000;
                    config.panelClass = ['success-bar'];
                    _this.snackbar.open('User removed successfully', null, config);
                }).catch(function (error) {
                    var config = new MatSnackBarConfig();
                    config.duration = 3000;
                    config.panelClass = ['error-bar'];
                    _this.snackbar.open(error.message, null, config);
                });
            }
        });
    };
    UsersComponent.prototype.setPermissions = function (userInput) {
        var dialogRef = this.dialog.open(PermissionManagerComponent, {
            width: '95%',
            maxWidth: '600px',
            data: { rootFirebasePath: this.rootFirebasePath, user: userInput }
        });
    };
    UsersComponent.ctorParameters = function () { return [
        { type: AuthorizatorService },
        { type: MatDialog },
        { type: MatSnackBar },
        { type: ProgressbarService }
    ]; };
    __decorate([
        Input(),
        __metadata("design:type", String)
    ], UsersComponent.prototype, "rootFirebasePath", void 0);
    UsersComponent = __decorate([
        Component({
            selector: 'lib-users',
            template: "<div class=\"users-container\">\n  <button mat-raised-button (click)=\"addUser()\"><mat-icon color=\"primary\">person_add</mat-icon> Add User</button>\n  <table mat-table [dataSource]=\"usersDataSource\" style=\"width: 100%;\">\n    <!--- Note that these columns can be defined in any order.\n          The actual rendered columns are set as a property on the row definition\" -->\n  \n    <!-- Remove Column -->\n    <ng-container matColumnDef=\"remove\">\n      <th mat-header-cell *matHeaderCellDef [ngClass]=\"'icon-column'\"></th>\n      <td mat-cell *matCellDef=\"let user\" [ngClass]=\"'icon-column'\">\n        <button mat-icon-button (click)=\"removeUser(user)\">\n          <mat-icon color=\"primary\" aria-label=\"Remove user\">delete</mat-icon>\n        </button>\n      </td>\n    </ng-container>\n  \n    <!-- User Column -->\n    <ng-container matColumnDef=\"user\">\n      <th mat-header-cell *matHeaderCellDef [ngClass]=\"'users-column'\"> User </th>\n      <td mat-cell *matCellDef=\"let user\" [ngClass]=\"'users-column'\">\n        <div>{{user.data.name}}</div>\n        <div>{{user.data.email}}</div>\n      </td>\n    </ng-container>\n  \n    <!-- Permissions Column -->\n    <ng-container matColumnDef=\"permissions\">\n      <th mat-header-cell *matHeaderCellDef [ngClass]=\"'permissions-column'\">Permissions</th>\n      <td mat-cell *matCellDef=\"let user\" [ngClass]=\"'permissions-column'\">\n        <button mat-button (click)=\"setPermissions(user)\">\n          <mat-icon color=\"primary\" aria-label=\"Set permissions\">vpn_key</mat-icon>\n        </button>\n      </td>\n    </ng-container>\n  \n    <tr mat-header-row *matHeaderRowDef=\"displayedColumns\"></tr>\n    <tr mat-row *matRowDef=\"let row; columns: displayedColumns;\"></tr>\n  </table>\n</div>\n",
            styles: [".icon-column{-webkit-box-flex:0;flex:0 0 50px}.permissions-column{-webkit-box-flex:0;flex:0 0 100px}.users-column{-webkit-box-flex:0;flex:0 0 300px}.users-container{width:470px;margin:auto;padding:20px}"]
        }),
        __metadata("design:paramtypes", [AuthorizatorService, MatDialog,
            MatSnackBar,
            ProgressbarService])
    ], UsersComponent);
    return UsersComponent;
}());

var UsersDatabase$1 = /** @class */ (function () {
    function UsersDatabase() {
        this.dataChange = new BehaviorSubject([]);
    }
    Object.defineProperty(UsersDatabase.prototype, "data", {
        get: function () { return this.dataChange.value; },
        enumerable: true,
        configurable: true
    });
    return UsersDatabase;
}());
var UsersDataSource$1 = /** @class */ (function (_super) {
    __extends(UsersDataSource, _super);
    function UsersDataSource(usersDatabase) {
        var _this = _super.call(this) || this;
        _this.usersDatabase = usersDatabase;
        return _this;
    }
    UsersDataSource.prototype.connect = function () {
        return this.usersDatabase.dataChange;
    };
    UsersDataSource.prototype.disconnect = function () { };
    return UsersDataSource;
}(DataSource));
var UpsertRoleComponent = /** @class */ (function () {
    function UpsertRoleComponent(data, authorizatorservice, dialogRef) {
        this.data = data;
        this.authorizatorservice = authorizatorservice;
        this.dialogRef = dialogRef;
        this.displayedColumns = ['remove', 'user'];
        this.usersDatabase = new UsersDatabase$1();
        this.users = [];
        this.roleUsers = [];
        this.roleForm = new FormGroup({
            name: new FormControl(null, [Validators.required]),
            description: new FormControl(null),
        });
    }
    UpsertRoleComponent.prototype.ngOnInit = function () {
        var _this = this;
        this.usersDataSource = new UsersDataSource$1(this.usersDatabase);
        this.authorizatorservice.getUsers(this.data.rootFirebasePath).then(function (users) {
            if (users) {
                _this.users = users.sort(function (prev, curr) {
                    if (prev.data.name > curr.data.name) {
                        return 1;
                    }
                    if (prev.data.name < curr.data.name) {
                        return -1;
                    }
                    return 0;
                });
                _this.roleUsers = _this.users.filter(function (user) { return _this.data && _this.data.role && _this.data.role.data.users.findIndex(function (usr) { return usr === user.id; }) > -1; });
                if (_this.roleUsers) {
                    _this.roleUsers = _this.roleUsers.sort(function (prev, curr) {
                        if (prev.data.name > curr.data.name) {
                            return 1;
                        }
                        if (prev.data.name < curr.data.name) {
                            return -1;
                        }
                        return 0;
                    });
                    _this.usersDatabase.dataChange.next(_this.roleUsers);
                }
            }
        });
        if (this.data.role) {
            this.roleForm.controls.name.setValue(this.data.role.data.name);
            this.roleForm.controls.description.setValue(this.data.role.data.description);
        }
    };
    UpsertRoleComponent.prototype.onAddUserToRole = function () {
        var _this = this;
        var existUser = this.roleUsers.findIndex(function (roleUser) { return roleUser.id === _this.selectUser.value; });
        if (existUser === -1) {
            this.roleUsers.push(this.users.find(function (user) { return user.id === _this.selectUser.value; }));
            this.roleUsers = this.roleUsers.sort(function (prev, curr) {
                if (prev.data.name > curr.data.name) {
                    return 1;
                }
                if (prev.data.name < curr.data.name) {
                    return -1;
                }
                return 0;
            });
            this.usersDatabase.dataChange.next(this.roleUsers);
        }
    };
    UpsertRoleComponent.prototype.onRemoveUserFromRole = function (user) {
        var userIndex = this.roleUsers.findIndex(function (roleUser) { return roleUser.id === user.id; });
        if (userIndex > -1) {
            this.roleUsers.splice(userIndex, 1);
            this.usersDatabase.dataChange.next(this.roleUsers);
        }
    };
    UpsertRoleComponent.prototype.onSubmitRole = function () {
        var _this = this;
        if (this.roleForm.valid) {
            var roleToAdd_1 = {
                id: this.data.role ? this.data.role.id : null,
                data: {
                    name: this.roleForm.controls.name.value,
                    description: this.roleForm.controls.description.value,
                    users: this.roleUsers.map(function (user) { return user.id; }),
                    permissions: null
                }
            };
            if (roleToAdd_1.id) {
                this.authorizatorservice.updateRole(this.data.rootFirebasePath, roleToAdd_1).then(function () {
                    _this.dialogRef.close(roleToAdd_1);
                }).catch(function (error) {
                    _this.roleForm.controls.name.setErrors({ defaulterror: true });
                });
            }
            else {
                this.authorizatorservice.addRole(this.data.rootFirebasePath, roleToAdd_1).then(function () {
                    _this.dialogRef.close(roleToAdd_1);
                }).catch(function (error) {
                    if (error.key === 'exists') {
                        _this.roleForm.controls.name.setErrors({ exists: true });
                    }
                    else {
                        _this.roleForm.controls.name.setErrors({ defaulterror: true });
                    }
                });
            }
        }
    };
    UpsertRoleComponent.ctorParameters = function () { return [
        { type: undefined, decorators: [{ type: Inject, args: [MAT_DIALOG_DATA,] }] },
        { type: AuthorizatorService },
        { type: MatDialogRef }
    ]; };
    __decorate([
        ViewChild('selectUser'),
        __metadata("design:type", MatSelect)
    ], UpsertRoleComponent.prototype, "selectUser", void 0);
    UpsertRoleComponent = __decorate([
        Component({
            selector: 'lib-upsert-role',
            template: "<form [formGroup]=\"roleForm\" (ngSubmit)=\"onSubmitRole()\" method=\"post\">\n  <h1 mat-dialog-title>{{data.role ? 'Edit Role' : 'Add Role'}}</h1>\n  <div mat-dialog-content>\n    <mat-form-field style=\"width: 100%;\">\n        <input matInput cdkFocusInitial placeholder=\"Name\" formControlName=\"name\" maxlength=\"30\">\n        <mat-error *ngIf=\"roleForm.controls['name'].hasError('required')\">Mandatory field</mat-error>\n        <mat-error *ngIf=\"roleForm.controls['name'].hasError('exists')\">Email already exists</mat-error>\n        <mat-error *ngIf=\"roleForm.controls['name'].hasError('defaulterror')\">Error updating role</mat-error>\n    </mat-form-field>\n    <mat-form-field style=\"width: 100%;\">\n        <input matInput cdkFocusInitial placeholder=\"Description\" formControlName=\"description\" maxlength=\"150\">\n    </mat-form-field>\n    <table style=\"width: 100%;\">\n      <tr>\n        <th style=\"width: 100%;\">\n          <mat-form-field style=\"width: 100%;\">\n            <mat-label>User</mat-label>\n            <mat-select #selectUser>\n              <mat-option *ngFor=\"let user of users\" [value]=\"user.id\">\n                {{user.data.name || user.data.email}}\n              </mat-option>\n            </mat-select>\n          </mat-form-field>\n        </th>\n        <th>\n          <button type=\"button\" [disabled]=\"!this.selectUser.value\" mat-raised-button (click)=\"onAddUserToRole()\">\n            <mat-icon color=\"primary\">person_add</mat-icon> Add User\n          </button>\n        </th>\n      </tr>\n    </table>\n    <table mat-table [dataSource]=\"usersDataSource\" style=\"width: 100%;\">\n    \n      <!-- Remove Column -->\n      <ng-container matColumnDef=\"remove\">\n        <th mat-header-cell *matHeaderCellDef [ngClass]=\"'icon-column'\"></th>\n        <td mat-cell *matCellDef=\"let user\" [ngClass]=\"'icon-column'\">\n          <button mat-icon-button (click)=\"onRemoveUserFromRole(user)\">\n            <mat-icon color=\"primary\" aria-label=\"Remove user\">delete</mat-icon>\n          </button>\n        </td>\n      </ng-container>\n    \n      <!-- User Column -->\n      <ng-container matColumnDef=\"user\">\n        <th mat-header-cell *matHeaderCellDef [ngClass]=\"'users-column'\"> User </th>\n        <td mat-cell *matCellDef=\"let user\" [ngClass]=\"'users-column'\">\n          <div>{{user.data.name}}</div>\n          <div>{{user.data.email}}</div>\n        </td>\n      </ng-container>\n    \n      <tr mat-header-row *matHeaderRowDef=\"displayedColumns\"></tr>\n      <tr mat-row *matRowDef=\"let row; columns: displayedColumns;\"></tr>\n    </table>\n  </div>\n  <div mat-dialog-actions>\n    <button mat-button [mat-dialog-close]>Close</button>\n    <button mat-raised-button color=\"primary\" type=\"submit\" [disabled]=\"!roleForm.valid\">{{data.role ? 'Update' : 'Add'}}</button>\n  </div>\n</form>\n  ",
            styles: [".mat-dialog-actions{-webkit-box-pack:end;justify-content:flex-end}"]
        }),
        __param(0, Inject(MAT_DIALOG_DATA)),
        __metadata("design:paramtypes", [Object, AuthorizatorService,
            MatDialogRef])
    ], UpsertRoleComponent);
    return UpsertRoleComponent;
}());

var DeleteRoleWarningComponent = /** @class */ (function () {
    function DeleteRoleWarningComponent(data) {
        this.data = data;
    }
    DeleteRoleWarningComponent.prototype.ngOnInit = function () {
    };
    DeleteRoleWarningComponent.ctorParameters = function () { return [
        { type: undefined, decorators: [{ type: Inject, args: [MAT_DIALOG_DATA,] }] }
    ]; };
    DeleteRoleWarningComponent = __decorate([
        Component({
            selector: 'lib-delete-role-warning',
            template: "<h1 mat-dialog-title>Remove Role</h1>\n<div mat-dialog-content>\n  <div>Are yo sure you want to remove role?</div>\n  <div>{{data.data.name}}</div>\n</div>\n<div mat-dialog-actions>\n  <button mat-button cdkFocusInitial [mat-dialog-close]>Close</button>\n  <button mat-raised-button color=\"warn\" [mat-dialog-close]=\"true\">Remove</button>\n</div>",
            styles: [".mat-dialog-actions{-webkit-box-pack:end;justify-content:flex-end}"]
        }),
        __param(0, Inject(MAT_DIALOG_DATA)),
        __metadata("design:paramtypes", [Object])
    ], DeleteRoleWarningComponent);
    return DeleteRoleWarningComponent;
}());

var RolesDatabase = /** @class */ (function () {
    function RolesDatabase() {
        this.dataChange = new BehaviorSubject([]);
    }
    Object.defineProperty(RolesDatabase.prototype, "data", {
        get: function () { return this.dataChange.value; },
        enumerable: true,
        configurable: true
    });
    return RolesDatabase;
}());
var RolesDataSource = /** @class */ (function (_super) {
    __extends(RolesDataSource, _super);
    function RolesDataSource(rolesDatabase) {
        var _this = _super.call(this) || this;
        _this.rolesDatabase = rolesDatabase;
        return _this;
    }
    RolesDataSource.prototype.connect = function () {
        return this.rolesDatabase.dataChange;
    };
    RolesDataSource.prototype.disconnect = function () { };
    return RolesDataSource;
}(DataSource));
var RolesComponent = /** @class */ (function () {
    function RolesComponent(authorizatorservice, dialog, snackbar, progressbarservice) {
        this.authorizatorservice = authorizatorservice;
        this.dialog = dialog;
        this.snackbar = snackbar;
        this.progressbarservice = progressbarservice;
        this.displayedColumns = ['remove', 'edit', 'role', 'permissions'];
        this.rolesDatabase = new RolesDatabase();
        this.roles = [];
    }
    RolesComponent.prototype.ngOnInit = function () {
        var _this = this;
        this.progressbarservice.showRolesWaitBar(true);
        this.authorizatorservice.getRoles(this.rootFirebasePath).then(function (roles) {
            if (roles) {
                _this.roles = roles.sort(function (prev, curr) {
                    if (prev.data.name > curr.data.name) {
                        return 1;
                    }
                    if (prev.data.name < curr.data.name) {
                        return -1;
                    }
                    return 0;
                });
                _this.rolesDataSource = new RolesDataSource(_this.rolesDatabase);
                _this.rolesDatabase.dataChange.next(roles);
                _this.progressbarservice.showRolesWaitBar(false);
            }
        }).catch(function (error) {
            console.error(error);
        }).finally(function () {
            _this.progressbarservice.showRolesWaitBar(false);
        });
    };
    RolesComponent.prototype.addRole = function () {
        var _this = this;
        var dialogRef = this.dialog.open(UpsertRoleComponent, {
            width: '95%',
            maxWidth: '500px',
            data: { role: null, rootFirebasePath: this.rootFirebasePath }
        });
        dialogRef.afterClosed().subscribe(function (roleAdded) {
            if (roleAdded) {
                _this.roles.push(roleAdded);
                _this.roles = _this.roles.sort(function (prev, curr) {
                    if (prev.data.name > curr.data.name) {
                        return 1;
                    }
                    if (prev.data.name < curr.data.name) {
                        return -1;
                    }
                    return 0;
                });
                _this.rolesDatabase.dataChange.next(_this.roles);
                var config = new MatSnackBarConfig();
                config.duration = 3000;
                config.panelClass = ['success-bar'];
                _this.snackbar.open('Role added successfully', null, config);
            }
        });
    };
    RolesComponent.prototype.editRole = function (inputRole) {
        var _this = this;
        var dialogRef = this.dialog.open(UpsertRoleComponent, {
            width: '95%',
            maxWidth: '500px',
            data: { role: inputRole, rootFirebasePath: this.rootFirebasePath }
        });
        dialogRef.afterClosed().subscribe(function (roleUpdated) {
            if (roleUpdated) {
                var roleUpdatedIndex = _this.roles.findIndex(function (role) { return role.id === roleUpdated.id; });
                if (roleUpdatedIndex > -1) {
                    _this.roles[roleUpdatedIndex].data = roleUpdated.data;
                    _this.rolesDatabase.dataChange.next(_this.roles);
                }
                var config = new MatSnackBarConfig();
                config.duration = 3000;
                config.panelClass = ['success-bar'];
                _this.snackbar.open('Role updated successfully', null, config);
            }
        });
    };
    RolesComponent.prototype.removeRole = function (role) {
        var _this = this;
        var dialogRef = this.dialog.open(DeleteRoleWarningComponent, {
            width: '300px',
            data: role
        });
        dialogRef.afterClosed().subscribe(function (response) {
            if (response) {
                _this.progressbarservice.showRolesWaitBar(true);
                _this.authorizatorservice.removeRole(_this.rootFirebasePath, role.id).then(function () {
                    _this.roles.splice(_this.roles.findIndex(function (roleArr) { return roleArr.id === role.id; }), 1);
                    _this.rolesDatabase.dataChange.next(_this.roles);
                    var config = new MatSnackBarConfig();
                    config.duration = 3000;
                    config.panelClass = ['success-bar'];
                    _this.snackbar.open('Role removed successfully', null, config);
                    _this.progressbarservice.showRolesWaitBar(false);
                }).catch(function (error) {
                    var config = new MatSnackBarConfig();
                    config.duration = 3000;
                    config.panelClass = ['error-bar'];
                    _this.snackbar.open(error.message, null, config);
                });
            }
        });
    };
    RolesComponent.prototype.setPermissions = function (roleInput) {
        var dialogRef = this.dialog.open(PermissionManagerComponent, {
            width: '95%',
            maxWidth: '600px',
            data: { rootFirebasePath: this.rootFirebasePath, role: roleInput }
        });
    };
    RolesComponent.ctorParameters = function () { return [
        { type: AuthorizatorService },
        { type: MatDialog },
        { type: MatSnackBar },
        { type: ProgressbarService }
    ]; };
    __decorate([
        Input(),
        __metadata("design:type", String)
    ], RolesComponent.prototype, "rootFirebasePath", void 0);
    RolesComponent = __decorate([
        Component({
            selector: 'lib-roles',
            template: "<div class=\"roles-container\">\n  <button mat-raised-button (click)=\"addRole()\"><mat-icon color=\"primary\">group_add</mat-icon> Add Role</button>\n  <table mat-table [dataSource]=\"rolesDataSource\" style=\"width: 100%;\">\n    <!--- Note that these columns can be defined in any order.\n          The actual rendered columns are set as a property on the row definition\" -->\n  \n    <!-- Remove Column -->\n    <ng-container matColumnDef=\"remove\">\n      <th mat-header-cell *matHeaderCellDef [ngClass]=\"'icon-column'\"></th>\n      <td mat-cell *matCellDef=\"let role\" [ngClass]=\"'icon-column'\">\n        <button mat-icon-button (click)=\"removeRole(role)\">\n          <mat-icon color=\"primary\" aria-label=\"Remove role\">delete</mat-icon>\n        </button>\n      </td>\n    </ng-container>\n\n    <!-- Edit Column -->\n    <ng-container matColumnDef=\"edit\">\n      <th mat-header-cell *matHeaderCellDef [ngClass]=\"'icon-column'\"></th>\n      <td mat-cell *matCellDef=\"let role\" [ngClass]=\"'icon-column'\">\n        <button mat-icon-button (click)=\"editRole(role)\">\n          <mat-icon color=\"primary\" aria-label=\"Edit role\">edit</mat-icon>\n        </button>\n      </td>\n    </ng-container>\n  \n    <!-- Role Column -->\n    <ng-container matColumnDef=\"role\">\n      <th mat-header-cell *matHeaderCellDef [ngClass]=\"'roles-column'\"> User </th>\n      <td mat-cell *matCellDef=\"let role\" [ngClass]=\"'roles-column'\">\n        <div>{{role.data.name}}</div>\n        <div>{{role.data.email}}</div>\n      </td>\n    </ng-container>\n  \n    <!-- Permissions Column -->\n    <ng-container matColumnDef=\"permissions\">\n      <th mat-header-cell *matHeaderCellDef [ngClass]=\"'permissions-column'\">Permissions</th>\n      <td mat-cell *matCellDef=\"let role\" [ngClass]=\"'permissions-column'\">\n        <button mat-button (click)=\"setPermissions(role)\">\n          <mat-icon color=\"primary\" aria-label=\"Set permissions\">vpn_key</mat-icon>\n        </button>\n      </td>\n    </ng-container>\n  \n    <tr mat-header-row *matHeaderRowDef=\"displayedColumns\"></tr>\n    <tr mat-row *matRowDef=\"let row; columns: displayedColumns;\"></tr>\n  </table>\n</div>\n  ",
            styles: [".icon-column{-webkit-box-flex:0;flex:0 0 50px}.permissions-column{-webkit-box-flex:0;flex:0 0 100px}.roles-column{-webkit-box-flex:0;flex:0 0 300px}.roles-container{width:470px;margin:auto;padding:20px}"]
        }),
        __metadata("design:paramtypes", [AuthorizatorService, MatDialog,
            MatSnackBar,
            ProgressbarService])
    ], RolesComponent);
    return RolesComponent;
}());

var AngularFirebaseAuthorizatorModule = /** @class */ (function () {
    function AngularFirebaseAuthorizatorModule() {
    }
    AngularFirebaseAuthorizatorModule_1 = AngularFirebaseAuthorizatorModule;
    AngularFirebaseAuthorizatorModule.forRoot = function (authorizatorConfig) {
        return {
            ngModule: AngularFirebaseAuthorizatorModule_1,
            providers: [
                {
                    provide: AUTHORIZATOR_CONFIG,
                    useValue: authorizatorConfig
                }
            ]
        };
    };
    var AngularFirebaseAuthorizatorModule_1;
    AngularFirebaseAuthorizatorModule = AngularFirebaseAuthorizatorModule_1 = __decorate([
        NgModule({
            declarations: [
                PermissionManagerComponent, AngularFirebaseAuthotizatorComponent,
                UsersComponent, UpsertUserComponent, DeleteUserWarningComponent,
                RolesComponent, DeleteRoleWarningComponent, UpsertRoleComponent
            ],
            imports: [
                CommonModule,
                FormsModule,
                ReactiveFormsModule,
                MatGridListModule,
                MatSlideToggleModule,
                MatButtonToggleModule,
                MatSelectModule,
                MatIconModule,
                MatTabsModule,
                MatTableModule,
                MatButtonModule,
                MatDialogModule,
                MatInputModule,
                MatSnackBarModule,
                MatProgressBarModule
            ],
            exports: [AngularFirebaseAuthotizatorComponent],
            providers: [AuthorizatorService, ProgressbarService],
            entryComponents: [
                UpsertUserComponent, DeleteUserWarningComponent,
                UpsertRoleComponent, DeleteRoleWarningComponent,
                PermissionManagerComponent
            ]
        })
    ], AngularFirebaseAuthorizatorModule);
    return AngularFirebaseAuthorizatorModule;
}());

/*
 * Public API Surface of angular-firebase-authorizator
 */

/**
 * Generated bundle index. Do not edit.
 */

export { AngularFirebaseAuthorizatorModule, AngularFirebaseAuthotizatorComponent, AuthGuard, AuthorizatorService, Operation, AUTHORIZATOR_CONFIG as ɵa, ProgressbarService as ɵb, PermissionManagerComponent as ɵc, UsersComponent as ɵd, UpsertUserComponent as ɵe, DeleteUserWarningComponent as ɵf, RolesComponent as ɵg, DeleteRoleWarningComponent as ɵh, UpsertRoleComponent as ɵi };
//# sourceMappingURL=angular-firebase-authorizator.js.map