@verisoft/security-core 20.0.0 → 20.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.eslintrc.json +48 -0
  2. package/jest.config.ts +21 -0
  3. package/ng-package.json +7 -0
  4. package/package.json +3 -17
  5. package/project.json +36 -0
  6. package/src/index.ts +1 -0
  7. package/src/lib/directives/has-permission.directive.ts +54 -0
  8. package/src/lib/directives/has-role.directive.ts +54 -0
  9. package/src/lib/directives/index.ts +2 -0
  10. package/src/lib/guards/auth.guard.ts +55 -0
  11. package/src/lib/guards/index.ts +1 -0
  12. package/src/lib/index.ts +6 -0
  13. package/src/lib/models/authenticated-user.model.ts +8 -0
  14. package/src/lib/models/config.model.ts +9 -0
  15. package/src/lib/models/functions.spec.ts +159 -0
  16. package/src/lib/models/functions.ts +103 -0
  17. package/src/lib/models/index.ts +3 -0
  18. package/src/lib/provider.ts +52 -0
  19. package/src/lib/services/auth-context.service.ts +38 -0
  20. package/src/lib/services/index.ts +7 -0
  21. package/src/lib/services/local-storage-token-provider.ts +23 -0
  22. package/src/lib/services/local-token-provider.ts +15 -0
  23. package/src/lib/services/login.service.ts +23 -0
  24. package/src/lib/services/logout.service.ts +15 -0
  25. package/src/lib/services/security-initializer.ts +26 -0
  26. package/src/lib/services/session-token-provider.ts +15 -0
  27. package/src/lib/services/token-provider.ts +5 -0
  28. package/src/lib/state/actions.ts +7 -0
  29. package/src/lib/state/feature.ts +10 -0
  30. package/src/lib/state/index.ts +4 -0
  31. package/src/lib/state/reducers.ts +11 -0
  32. package/src/lib/state/selectors.ts +9 -0
  33. package/src/lib/state/state.ts +9 -0
  34. package/src/test-setup.ts +8 -0
  35. package/tsconfig.json +28 -0
  36. package/tsconfig.lib.json +17 -0
  37. package/tsconfig.lib.prod.json +9 -0
  38. package/tsconfig.spec.json +16 -0
  39. package/fesm2022/verisoft-security-core.mjs +0 -380
  40. package/fesm2022/verisoft-security-core.mjs.map +0 -1
  41. package/index.d.ts +0 -153
