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

16 lines (14 loc) 41 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@angular/core"),require("rxjs"),require("firebase"),require("@angular/router"),require("rxjs/operators"),require("@angular/material/dialog"),require("@angular/material/snack-bar"),require("@angular/material/grid-list"),require("@angular/material/slide-toggle"),require("@angular/material/button-toggle"),require("@angular/material/select"),require("@angular/material/icon"),require("@angular/material/tabs"),require("@angular/material/table"),require("@angular/material/button"),require("@angular/material/input"),require("@angular/material/progress-bar"),require("@angular/common"),require("@angular/cdk/table"),require("@angular/forms")):"function"==typeof define&&define.amd?define("angular-firebase-authorizator",["exports","@angular/core","rxjs","firebase","@angular/router","rxjs/operators","@angular/material/dialog","@angular/material/snack-bar","@angular/material/grid-list","@angular/material/slide-toggle","@angular/material/button-toggle","@angular/material/select","@angular/material/icon","@angular/material/tabs","@angular/material/table","@angular/material/button","@angular/material/input","@angular/material/progress-bar","@angular/common","@angular/cdk/table","@angular/forms"],t):t((e=e||self)["angular-firebase-authorizator"]={},e.ng.core,e.rxjs,e.firebase,e.ng.router,e.rxjs.operators,e.ng.material.dialog,e.ng.material["snack-bar"],e.ng.material["grid-list"],e.ng.material["slide-toggle"],e.ng.material["button-toggle"],e.ng.material.select,e.ng.material.icon,e.ng.material.tabs,e.ng.material.table,e.ng.material.button,e.ng.material.input,e.ng.material["progress-bar"],e.ng.common,e.ng.cdk.table,e.ng.forms)}(this,(function(e,t,r,n,o,a,i,s,l,c,u,d,m,p,f,h,g,b,v,y,C){"use strict"; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */var x=function(e,t){return(x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function w(e,t){function r(){this.constructor=e}x(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var R;function D(e,t,r,n){var o,a=arguments.length,i=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,r,n);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(i=(a<3?o(i):a>3?o(t,r,i):o(t,r))||i);return a>3&&i&&Object.defineProperty(t,r,i),i}function k(e,t){return function(r,n){t(r,n,e)}}function P(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}(R=e.Operation||(e.Operation={}))[R.Create=0]="Create",R[R.Read=1]="Read",R[R.Update=2]="Update",R[R.Delete=3]="Delete",R[R.Deny=4]="Deny";var I=function(){function e(){this.usersWaitBar=new r.BehaviorSubject(null),this.rolesWaitBar=new r.BehaviorSubject(null)}return e.prototype.showUsersWaitBar=function(e){this.usersWaitBar.next(e)},e.prototype.showRolesWaitBar=function(e){this.rolesWaitBar.next(e)},e.ɵprov=t["ɵɵdefineInjectable"]({factory:function(){return new e},token:e,providedIn:"root"}),e=D([t.Injectable({providedIn:"root"}),P("design:paramtypes",[])],e)}(),U=new t.InjectionToken("AUTHORIZATOR_CONFIG"),F=function(){function i(e,t){this.router=e,this.authorizatorservice=t}return i.prototype.isAuthorized=function(t,o){var a=this;return new r.Observable((function(r){n.auth().onAuthStateChanged((function(n){n?o?Promise.all([a.authorizatorservice.getUser(t,n.email),a.authorizatorservice.getRolesByUser(t,n.email)]).then((function(t){var n=t[0],a=t[1]||[],i=[],s=[];n&&n.data.permissions&&n.data.permissions.filter((function(e){return e.resource===o||"owner"===e.resource})).forEach((function(e){i.push(e)})),a.forEach((function(e){e.data.permissions&&e.data.permissions.filter((function(e){return e.resource===o})).forEach((function(e){s.push(e)}))})),i&&i.length>0&&-1===i.findIndex((function(t){return t.operations&&t.operations.findIndex((function(t){return t===e.Operation.Deny}))>-1}))?r.next("authorized"):s&&s.length>0&&-1===s.findIndex((function(t){return t.operations.findIndex((function(t){return t===e.Operation.Deny}))>-1}))?r.next("authorized"):(console.error("Unauthorized resource"),r.next("unauthorized"))})).catch((function(e){console.error("Error getting permissions from database"),console.error(e),r.next("unauthorized")})):(console.error("Resource not received"),r.next("unauthorized")):(console.error("Unauthenticated user"),r.next("unauthenticated"))}),(function(e){r.error(e)}),(function(){r.complete()}))}))},i.prototype.canActivate=function(e,t){var n=this,o=e.data.rootFirebasePath,i=e.data.resource,s=e.data.anonymousRoute||"/",l=e.data.unauthorizedRoute||"/",c=o.indexOf(":");if(c>-1){var u,d=o.indexOf("/",c);u=d>-1?o.substring(c+1,d):o.substring(c+1),Object.keys(e.params).findIndex((function(e){return e===u}))>-1&&(o=o.replace(":"+u,e.params[u]))}return this.isAuthorized(o,i).pipe(a.take(1),a.map((function(e){return"unauthenticated"===e?(n.router.navigate([s],{queryParams:{returnUrl:t.url}}),!1):"unauthorized"===e?(n.router.navigate([l],{queryParams:{returnUrl:t.url}}),!1):"authorized"===e})),a.catchError((function(e){return console.error("Error getting authenticated user"),console.error(e),n.router.navigate([s],{queryParams:{returnUrl:t.url}}),r.of(!1)})))},i.ctorParameters=function(){return[{type:o.Router},{type:A}]},i=D([t.Injectable(),P("design:paramtypes",[o.Router,A])],i)}(),A=function(){function e(){}return e.prototype.addUser=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=((e=e||"")+"/users").replace("//","/");a.collection(i).doc(t.id).get().then((function(e){e.exists?o({key:"exists",message:"User already exists"}):a.collection(i).doc(t.id).set(t.data).then((function(){r()})).catch((function(e){console.error(e),o({key:"defaulterror",message:"Error adding user"})}))}))}))},e.prototype.removeUser=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=((e=e||"")+"/users").replace("//","/");a.collection(i).doc(t).delete().then((function(){r()})).catch((function(e){console.error(e),o({key:"defaulterror",message:"Error removing user"})}))}))},e.prototype.getUser=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=(e+"/users").replace("//","/");a.collection(i).doc(t).get().then((function(e){r({id:e.id,data:e.data()})})).catch((function(e){o(e)}))}))},e.prototype.getUsers=function(e){return new Promise((function(t,r){var o=n.firestore();e||(e="");var a=(e+"/users").replace("//","/");o.collection(a).get().then((function(e){e.empty?t(null):t(e.docs.map((function(e){return{id:e.id,data:e.data()}})))})).catch((function(e){r(e)}))}))},e.prototype.updateUserPermissions=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=((e=e||"")+"/users").replace("//","/");a.collection(i).doc(t.id).get().then((function(e){e.exists?a.collection(i).doc(t.id).update({permissions:t.data.permissions}).then((function(){r()})).catch((function(e){console.error(e),o({key:"defaulterror",message:"Error updating permissions"})})):o({key:"notexists",message:"User not exists"})}))}))},e.prototype.addResource=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=(e+"/resources").replace("//","/");a.collection(i).add(t.data).then((function(e){r(e.id)})).catch((function(e){o(e)}))}))},e.prototype.removeResource=function(e,t){var r=this;return new Promise((function(o,a){var i=n.firestore(),s=(e+"/resources").replace("//","/"),l=(e+"/users").replace("//","/"),c=(e+"/roles").replace("//","/"),u=i.collection(s).doc(t);Promise.all([r.getUsersByResource(e,t),r.getRolesByResource(e,t)]).then((function(e){var r=i.batch(),n=e[0],s=e[1];n.forEach((function(e){e.data.permissions.splice(e.data.permissions.findIndex((function(e){return e.resource===t})),1);var n=i.collection(l).doc(e.id);r.update(n,{data:e.data})})),s.forEach((function(e){e.data.permissions.splice(e.data.permissions.findIndex((function(e){return e.resource===t})),1);var n=i.collection(c).doc(e.id);r.update(n,{data:e.data})})),r.delete(u),r.commit().then((function(){o()})).catch((function(e){a(e)}))})).catch((function(e){a(e)}))}))},e.prototype.updateResource=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=(e+"/resources").replace("//","/");a.collection(i).doc(t.id).set(t.data).then((function(){r()})).catch((function(e){o(e)}))}))},e.prototype.getResource=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=(e+"/resources").replace("//","/");a.collection(i).doc(t).get().then((function(e){r({id:e.id,data:e.data()})})).catch((function(e){o(e)}))}))},e.prototype.getResources=function(e){return new Promise((function(t,r){var o=n.firestore(),a=(e+"/resources").replace("//","/");o.collection(a).get().then((function(e){e.empty?t(null):t(e.docs.map((function(e){return{id:e.id,data:e.data()}})))})).catch((function(e){r(e)}))}))},e.prototype.addRole=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=((e=e||"")+"/roles").replace("//","/");a.collection(i).where("name","==",t.data.name).get().then((function(e){e.empty?a.collection(i).add(t.data).then((function(){r()})).catch((function(e){console.error(e),o({key:"defaulterror",message:"Error adding role"})})):o({key:"exists",message:"Role already exists"})}))}))},e.prototype.removeRole=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=((e=e||"")+"/roles").replace("//","/");a.collection(i).doc(t).delete().then((function(){r()})).catch((function(e){console.error(e),o({key:"defaulterror",message:"Error removing role"})}))}))},e.prototype.updateRole=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=((e=e||"")+"/roles").replace("//","/");a.collection(i).doc(t.id).set(t.data).then((function(){r()})).catch((function(e){console.error(e),o({key:"defaulterror",message:"Error updating role"})}))}))},e.prototype.getRole=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=(e+"/roles").replace("//","/");a.collection(i).doc(t).get().then((function(e){r({id:e.id,data:e.data()})})).catch((function(e){o(e)}))}))},e.prototype.getRoles=function(e){return new Promise((function(t,r){var o=n.firestore();e||(e="");var a=(e+"/roles").replace("//","/");o.collection(a).get().then((function(e){e.empty?t(null):t(e.docs.map((function(e){return{id:e.id,data:e.data()}})))})).catch((function(e){r(e)}))}))},e.prototype.getRolesByResource=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=(e+"/roles").replace("//","/");a.collection(i).where("data.resources","array-contains",t).get().then((function(e){e.empty?r(null):r(e.docs.map((function(e){return{id:e.id,data:e.data()}})))})).catch((function(e){o(e)}))}))},e.prototype.getRolesByUser=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=(e+"/roles").replace("//","/");a.collection(i).where("users","array-contains",t).get().then((function(e){e.empty?r(null):r(e.docs.map((function(e){return{id:e.id,data:e.data()}})))})).catch((function(e){o(e)}))}))},e.prototype.updateRolePermissions=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=((e=e||"")+"/roles").replace("//","/");a.collection(i).doc(t.id).get().then((function(e){e.exists?a.collection(i).doc(t.id).update({permissions:t.data.permissions}).then((function(){r()})).catch((function(e){console.error(e),o({key:"defaulterror",message:"Error updating permissions"})})):o({key:"notexists",message:"Role not exists"})}))}))},e.prototype.removeUserFromRole=function(e,t){var r=this;return new Promise((function(o,a){var i=n.firestore(),s=(e+"/users").replace("//","/"),l=(e+"/roles").replace("//","/");r.getRolesByUser(e,t).then((function(e){var r=i.batch();e.forEach((function(e){e.data.users.splice(e.data.users.findIndex((function(e){return e===t})),1);var n=i.collection(l).doc(e.id);r.update(n,{data:e.data})}));var n=i.collection(s).doc(t);r.delete(n),r.commit().then((function(){o()})).catch((function(e){a(e)}))})).catch((function(e){a(e)}))}))},e.prototype.getUsersByResource=function(e,t){return new Promise((function(r,o){var a=n.firestore(),i=(e+"/users").replace("//","/");a.collection(i).where("data.resources","array-contains",t).get().then((function(e){e.empty?r(null):r(e.docs.map((function(e){return{id:e.id,data:e.data()}})))})).catch((function(e){o(e)}))}))},e=D([t.Injectable(),P("design:paramtypes",[])],e)}(),M=function(){function e(e,t,r,n){this.progressbarservice=e,this.cd=t,this.authorizatorConfig=r,this.authroizatorservice=n,this.isUsersWaitBarShowing=!1,this.isRolesWaitBarShowing=!1}return e.prototype.ngOnInit=function(){var e=this;this.progressbarservice.usersWaitBar.subscribe((function(t){e.isUsersWaitBarShowing=t,e.cd.detectChanges()})),this.progressbarservice.rolesWaitBar.subscribe((function(t){e.isRolesWaitBarShowing=t,e.cd.detectChanges()}))},e.ctorParameters=function(){return[{type:I},{type:t.ChangeDetectorRef},{type:void 0,decorators:[{type:t.Inject,args:[U]}]},{type:A}]},D([t.Input(),P("design:type",String)],e.prototype,"rootFirebasePath",void 0),e=D([t.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}"]}),k(2,t.Inject(U)),P("design:paramtypes",[I,t.ChangeDetectorRef,Object,A])],e)}(),O=function(){function n(r,n,o,a,i){this.authorizatorConfig=r,this.cd=n,this.data=o,this.authorizatorservice=a,this.snackbar=i,this.AllowedOperation=e.Operation,this.resourceCols=5,this.permissionCols=5,this.change=new t.EventEmitter,this.user=o.user,this.role=o.role}return n.prototype.ngOnInit=function(){var e=this;this.authorizatorConfig&&this.authorizatorConfig.permissions?this.permissionsConfig=this.authorizatorConfig.permissions.map((function(t){return{resource:t.resource,operations:t.allowedOperations.map((function(r){return{id:r,value:e.user?!!e.user.data.permissions&&(!!e.user.data.permissions.find((function(e){return e.resource===t.resource.id}))&&e.user.data.permissions.find((function(e){return e.resource===t.resource.id})).operations.findIndex((function(e){return e===r}))>-1):!!e.role&&(!!e.role.data.permissions&&(!!e.role.data.permissions.find((function(e){return e.resource===t.resource.id}))&&e.role.data.permissions.find((function(e){return e.resource===t.resource.id})).operations.findIndex((function(e){return e===r}))>-1))}}))}})):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 })")},n.prototype.ngAfterViewInit=function(){if(this.permissionsConfig){var e=document.getElementById("permission_manager_container").offsetWidth;e<=400?(this.resourceCols=5,this.permissionCols=5):e>400&&e<=600?(this.resourceCols=6,this.permissionCols=4):e>600&&e<=800?(this.resourceCols=7,this.permissionCols=3):(this.resourceCols=8,this.permissionCols=2)}this.cd.detectChanges()},n.prototype.onPermissionChange=function(e,t,n){var o,a=this,i=new r.BehaviorSubject(null),l=this.user?this.user.data.permissions||[]:this.role&&this.role.data.permissions||[],c=l.findIndex((function(t){return t.resource===e.id}));n.checked?c>-1?-1===(o=l[c].operations.findIndex((function(e){return e===t})))&&(l[c].operations.push(t),i.next(l)):(l.push({resource:e.id,operations:[t]}),i.next(l)):c>-1&&(o=l[c].operations.findIndex((function(e){return e===t})))>-1&&(l[c].operations.length>1?l[c].operations.splice(o,1):l.splice(c,1),i.next(l));i.subscribe((function(e){if(e){if(a.user){var t=a.data.user;t.data.permissions=e;var r=new s.MatSnackBarConfig;r.duration=2e3,a.authorizatorservice.updateUserPermissions(a.data.rootFirebasePath,t).then((function(){r.panelClass=["success-bar"],a.snackbar.open("Permissions updated",null,r)})).catch((function(e){r.panelClass=["error-bar"],a.snackbar.open(e.message,null,r)}))}if(a.role){var n=a.data.role;n.data.permissions=e;var o=new s.MatSnackBarConfig;o.duration=2e3,a.authorizatorservice.updateRolePermissions(a.data.rootFirebasePath,n).then((function(){o.panelClass=["success-bar"],a.snackbar.open("Permissions updated",null,o)})).catch((function(e){console.log("ban5"),console.log(e),o.panelClass=["error-bar"],a.snackbar.open(e.message,null,o)}))}i.unsubscribe()}}))},n.ctorParameters=function(){return[{type:void 0,decorators:[{type:t.Inject,args:[U]}]},{type:t.ChangeDetectorRef},{type:void 0,decorators:[{type:t.Inject,args:[i.MAT_DIALOG_DATA]}]},{type:A},{type:s.MatSnackBar}]},D([t.Output(),P("design:type",t.EventEmitter)],n.prototype,"change",void 0),n=D([t.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}"]}),k(0,t.Inject(U)),k(2,t.Inject(i.MAT_DIALOG_DATA)),P("design:paramtypes",[Object,t.ChangeDetectorRef,Object,A,s.MatSnackBar])],n)}(),B=function(){function e(e,t,r){this.data=e,this.authorizatorservice=t,this.dialogRef=r,this.userForm=new C.FormGroup({email:new C.FormControl(null,[C.Validators.required,C.Validators.email])})}return e.prototype.onSubmitUser=function(){var e=this;if(this.userForm.valid){var t={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,t).then((function(){e.dialogRef.close(t)})).catch((function(t){"exists"===t.key?e.userForm.controls.email.setErrors({exists:!0}):e.userForm.controls.email.setErrors({defaulterror:!0})}))}},e.ctorParameters=function(){return[{type:void 0,decorators:[{type:t.Inject,args:[i.MAT_DIALOG_DATA]}]},{type:A},{type:i.MatDialogRef}]},e=D([t.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}"]}),k(0,t.Inject(i.MAT_DIALOG_DATA)),P("design:paramtypes",[Object,A,i.MatDialogRef])],e)}(),S=function(){function e(e){this.data=e}return e.prototype.ngOnInit=function(){},e.ctorParameters=function(){return[{type:void 0,decorators:[{type:t.Inject,args:[i.MAT_DIALOG_DATA]}]}]},e=D([t.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}"]}),k(0,t.Inject(i.MAT_DIALOG_DATA)),P("design:paramtypes",[Object])],e)}(),j=function(){function e(){this.dataChange=new r.BehaviorSubject([])}return Object.defineProperty(e.prototype,"data",{get:function(){return this.dataChange.value},enumerable:!0,configurable:!0}),e}(),E=function(e){function t(t){var r=e.call(this)||this;return r.usersDatabase=t,r}return w(t,e),t.prototype.connect=function(){return this.usersDatabase.dataChange},t.prototype.disconnect=function(){},t}(y.DataSource),z=function(){function e(e,t,r,n){this.authorizatorservice=e,this.dialog=t,this.snackbar=r,this.progressbarservice=n,this.displayedColumns=["remove","user","permissions"],this.usersDatabase=new j,this.users=[]}return e.prototype.ngOnInit=function(){var e=this;this.progressbarservice.showUsersWaitBar(!0),this.authorizatorservice.getUsers(this.rootFirebasePath).then((function(t){e.progressbarservice.showUsersWaitBar(!1),t&&(e.users=t.sort((function(e,t){return e.data.name>t.data.name?1:e.data.name<t.data.name?-1:0})),e.usersDataSource=new E(e.usersDatabase),e.usersDatabase.dataChange.next(t))}))},e.prototype.addUser=function(){var e=this;this.dialog.open(B,{width:"300px",data:{type:"add",user:null,rootFirebasePath:this.rootFirebasePath}}).afterClosed().subscribe((function(t){if(t){e.users.push(t),e.users=e.users.sort((function(e,t){return e.data.name>t.data.name?1:e.data.name<t.data.name?-1:0})),e.usersDatabase.dataChange.next(e.users);var r=new s.MatSnackBarConfig;r.duration=3e3,r.panelClass=["success-bar"],e.snackbar.open("User added successfully",null,r)}}))},e.prototype.removeUser=function(e){var t=this;this.dialog.open(S,{width:"300px",data:e}).afterClosed().subscribe((function(r){r&&(t.progressbarservice.showUsersWaitBar(!0),t.authorizatorservice.removeUser(t.rootFirebasePath,e.id).then((function(){t.progressbarservice.showUsersWaitBar(!1),t.users.splice(t.users.findIndex((function(t){return t.id===e.id})),1),t.usersDatabase.dataChange.next(t.users);var r=new s.MatSnackBarConfig;r.duration=3e3,r.panelClass=["success-bar"],t.snackbar.open("User removed successfully",null,r)})).catch((function(e){var r=new s.MatSnackBarConfig;r.duration=3e3,r.panelClass=["error-bar"],t.snackbar.open(e.message,null,r)})))}))},e.prototype.setPermissions=function(e){this.dialog.open(O,{width:"95%",maxWidth:"600px",data:{rootFirebasePath:this.rootFirebasePath,user:e}})},e.ctorParameters=function(){return[{type:A},{type:i.MatDialog},{type:s.MatSnackBar},{type:I}]},D([t.Input(),P("design:type",String)],e.prototype,"rootFirebasePath",void 0),e=D([t.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 \x3c!--- Note that these columns can be defined in any order.\n The actual rendered columns are set as a property on the row definition" --\x3e\n \n \x3c!-- Remove Column --\x3e\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 \x3c!-- User Column --\x3e\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 \x3c!-- Permissions Column --\x3e\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}"]}),P("design:paramtypes",[A,i.MatDialog,s.MatSnackBar,I])],e)}(),_=function(){function e(){this.dataChange=new r.BehaviorSubject([])}return Object.defineProperty(e.prototype,"data",{get:function(){return this.dataChange.value},enumerable:!0,configurable:!0}),e}(),T=function(e){function t(t){var r=e.call(this)||this;return r.usersDatabase=t,r}return w(t,e),t.prototype.connect=function(){return this.usersDatabase.dataChange},t.prototype.disconnect=function(){},t}(y.DataSource),W=function(){function e(e,t,r){this.data=e,this.authorizatorservice=t,this.dialogRef=r,this.displayedColumns=["remove","user"],this.usersDatabase=new _,this.users=[],this.roleUsers=[],this.roleForm=new C.FormGroup({name:new C.FormControl(null,[C.Validators.required]),description:new C.FormControl(null)})}return e.prototype.ngOnInit=function(){var e=this;this.usersDataSource=new T(this.usersDatabase),this.authorizatorservice.getUsers(this.data.rootFirebasePath).then((function(t){t&&(e.users=t.sort((function(e,t){return e.data.name>t.data.name?1:e.data.name<t.data.name?-1:0})),e.roleUsers=e.users.filter((function(t){return e.data&&e.data.role&&e.data.role.data.users.findIndex((function(e){return e===t.id}))>-1})),e.roleUsers&&(e.roleUsers=e.roleUsers.sort((function(e,t){return e.data.name>t.data.name?1:e.data.name<t.data.name?-1:0})),e.usersDatabase.dataChange.next(e.roleUsers)))})),this.data.role&&(this.roleForm.controls.name.setValue(this.data.role.data.name),this.roleForm.controls.description.setValue(this.data.role.data.description))},e.prototype.onAddUserToRole=function(){var e=this;-1===this.roleUsers.findIndex((function(t){return t.id===e.selectUser.value}))&&(this.roleUsers.push(this.users.find((function(t){return t.id===e.selectUser.value}))),this.roleUsers=this.roleUsers.sort((function(e,t){return e.data.name>t.data.name?1:e.data.name<t.data.name?-1:0})),this.usersDatabase.dataChange.next(this.roleUsers))},e.prototype.onRemoveUserFromRole=function(e){var t=this.roleUsers.findIndex((function(t){return t.id===e.id}));t>-1&&(this.roleUsers.splice(t,1),this.usersDatabase.dataChange.next(this.roleUsers))},e.prototype.onSubmitRole=function(){var e=this;if(this.roleForm.valid){var t={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(e){return e.id})),permissions:null}};t.id?this.authorizatorservice.updateRole(this.data.rootFirebasePath,t).then((function(){e.dialogRef.close(t)})).catch((function(t){e.roleForm.controls.name.setErrors({defaulterror:!0})})):this.authorizatorservice.addRole(this.data.rootFirebasePath,t).then((function(){e.dialogRef.close(t)})).catch((function(t){"exists"===t.key?e.roleForm.controls.name.setErrors({exists:!0}):e.roleForm.controls.name.setErrors({defaulterror:!0})}))}},e.ctorParameters=function(){return[{type:void 0,decorators:[{type:t.Inject,args:[i.MAT_DIALOG_DATA]}]},{type:A},{type:i.MatDialogRef}]},D([t.ViewChild("selectUser"),P("design:type",d.MatSelect)],e.prototype,"selectUser",void 0),e=D([t.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 \x3c!-- Remove Column --\x3e\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 \x3c!-- User Column --\x3e\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}"]}),k(0,t.Inject(i.MAT_DIALOG_DATA)),P("design:paramtypes",[Object,A,i.MatDialogRef])],e)}(),q=function(){function e(e){this.data=e}return e.prototype.ngOnInit=function(){},e.ctorParameters=function(){return[{type:void 0,decorators:[{type:t.Inject,args:[i.MAT_DIALOG_DATA]}]}]},e=D([t.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}"]}),k(0,t.Inject(i.MAT_DIALOG_DATA)),P("design:paramtypes",[Object])],e)}(),G=function(){function e(){this.dataChange=new r.BehaviorSubject([])}return Object.defineProperty(e.prototype,"data",{get:function(){return this.dataChange.value},enumerable:!0,configurable:!0}),e}(),H=function(e){function t(t){var r=e.call(this)||this;return r.rolesDatabase=t,r}return w(t,e),t.prototype.connect=function(){return this.rolesDatabase.dataChange},t.prototype.disconnect=function(){},t}(y.DataSource),L=function(){function e(e,t,r,n){this.authorizatorservice=e,this.dialog=t,this.snackbar=r,this.progressbarservice=n,this.displayedColumns=["remove","edit","role","permissions"],this.rolesDatabase=new G,this.roles=[]}return e.prototype.ngOnInit=function(){var e=this;this.progressbarservice.showRolesWaitBar(!0),this.authorizatorservice.getRoles(this.rootFirebasePath).then((function(t){t&&(e.roles=t.sort((function(e,t){return e.data.name>t.data.name?1:e.data.name<t.data.name?-1:0})),e.rolesDataSource=new H(e.rolesDatabase),e.rolesDatabase.dataChange.next(t),e.progressbarservice.showRolesWaitBar(!1))})).catch((function(e){console.error(e)})).finally((function(){e.progressbarservice.showRolesWaitBar(!1)}))},e.prototype.addRole=function(){var e=this;this.dialog.open(W,{width:"95%",maxWidth:"500px",data:{role:null,rootFirebasePath:this.rootFirebasePath}}).afterClosed().subscribe((function(t){if(t){e.roles.push(t),e.roles=e.roles.sort((function(e,t){return e.data.name>t.data.name?1:e.data.name<t.data.name?-1:0})),e.rolesDatabase.dataChange.next(e.roles);var r=new s.MatSnackBarConfig;r.duration=3e3,r.panelClass=["success-bar"],e.snackbar.open("Role added successfully",null,r)}}))},e.prototype.editRole=function(e){var t=this;this.dialog.open(W,{width:"95%",maxWidth:"500px",data:{role:e,rootFirebasePath:this.rootFirebasePath}}).afterClosed().subscribe((function(e){if(e){var r=t.roles.findIndex((function(t){return t.id===e.id}));r>-1&&(t.roles[r].data=e.data,t.rolesDatabase.dataChange.next(t.roles));var n=new s.MatSnackBarConfig;n.duration=3e3,n.panelClass=["success-bar"],t.snackbar.open("Role updated successfully",null,n)}}))},e.prototype.removeRole=function(e){var t=this;this.dialog.open(q,{width:"300px",data:e}).afterClosed().subscribe((function(r){r&&(t.progressbarservice.showRolesWaitBar(!0),t.authorizatorservice.removeRole(t.rootFirebasePath,e.id).then((function(){t.roles.splice(t.roles.findIndex((function(t){return t.id===e.id})),1),t.rolesDatabase.dataChange.next(t.roles);var r=new s.MatSnackBarConfig;r.duration=3e3,r.panelClass=["success-bar"],t.snackbar.open("Role removed successfully",null,r),t.progressbarservice.showRolesWaitBar(!1)})).catch((function(e){var r=new s.MatSnackBarConfig;r.duration=3e3,r.panelClass=["error-bar"],t.snackbar.open(e.message,null,r)})))}))},e.prototype.setPermissions=function(e){this.dialog.open(O,{width:"95%",maxWidth:"600px",data:{rootFirebasePath:this.rootFirebasePath,role:e}})},e.ctorParameters=function(){return[{type:A},{type:i.MatDialog},{type:s.MatSnackBar},{type:I}]},D([t.Input(),P("design:type",String)],e.prototype,"rootFirebasePath",void 0),e=D([t.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 \x3c!--- Note that these columns can be defined in any order.\n The actual rendered columns are set as a property on the row definition" --\x3e\n \n \x3c!-- Remove Column --\x3e\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 \x3c!-- Edit Column --\x3e\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 \x3c!-- Role Column --\x3e\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 \x3c!-- Permissions Column --\x3e\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}"]}),P("design:paramtypes",[A,i.MatDialog,s.MatSnackBar,I])],e)}(),N=function(){function e(){}var r;return r=e,e.forRoot=function(e){return{ngModule:r,providers:[{provide:U,useValue:e}]}},e=r=D([t.NgModule({declarations:[O,M,z,B,S,L,q,W],imports:[v.CommonModule,C.FormsModule,C.ReactiveFormsModule,l.MatGridListModule,c.MatSlideToggleModule,u.MatButtonToggleModule,d.MatSelectModule,m.MatIconModule,p.MatTabsModule,f.MatTableModule,h.MatButtonModule,i.MatDialogModule,g.MatInputModule,s.MatSnackBarModule,b.MatProgressBarModule],exports:[M],providers:[A,I],entryComponents:[B,S,W,q,O]})],e)}();e.AngularFirebaseAuthorizatorModule=N,e.AngularFirebaseAuthotizatorComponent=M,e.AuthGuard=F,e.AuthorizatorService=A,e.ɵa=U,e.ɵb=I,e.ɵc=O,e.ɵd=z,e.ɵe=B,e.ɵf=S,e.ɵg=L,e.ɵh=q,e.ɵi=W,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=angular-firebase-authorizator.umd.min.js.map