package/.eslintrc.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "extends": ["../../../../.eslintrc.base.json"],
3
+ "ignorePatterns": ["!**/*"],
4
+ "overrides": [
5
+ {
6
+ "files": ["*.ts"],
7
+ "extends": [
8
+ "plugin:@nx/angular",
9
+ "plugin:@angular-eslint/template/process-inline-templates"
10
+ ],
11
+ "rules": {
12
+ "@angular-eslint/directive-selector": [
13
+ "error",
14
+ {
15
+ "type": "attribute",
16
+ "prefix": "",
17
+ "style": "camelCase"
18
+ }
19
+ ],
20
+ "@angular-eslint/component-selector": [
21
+ "error",
22
+ {
23
+ "type": "element",
24
+ "prefix": "v-sec",
25
+ "style": "kebab-case"
26
+ }
27
+ ]
28
+ }
29
+ },
30
+ {
31
+ "files": ["*.html"],
32
+ "extends": ["plugin:@nx/angular-template"],
33
+ "rules": {}
34
+ },
35
+ {
36
+ "files": ["*.json"],
37
+ "parser": "jsonc-eslint-parser",
38
+ "rules": {
39
+ "@nx/dependency-checks": [
40
+ "error",
41
+ {
42
+ "ignoredFiles": ["{projectRoot}/eslint.config.{js,cjs,mjs}"]
43
+ }
44
+ ]
45
+ }
46
+ }
47
+ ]
48
+ }
package/jest.config.ts ADDED
@@ -0,0 +1,21 @@
1
+ export default {
2
+ displayName: 'security-core',
3
+ preset: '../../../../jest.preset.js',
4
+ setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
5
+ coverageDirectory: '../../../../coverage/src/libs/security/core',
6
+ transform: {
7
+ '^.+\\.(ts|mjs|js|html)$': [
8
+ 'jest-preset-angular',
9
+ {
10
+ tsconfig: '<rootDir>/tsconfig.spec.json',
11
+ stringifyContentPathRegex: '\\.(html|svg)$',
12
+ },
13
+ ],
14
+ },
15
+ transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
16
+ snapshotSerializers: [
17
+ 'jest-preset-angular/build/serializers/no-ng-attributes',
18
+ 'jest-preset-angular/build/serializers/ng-snapshot',
19
+ 'jest-preset-angular/build/serializers/html-comment',
20
+ ],
21
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "$schema": "../../../../node_modules/ng-packagr/ng-package.schema.json",
3
+ "dest": "../../../../dist/src/libs/security/core",
4
+ "lib": {
5
+ "entryFile": "src/index.ts"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,25 +1,11 @@
1
1
  {
2
2
  "name": "@verisoft/security-core",
3
- "version": "20.0.0",
3
+ "version": "20.1.0",
4
4
  "peerDependencies": {
5
5
  "@angular/core": "~20.2.0",
6
6
  "@angular/router": "~20.2.0",
7
7
  "@ngrx/store": "~20.0.0",
8
8
  "rxjs": "~7.8.0"
9
9
  },
10
- "sideEffects": false,
11
- "module": "fesm2022/verisoft-security-core.mjs",
12
- "typings": "index.d.ts",
13
- "exports": {
14
- "./package.json": {
15
- "default": "./package.json"
16
- },
17
- ".": {
18
- "types": "./index.d.ts",
19
- "default": "./fesm2022/verisoft-security-core.mjs"
20
- }
21
- },
22
- "dependencies": {
23
- "tslib": "^2.3.0"
24
- }
25
- }
10
+ "sideEffects": false
11
+ }
package/project.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "security-core",
3
+ "$schema": "../../../../node_modules/nx/schemas/project-schema.json",
4
+ "sourceRoot": "src/libs/security/core/src",
5
+ "prefix": "lib",
6
+ "projectType": "library",
7
+ "tags": [],
8
+ "targets": {
9
+ "build": {
10
+ "executor": "@nx/angular:package",
11
+ "outputs": ["{workspaceRoot}/dist/src/libs/security/core"],
12
+ "options": {
13
+ "project": "src/libs/security/core/ng-package.json"
14
+ },
15
+ "configurations": {
16
+ "production": {
17
+ "tsConfig": "src/libs/security/core/tsconfig.lib.prod.json"
18
+ },
19
+ "development": {
20
+ "tsConfig": "src/libs/security/core/tsconfig.lib.json"
21
+ }
22
+ },
23
+ "defaultConfiguration": "production"
24
+ },
25
+ "test": {
26
+ "executor": "@nx/jest:jest",
27
+ "outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
28
+ "options": {
29
+ "jestConfig": "src/libs/security/core/jest.config.ts"
30
+ }
31
+ },
32
+ "lint": {
33
+ "executor": "@nx/eslint:lint"
34
+ }
35
+ }
36
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './lib';
@@ -0,0 +1,54 @@
1
+ import {
2
+ Directive,
3
+ Input,
4
+ TemplateRef,
5
+ ViewContainerRef,
6
+ OnDestroy,
7
+ } from '@angular/core';
8
+ import { distinctUntilChanged, Subscription } from 'rxjs';
9
+ import { AuthContextService } from '../services';
10
+
11
+ @Directive({
12
+ standalone: true,
13
+ selector: '[hasPermission]',
14
+ })
15
+ export class HasPermissionDirective<T> implements OnDestroy {
16
+ private requiredPermissions: string | string[] = '';
17
+ private sub?: Subscription;
18
+
19
+ constructor(
20
+ private templateRef: TemplateRef<T>,
21
+ private viewContainer: ViewContainerRef,
22
+ private authContext: AuthContextService
23
+ ) {}
24
+
25
+ @Input()
26
+ set hasPermission(value: string | string[]) {
27
+ this.requiredPermissions = value;
28
+ this.updateView();
29
+ }
30
+
31
+ ngOnDestroy(): void {
32
+ this.unregister();
33
+ }
34
+
35
+ private unregister() {
36
+ this.sub?.unsubscribe();
37
+ }
38
+
39
+ private updateView(): void {
40
+ this.unregister();
41
+ if (this.requiredPermissions || this.requiredPermissions.length) {
42
+ this.sub = this.authContext
43
+ .hasRequiredPermission(this.requiredPermissions)
44
+ .pipe(distinctUntilChanged())
45
+ .subscribe((hasPerm) => {
46
+ if (hasPerm) {
47
+ this.viewContainer.createEmbeddedView(this.templateRef);
48
+ } else {
49
+ this.viewContainer.clear();
50
+ }
51
+ });
52
+ }
53
+ }
54
+ }
@@ -0,0 +1,54 @@
1
+ import {
2
+ Directive,
3
+ Input,
4
+ TemplateRef,
5
+ ViewContainerRef,
6
+ OnDestroy,
7
+ } from '@angular/core';
8
+ import { distinctUntilChanged, Subscription } from 'rxjs';
9
+ import { AuthContextService } from '../services';
10
+
11
+ @Directive({
12
+ standalone: true,
13
+ selector: '[hasRole]',
14
+ })
15
+ export class HasRoleDirective<T> implements OnDestroy {
16
+ private requiredRoles: string | string[] | undefined;
17
+ private sub?: Subscription;
18
+
19
+ constructor(
20
+ private templateRef: TemplateRef<T>,
21
+ private viewContainer: ViewContainerRef,
22
+ private authContext: AuthContextService
23
+ ) {}
24
+
25
+ @Input()
26
+ set hasRole(value: string | string[]) {
27
+ this.requiredRoles = value;
28
+ this.updateView();
29
+ }
30
+
31
+ ngOnDestroy(): void {
32
+ this.unregister();
33
+ }
34
+
35
+ private unregister() {
36
+ this.sub?.unsubscribe();
37
+ }
38
+
39
+ private updateView(): void {
40
+ this.unregister();
41
+ if (this.requiredRoles || this.requiredRoles?.length) {
42
+ this.sub = this.authContext
43
+ .hasRequiredRole(this.requiredRoles)
44
+ .pipe(distinctUntilChanged())
45
+ .subscribe((hasRole) => {
46
+ if (hasRole) {
47
+ this.viewContainer.createEmbeddedView(this.templateRef);
48
+ } else {
49
+ this.viewContainer.clear();
50
+ }
51
+ });
52
+ }
53
+ }
54
+ }
@@ -0,0 +1,2 @@
1
+ export * from './has-permission.directive';
2
+ export * from './has-role.directive';
@@ -0,0 +1,55 @@
1
+ import { inject, Injectable } from '@angular/core';
2
+ import {
3
+ ActivatedRouteSnapshot,
4
+ CanActivate,
5
+ CanActivateChild,
6
+ Router,
7
+ UrlTree,
8
+ } from '@angular/router';
9
+ import { map, Observable, of, switchMap } from 'rxjs';
10
+ import { SecurityConfig } from '../models';
11
+ import { hasRequiredPermission } from '../models/functions';
12
+ import { SECURITY_CONFIG } from '../provider';
13
+ import { AuthContextService } from '../services';
14
+
15
+ @Injectable({
16
+ providedIn: 'root',
17
+ })
18
+ export class AuthGuard implements CanActivate, CanActivateChild {
19
+ private config = inject<SecurityConfig>(SECURITY_CONFIG);
20
+ private router = inject(Router);
21
+ private authContext = inject(AuthContextService);
22
+
23
+ canActivate(route: ActivatedRouteSnapshot): Observable<boolean | UrlTree> {
24
+ return this.checkPermissionsAndRolesAndNavigate(route, this.config.notAuthorizedPage);
25
+ }
26
+
27
+ canActivateChild(
28
+ childRoute: ActivatedRouteSnapshot
29
+ ): Observable<boolean | UrlTree> {
30
+ return this.checkPermissionsAndRolesAndNavigate(childRoute, this.config.notAuthorizedPage);
31
+ }
32
+
33
+ private checkPermissionsAndRolesAndNavigate(
34
+ route: ActivatedRouteSnapshot,
35
+ notAuthorizedUrl: string | undefined
36
+ ): Observable<boolean | UrlTree> {
37
+ const requiredPermissions = route.data['permissions'] as | string | string[] | undefined;
38
+ const requiredRoles = route.data['roles'] as string | string[] | undefined;
39
+
40
+ return this.authContext.user$.pipe(
41
+ map(
42
+ (user) => user &&
43
+ (!requiredPermissions ||
44
+ hasRequiredPermission(user, requiredPermissions)) &&
45
+ (!requiredRoles || hasRequiredPermission(user, requiredRoles))
46
+ ),
47
+ switchMap((hasPermission) => {
48
+ if (!hasPermission && notAuthorizedUrl) {
49
+ return of(this.router.parseUrl(notAuthorizedUrl));
50
+ }
51
+ return of(!!hasPermission);
52
+ })
53
+ );
54
+ }
55
+ }
@@ -0,0 +1 @@
1
+ export * from './auth.guard';
@@ -0,0 +1,6 @@
1
+ export * from './directives';
2
+ export * from './guards';
3
+ export * from './models';
4
+ export * from './services';
5
+ export * from './state';
6
+ export * from './provider';
@@ -0,0 +1,8 @@
1
+ export interface AuthenticatedUser {
2
+ userId?: string;
3
+ userName: string;
4
+ email: string;
5
+ displayName?: string;
6
+ roles: string[] | undefined;
7
+ permissions: string[] | undefined;
8
+ }
@@ -0,0 +1,9 @@
1
+
2
+ export interface SecurityConfig {
3
+ tokenStorageKey: string;
4
+ contextTokenStorageKey?: string;
5
+ loginPage?: string;
6
+ logoutPage?: string;
7
+ notAuthorizedPage?: string;
8
+ sendTokenHeader?: boolean;
9
+ }
@@ -0,0 +1,159 @@
1
+ import { AuthenticatedUser } from './authenticated-user.model';
2
+ import {
3
+ convertJWTToUser,
4
+ hasRequiredPermission,
5
+ hasRequiredRole,
6
+ } from './functions';
7
+
8
+ describe('Permissions Utils', () => {
9
+ let user: AuthenticatedUser;
10
+
11
+ beforeEach(() => {
12
+ user = {
13
+ userName: 'testUser',
14
+ email: 'test@email.cz',
15
+ displayName: 'Test User',
16
+ permissions: ['READ', 'WRITE', 'DELETE_USER'],
17
+ roles: ['ADMIN', 'USER'],
18
+ };
19
+ });
20
+
21
+ describe('hasRequiredPermission', () => {
22
+ it('should return false if user is undefined', () => {
23
+ expect(hasRequiredPermission(undefined, 'READ')).toBe(false);
24
+ });
25
+
26
+ it('should return false if user.permissions is undefined', () => {
27
+ const noPermissionsUser: AuthenticatedUser = {
28
+ ...user,
29
+ permissions: undefined,
30
+ };
31
+ expect(hasRequiredPermission(noPermissionsUser, 'READ')).toBe(false);
32
+ });
33
+
34
+ it('should return true for a single permission the user has', () => {
35
+ expect(hasRequiredPermission(user, 'READ')).toBe(true);
36
+ });
37
+
38
+ it('should return false for a single permission the user does not have', () => {
39
+ expect(hasRequiredPermission(user, 'UNKNOWN')).toBe(false);
40
+ });
41
+
42
+ it('should return true for comma-delimited permissions if user has ALL', () => {
43
+ expect(hasRequiredPermission(user, 'READ,WRITE')).toBe(true);
44
+ });
45
+
46
+ it('should return false for comma-delimited permissions if missing one', () => {
47
+ expect(hasRequiredPermission(user, 'READ,UPDATE_USER')).toBe(false);
48
+ });
49
+
50
+ it('should return true if user has ANY of the permissions in the array', () => {
51
+ expect(hasRequiredPermission(user, ['READ', 'UPDATE_USER'])).toBe(true);
52
+ });
53
+
54
+ it('should return false if user does not have ANY of the permissions in the array', () => {
55
+ expect(hasRequiredPermission(user, ['UPDATE_USER', 'CREATE_POST'])).toBe(
56
+ false
57
+ );
58
+ });
59
+ });
60
+
61
+ describe('hasRequiredRole', () => {
62
+ it('should return false if user is undefined', () => {
63
+ expect(hasRequiredRole(undefined, 'ADMIN')).toBe(false);
64
+ });
65
+
66
+ it('should return false if user.roles is undefined', () => {
67
+ const noRolesUser: AuthenticatedUser = { ...user, roles: undefined };
68
+ expect(hasRequiredRole(noRolesUser, 'ADMIN')).toBe(false);
69
+ });
70
+
71
+ it('should return true for a single role the user has', () => {
72
+ expect(hasRequiredRole(user, 'ADMIN')).toBe(true);
73
+ });
74
+
75
+ it('should return false for a single role the user does not have', () => {
76
+ expect(hasRequiredRole(user, 'MANAGER')).toBe(false);
77
+ });
78
+
79
+ it('should return true for comma-delimited roles if user has ALL', () => {
80
+ // user has 'ADMIN' and 'USER'
81
+ expect(hasRequiredRole(user, 'ADMIN,USER')).toBe(true);
82
+ });
83
+
84
+ it('should return false for comma-delimited roles if missing one', () => {
85
+ // user has 'ADMIN' and 'USER' but not 'MANAGER'
86
+ expect(hasRequiredRole(user, 'ADMIN,MANAGER')).toBe(false);
87
+ });
88
+
89
+ it('should return true if user has ANY of the roles in the array', () => {
90
+ expect(hasRequiredRole(user, ['USER', 'MANAGER'])).toBe(true);
91
+ });
92
+
93
+ it('should return false if user does not have ANY of the roles in the array', () => {
94
+ expect(hasRequiredRole(user, ['GUEST', 'MANAGER'])).toBe(false);
95
+ });
96
+ });
97
+
98
+ describe('convertJWTToUser', () => {
99
+ it('should return undefined if base64Token is undefined', () => {
100
+ expect(convertJWTToUser(undefined)).toBeUndefined();
101
+ });
102
+
103
+ it('should return undefined if base64Token is invalid', () => {
104
+ expect(convertJWTToUser('invalid.token')).toBeUndefined();
105
+ });
106
+
107
+ it('should return undefined if payload does not contain userName', () => {
108
+ const token =
109
+ btoa('header') + '.' + btoa(JSON.stringify({})) + '.signature';
110
+ expect(convertJWTToUser(token)).toBeUndefined();
111
+ });
112
+
113
+ it('should return a user object if payload contains userName', () => {
114
+ const payload = {
115
+ sub: 'testUser',
116
+ email: 'test@example.com',
117
+ name: 'Test User',
118
+ role: 'ADMIN',
119
+ permission: 'READ',
120
+ };
121
+ const token =
122
+ btoa('header') + '.' + btoa(JSON.stringify(payload)) + '.signature';
123
+ const user = convertJWTToUser(token);
124
+ expect(user).toEqual({
125
+ userName: 'testUser',
126
+ email: 'test@example.com',
127
+ displayName: 'Test User',
128
+ roles: ['ADMIN'],
129
+ permissions: ['READ'],
130
+ });
131
+ });
132
+
133
+ it('should return a user object if payload contains nameid', () => {
134
+ const payload = {
135
+ nameid: 'testUser',
136
+ email: 'test@example.com',
137
+ name: 'Test User',
138
+ role: 'ADMIN',
139
+ permission: 'READ',
140
+ };
141
+ const token =
142
+ btoa('header') + '.' + btoa(JSON.stringify(payload)) + '.signature';
143
+ const user = convertJWTToUser(token);
144
+ expect(user).toEqual({
145
+ userName: 'testUser',
146
+ email: 'test@example.com',
147
+ displayName: 'Test User',
148
+ roles: ['ADMIN'],
149
+ permissions: ['READ'],
150
+ });
151
+ });
152
+
153
+ it('should return undefined if an error occurs during parsing', () => {
154
+ const token =
155
+ btoa('header') + '.' + btoa('invalidPayload') + '.signature';
156
+ expect(convertJWTToUser(token)).toBeUndefined();
157
+ });
158
+ });
159
+ });
@@ -0,0 +1,103 @@
1
+ import { AuthenticatedUser } from './authenticated-user.model';
2
+
3
+ export function hasRequiredPermission(
4
+ user: AuthenticatedUser | undefined,
5
+ permission: string | string[]
6
+ ): boolean {
7
+ return hasItems(user?.permissions, permission);
8
+ }
9
+
10
+ export function hasRequiredRole(
11
+ user: AuthenticatedUser | undefined,
12
+ role: string | string[]
13
+ ): boolean {
14
+ return hasItems(user?.roles, role);
15
+ }
16
+
17
+ function hasItems(
18
+ userItems: string[] | undefined,
19
+ neededItems: string | string[]
20
+ ): boolean {
21
+ if (!neededItems || !neededItems.length) {
22
+ return true;
23
+ }
24
+
25
+ if (!userItems || !userItems.length) {
26
+ return false;
27
+ }
28
+
29
+ const userItemsSet = new Set(userItems);
30
+ if (Array.isArray(neededItems)) {
31
+ return neededItems.some((item) => hasItems(userItems, item));
32
+ }
33
+
34
+ if (neededItems.includes(',')) {
35
+ const splitItems = neededItems.split(',').map((i) => i.trim());
36
+ return splitItems.every((i) => userItemsSet.has(i));
37
+ }
38
+
39
+ return userItemsSet.has(neededItems);
40
+ }
41
+
42
+ export function convertJWTToUser(
43
+ base64Token?: string
44
+ ): AuthenticatedUser | undefined {
45
+ if (!base64Token) {
46
+ return undefined;
47
+ }
48
+
49
+ try {
50
+ const parts = base64Token.split('.');
51
+ if (parts.length < 2) {
52
+ return undefined;
53
+ }
54
+ const payload = decodeJwtPayload(parts[1]);
55
+
56
+ const userName = payload['unique_name'] ?? payload['nameid'];
57
+ if (!userName) {
58
+ return undefined;
59
+ }
60
+
61
+ const user: AuthenticatedUser = {
62
+ userName,
63
+ userId: payload['nameid'],
64
+ email: payload['email'],
65
+ displayName: payload['name'],
66
+ roles: convertToArray(payload, 'role'),
67
+ permissions: convertToArray(payload, 'permission'),
68
+ };
69
+
70
+ return user;
71
+ } catch (error) {
72
+ return undefined;
73
+ }
74
+ }
75
+
76
+ export function decodeJwtPayload(jwt: string): any {
77
+ const base64 = jwt.replace(/-/g, '+').replace(/_/g, '/');
78
+
79
+ const jsonPayload = decodeURIComponent(
80
+ atob(base64)
81
+ .split('')
82
+ .map(c => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'))
83
+ .join('')
84
+ );
85
+
86
+ return JSON.parse(jsonPayload);
87
+ }
88
+
89
+ function convertToArray(
90
+ item: { [key: string]: string | string[] },
91
+ propertyName: string
92
+ ): string[] | undefined {
93
+ const rawValue = item[propertyName];
94
+ if (!rawValue) {
95
+ return undefined;
96
+ }
97
+
98
+ if (Array.isArray(rawValue)) {
99
+ return rawValue;
100
+ }
101
+
102
+ return [rawValue];
103
+ }
@@ -0,0 +1,3 @@
1
+ export * from './authenticated-user.model';
2
+ export * from './functions';
3
+ export * from './config.model';
@@ -0,0 +1,52 @@
1
+ import { EnvironmentProviders, InjectionToken, ModuleWithProviders, NgModule, Provider, inject, provideAppInitializer } from '@angular/core';
2
+ import { Router } from '@angular/router';
3
+ import { StoreModule } from '@ngrx/store';
4
+ import { AuthGuard } from './guards';
5
+ import { SecurityConfig } from './models';
6
+ import {
7
+ AuthContextService,
8
+ LocalStorageTokenProvider,
9
+ securityInitializerFactory,
10
+ TokenProvider,
11
+ } from './services';
12
+ import { SecurityFeature } from './state/feature';
13
+
14
+ export function provideSecurity(
15
+ config: Partial<SecurityConfig> | undefined = undefined
16
+ ): (Provider | EnvironmentProviders)[] {
17
+ const securityConfig: SecurityConfig = {
18
+ tokenStorageKey: 'APP_TOKEN',
19
+ notAuthorizedPage: '/not-authorized',
20
+ ...(config ?? {}),
21
+ };
22
+ return [
23
+ AuthGuard,
24
+ SECURITY_INITIALIZER_PROVIDER,
25
+ { provide: SECURITY_CONTEXT_TOKEN_PROVIDER, useClass: LocalStorageTokenProvider },
26
+ { provide: SECURITY_CONFIG, useValue: securityConfig },
27
+ ];
28
+ }
29
+
30
+ @NgModule({
31
+ imports: [StoreModule.forFeature(SecurityFeature)],
32
+ })
33
+ export class SecurityModule {
34
+ static forRoot(
35
+ config?: Partial<SecurityConfig>
36
+ ): ModuleWithProviders<SecurityModule> {
37
+ return {
38
+ ngModule: SecurityModule,
39
+ providers: [...provideSecurity(config)],
40
+ };
41
+ }
42
+ }
43
+
44
+ export const SECURITY_CONTEXT_TOKEN_PROVIDER = new InjectionToken('SECURITY_CONTEXT_TOKEN_PROVIDER');
45
+
46
+ export const SECURITY_CONFIG = new InjectionToken('SECURITY_CONFIG');
47
+
48
+
49
+ export const SECURITY_INITIALIZER_PROVIDER: EnvironmentProviders = provideAppInitializer(() => {
50
+ const initializerFn = (securityInitializerFactory)(inject<TokenProvider>(SECURITY_CONTEXT_TOKEN_PROVIDER), inject(AuthContextService), inject<SecurityConfig>(SECURITY_CONFIG), inject(Router));
51
+ return initializerFn();
52
+ });