mesauth-angular 1.2.0 → 1.2.1

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.
package/package.json CHANGED
@@ -1,40 +1,39 @@
1
- {
2
- "name": "mesauth-angular",
3
- "version": "1.2.0",
4
- "description": "Angular helper library to connect to a backend API and SignalR hub to surface the current logged-in user and incoming notifications with dark/light theme support",
5
- "scripts": {
6
- "build": "ng-packagr -p ng-package.json",
7
- "prepare": "npm run build"
8
- },
9
- "keywords": [
10
- "angular",
11
- "signalr",
12
- "notifications",
13
- "auth",
14
- "mes"
15
- ],
16
- "license": "MIT",
17
- "peerDependencies": {
18
- "@angular/common": "^20.0.0",
19
- "@angular/core": "^20.0.0",
20
- "@angular/router": "^20.0.0",
21
- "rxjs": "^7"
22
- },
23
- "dependencies": {
24
- "@microsoft/signalr": "^7.0.0",
25
- "rxjs": "^7"
26
- },
27
- "devDependencies": {
28
- "@angular/common": "^20.0.0",
29
- "@angular/compiler": "^20.0.0",
30
- "@angular/compiler-cli": "^20.0.0",
31
- "@angular/core": "^20.0.0",
32
- "@angular/router": "^20.0.0",
33
- "ng-packagr": "^20.3.2",
34
- "tslib": "^2.0.0",
35
- "typescript": "~5.8.0"
36
- },
37
- "angularCompilerOptions": {
38
- "enableIvy": true
39
- }
40
- }
1
+ {
2
+ "name": "mesauth-angular",
3
+ "version": "1.2.1",
4
+ "description": "Angular helper library to connect to a backend API and SignalR hub to surface the current logged-in user and incoming notifications with dark/light theme support",
5
+ "keywords": [
6
+ "angular",
7
+ "signalr",
8
+ "notifications",
9
+ "auth",
10
+ "mes"
11
+ ],
12
+ "license": "MIT",
13
+ "peerDependencies": {
14
+ "@angular/common": "^20.0.0",
15
+ "@angular/core": "^20.0.0",
16
+ "@angular/router": "^20.0.0",
17
+ "rxjs": "^7"
18
+ },
19
+ "dependencies": {
20
+ "@microsoft/signalr": "^7.0.0",
21
+ "rxjs": "^7",
22
+ "tslib": "^2.3.0"
23
+ },
24
+ "angularCompilerOptions": {
25
+ "enableIvy": true
26
+ },
27
+ "module": "fesm2022/mesauth-angular.mjs",
28
+ "typings": "index.d.ts",
29
+ "exports": {
30
+ "./package.json": {
31
+ "default": "./package.json"
32
+ },
33
+ ".": {
34
+ "types": "./index.d.ts",
35
+ "default": "./fesm2022/mesauth-angular.mjs"
36
+ }
37
+ },
38
+ "sideEffects": false
39
+ }
package/dist/README.md DELETED
@@ -1,297 +0,0 @@
1
- # mesauth-angular
2
-
3
- Angular helper library to connect to a backend API and SignalR hub to surface the current logged-in user and incoming notifications with dark/light theme support.
4
-
5
- ## Changelog
6
-
7
- ### v1.2.0 (2026-02-05) - **Notification & Auth Interceptor Fix**
8
- - **Removed route-change user polling**: `MesAuthService` no longer re-fetches the user on every `NavigationEnd` event. User is fetched once on app init; SignalR handles real-time updates. This eliminates redundant API calls and notification toast spam on every route change.
9
- - **Removed `fetchInitialNotifications()`**: Historical notifications were being emitted through `notifications$` Subject on every user refresh, causing toast popups for old notifications. The `notifications$` observable now only carries truly new real-time events from SignalR.
10
- - **`refreshUser()` returns `Observable`**: Callers can now subscribe and wait for user data to load before proceeding (e.g., navigate after login). Previously returned `void`.
11
- - **Fixed 401 redirect for expired sessions**: Removed the `!isAuthenticated` guard from the interceptor's 401 condition. When a session expires, the `BehaviorSubject` still holds stale user data, so this check was blocking the redirect to login. The `!isMeAuthPage`, `!isLoginPage`, and `!isAuthPage` guards are sufficient to prevent redirect loops.
12
-
13
- ### v1.1.0 (2026-01-21) - **Major Update**
14
- - 🚀 **New `provideMesAuth()` Function**: Simplified setup with a single function call
15
- - ✨ **Functional Interceptor**: New `mesAuthInterceptor` for better compatibility with standalone apps
16
- - 📦 **Automatic Initialization**: `provideMesAuth()` handles service initialization via `APP_INITIALIZER`
17
- - 🔧 **Simplified API**: Just pass `apiBaseUrl` and `userBaseUrl` - no manual DI required
18
-
19
- ### v1.0.1 (2026-01-21)
20
- - 🔧 Internal refactoring for better module compatibility
21
-
22
- ### v0.2.28 (2026-01-19)
23
- - ✨ **Enhanced Avatar Support**: Direct `avatarPath` usage from user data for instant display without backend calls
24
- - 🔄 **Improved Avatar Refresh**: Timestamp-based cache busting prevents request cancellation issues
25
- - 🎯 **Better Change Detection**: Signal-based user updates with `ChangeDetectorRef` for reliable UI updates
26
-
27
- ### v0.2.27 (2026-01-19)
28
- - 🐛 Fixed avatar refresh issues in header components
29
- - 📦 Improved build process and dependencies
30
-
31
- ## Features
32
-
33
- - 🔐 **Authentication**: User login/logout with API integration
34
- - 🔔 **Real-time Notifications**: SignalR integration for live notifications
35
- - 🎨 **Dark/Light Theme**: Automatic theme detection and support
36
- - 🖼️ **Avatar Support**: Direct API-based avatar loading
37
- - 🍞 **Toast Notifications**: In-app notification toasts
38
- - 🛡️ **HTTP Interceptor**: Automatic 401/403 error handling with redirects
39
-
40
- ## Quick Start (v1.1.0+)
41
-
42
- ### 1. Install
43
-
44
- ```bash
45
- npm install mesauth-angular
46
- ```
47
-
48
- ### 2. Configure in app.config.ts (Recommended for Angular 14+)
49
-
50
- ```ts
51
- import { ApplicationConfig } from '@angular/core';
52
- import { provideHttpClient, withInterceptors } from '@angular/common/http';
53
- import { provideMesAuth, mesAuthInterceptor } from 'mesauth-angular';
54
-
55
- export const appConfig: ApplicationConfig = {
56
- providers: [
57
- provideHttpClient(
58
- withInterceptors([mesAuthInterceptor]) // Handles 401/403 redirects
59
- ),
60
- provideMesAuth({
61
- apiBaseUrl: 'https://mes.kefico.vn/auth',
62
- userBaseUrl: 'https://mes.kefico.vn/x' // For login/403 redirects
63
- })
64
- ]
65
- };
66
- ```
67
-
68
- That's it! The library handles:
69
- - Service initialization via `APP_INITIALIZER`
70
- - `HttpClient` and `Router` injection automatically
71
- - 401 → redirects to `{userBaseUrl}/login?returnUrl=...`
72
- - 403 → redirects to `{userBaseUrl}/403?returnUrl=...`
73
-
74
- ### 3. Use in Components
75
-
76
- ```ts
77
- import { MesAuthService } from 'mesauth-angular';
78
-
79
- @Component({...})
80
- export class MyComponent {
81
- private auth = inject(MesAuthService);
82
-
83
- // Observable streams
84
- currentUser$ = this.auth.currentUser$;
85
- notifications$ = this.auth.notifications$;
86
-
87
- logout() {
88
- this.auth.logout().subscribe();
89
- }
90
- }
91
- ```
92
-
93
- ## Configuration Options
94
-
95
- ```ts
96
- interface MesAuthConfig {
97
- apiBaseUrl: string; // Required: MesAuth API base URL
98
- userBaseUrl?: string; // Optional: Base URL for login/403 redirects
99
- withCredentials?: boolean; // Optional: Send cookies (default: true)
100
- }
101
- ```
102
-
103
- ## Theme Support
104
-
105
- The library automatically detects and adapts to your application's theme:
106
-
107
- ### Automatic Theme Detection
108
- The library checks for theme indicators on the `<html>` element:
109
- - `class="dark"`
110
- - `data-theme="dark"`
111
- - `theme="dark"`
112
- - `data-coreui-theme="dark"`
113
-
114
- ### Dynamic Theme Changes
115
- Theme changes are detected in real-time using `MutationObserver`, so components automatically update when your app switches themes.
116
-
117
- ### Manual Theme Control
118
- ```ts
119
- import { ThemeService } from 'mesauth-angular';
120
-
121
- // Check current theme
122
- const currentTheme = themeService.currentTheme; // 'light' | 'dark'
123
-
124
- // Manually set theme
125
- themeService.setTheme('dark');
126
-
127
- // Listen for theme changes
128
- themeService.currentTheme$.subscribe(theme => {
129
- console.log('Theme changed to:', theme);
130
- });
131
- ```
132
-
133
- ## Avatar Loading
134
-
135
- Avatars are loaded efficiently using multiple strategies:
136
-
137
- ### Primary Method: Direct Path Usage
138
- If the user object contains an `avatarPath`, it's used directly:
139
- - **Full URLs**: Used as-is (e.g., `https://example.com/avatar.jpg`)
140
- - **Relative Paths**: Combined with API base URL (e.g., `/uploads/avatar.jpg` → `{apiBaseUrl}/uploads/avatar.jpg`)
141
-
142
- ### Fallback Method: API Endpoint
143
- If no `avatarPath` is available, avatars are loaded via API:
144
- - **API Endpoint**: `GET {apiBaseUrl}/auth/{userId}/avatar`
145
- - **Authentication**: Uses the same credentials as other API calls
146
-
147
- ### Cache Busting
148
- Avatar URLs include timestamps to prevent browser caching issues during updates:
149
- - Automatic refresh when user data changes
150
- - Manual refresh triggers for upload/delete operations
151
-
152
- ### Fallback Service
153
- - **UI Avatars**: Generates initials-based avatars if no user data available
154
- - **Authentication**: Not required for fallback avatars
155
-
156
- ## Components
157
-
158
- **Note:** All components are standalone and can be imported directly.
159
-
160
- ### ma-user-profile
161
-
162
- A reusable Angular component for displaying the current user's profile information, with options for navigation and logout.
163
-
164
- - **Description**: Renders user details (e.g., name, avatar) fetched via the MesAuthService. Supports custom event handlers for navigation and logout actions.
165
- - **Inputs**: None (data is sourced from the MesAuthService).
166
- - **Outputs**:
167
- - `onNavigate`: Emits an event when the user triggers navigation (e.g., to a profile page). Pass a handler to define behavior.
168
- - `onLogout`: Emits an event when the user logs out. Pass a handler to perform logout logic (e.g., clear tokens, redirect).
169
- - **Usage Example**:
170
-
171
- ```html
172
- <ma-user-profile
173
- (onNavigate)="handleNavigation($event)"
174
- (onLogout)="handleLogout()">
175
- </ma-user-profile>
176
- ```
177
-
178
- In your component's TypeScript file:
179
-
180
- ```ts
181
- handleNavigation(event: any) {
182
- // Navigate to user profile page
183
- this.router.navigate(['/profile']);
184
- }
185
-
186
- handleLogout() {
187
- // Perform logout, e.g., clear session and redirect
188
- this.mesAuth.logout(); // Assuming a logout method exists
189
- this.router.navigate(['/login']);
190
- }
191
- ```
192
-
193
- ### ma-notification-panel
194
-
195
- A standalone component for displaying a slide-out notification panel with real-time updates.
196
-
197
- - **Description**: Shows a list of notifications, allows marking as read/delete, and integrates with toast notifications for new alerts.
198
- - **Inputs**: None.
199
- - **Outputs**: None (uses internal methods for actions).
200
- - **Usage Example**:
201
-
202
- ```html
203
- <ma-notification-panel #notificationPanel></ma-notification-panel>
204
- ```
205
-
206
- In your component:
207
-
208
- ```ts
209
- // To open the panel
210
- notificationPanel.open();
211
- ```
212
-
213
- ## Migration Guide
214
-
215
- ### Upgrading from v0.x to v1.1.0+
216
-
217
- The setup has been greatly simplified. Here's how to migrate:
218
-
219
- **Before (v0.x):**
220
- ```ts
221
- // app.config.ts - OLD WAY
222
- import { MesAuthModule, MesAuthService } from 'mesauth-angular';
223
- import { HTTP_INTERCEPTORS } from '@angular/common/http';
224
-
225
- export const appConfig: ApplicationConfig = {
226
- providers: [
227
- importProvidersFrom(MesAuthModule),
228
- { provide: HTTP_INTERCEPTORS, useClass: MesAuthInterceptor, multi: true }
229
- ]
230
- };
231
-
232
- // app.component.ts - OLD WAY
233
- export class AppComponent {
234
- constructor() {
235
- this.mesAuthService.init({
236
- apiBaseUrl: '...',
237
- userBaseUrl: '...'
238
- }, inject(HttpClient), inject(Router));
239
- }
240
- }
241
- ```
242
-
243
- **After (v1.1.0+):**
244
- ```ts
245
- // app.config.ts - NEW WAY (everything in one place!)
246
- import { provideMesAuth, mesAuthInterceptor } from 'mesauth-angular';
247
-
248
- export const appConfig: ApplicationConfig = {
249
- providers: [
250
- provideHttpClient(withInterceptors([mesAuthInterceptor])),
251
- provideMesAuth({
252
- apiBaseUrl: 'https://mes.kefico.vn/auth',
253
- userBaseUrl: 'https://mes.kefico.vn/x'
254
- })
255
- ]
256
- };
257
-
258
- // app.component.ts - No init() needed!
259
- export class AppComponent {
260
- // Just inject and use - no manual initialization required
261
- }
262
- ```
263
-
264
- **Key Changes:**
265
- - `provideMesAuth()` replaces `MesAuthModule` + manual `init()` call
266
- - `mesAuthInterceptor` (functional) replaces `MesAuthInterceptor` (class-based)
267
- - No need to inject `HttpClient` or `Router` manually
268
- - Configuration moved from `AppComponent` to `app.config.ts`
269
-
270
- ## Troubleshooting
271
-
272
- ### JIT Compiler Error in Production or AOT Mode
273
- If you encounter an error like "The injectable 'MesAuthService' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available," this typically occurs because:
274
- - The package is being imported directly from source code (e.g., during development) without building it first.
275
- - The client app is running in AOT (Ahead-of-Time) compilation mode, which requires pre-compiled libraries.
276
-
277
- **Solutions:**
278
- 1. **Build the package for production/AOT compatibility:**
279
- - Ensure you have built the package using `npm run build` (which uses ng-packagr or similar to generate AOT-ready code).
280
- - Install the built package via npm (e.g., from a local tarball or registry) instead of linking to the source folder.
281
-
282
- 2. **For development (if you must link to source):**
283
- - Switch your Angular app to JIT mode by bootstrapping with `@angular/platform-browser-dynamic` instead of `@angular/platform-browser`.
284
-
285
- 3. **Verify imports:**
286
- - Ensure you're importing from the built package (e.g., `import { MesAuthService } from 'mesauth-angular';`) and not from the `src` folder.
287
-
288
- ### Components Appear Empty
289
- If components like `ma-user` or `ma-user-profile` render as empty:
290
- - Ensure `provideMesAuth()` is called in your `app.config.ts`.
291
- - Check browser console for logs from components.
292
- - If `currentUser` is null, the component shows a login button—verify the API returns user data.
293
-
294
- ## Notes
295
- - The service expects an endpoint `GET {apiBaseUrl}/auth/me` that returns the current user.
296
- - Avatar endpoint: `GET {apiBaseUrl}/auth/{userId}/avatar`
297
- - SignalR events used: `ReceiveNotification` (adjust to your backend).
Binary file
Binary file
Binary file
package/ng-package.json DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "$schema": "./node_modules/ng-packagr/ng-package.schema.json",
3
- "dest": "dist",
4
- "allowedNonPeerDependencies": ["@microsoft/signalr", "rxjs"],
5
- "lib": {
6
- "entryFile": "src/index.ts"
7
- }
8
- }
package/src/index.ts DELETED
@@ -1,10 +0,0 @@
1
- export * from './mes-auth.service';
2
- export * from './mes-auth.interceptor';
3
- export * from './mes-auth.module';
4
- export * from './user-profile.component';
5
- export * from './ma-user.component';
6
- export * from './notification-badge.component';
7
- export * from './notification-panel.component';
8
- export * from './toast-container.component';
9
- export * from './toast.service';
10
- export * from './theme.service';
@@ -1,39 +0,0 @@
1
- import { Component, ViewChild, AfterViewInit } from '@angular/core';
2
- import { ToastContainerComponent } from './toast-container.component';
3
- import { UserProfileComponent } from './user-profile.component';
4
- import { NotificationPanelComponent } from './notification-panel.component';
5
-
6
- @Component({
7
- selector: 'ma-user',
8
- standalone: true,
9
- imports: [ToastContainerComponent, UserProfileComponent, NotificationPanelComponent],
10
- template: `
11
- <ma-toast-container></ma-toast-container>
12
- <div class="user-header">
13
- <ma-user-profile (notificationClick)="notificationPanel.open()"></ma-user-profile>
14
- </div>
15
- <ma-notification-panel #notificationPanel (notificationRead)="onNotificationRead()"></ma-notification-panel>
16
- `,
17
- styles: [`
18
- .user-header {
19
- display: flex;
20
- justify-content: flex-end;
21
- }
22
- `]
23
- })
24
- export class MaUserComponent implements AfterViewInit {
25
- @ViewChild(UserProfileComponent) userProfile?: UserProfileComponent;
26
-
27
- ngAfterViewInit() {
28
- // Ensure proper initialization
29
- if (this.userProfile) {
30
- this.userProfile.loadUnreadCount();
31
- }
32
- }
33
-
34
- onNotificationRead() {
35
- if (this.userProfile) {
36
- this.userProfile.loadUnreadCount();
37
- }
38
- }
39
- }
@@ -1,59 +0,0 @@
1
- import { inject } from '@angular/core';
2
- import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
3
- import { throwError } from 'rxjs';
4
- import { catchError } from 'rxjs/operators';
5
- import { Router } from '@angular/router';
6
- import { MesAuthService } from './mes-auth.service';
7
-
8
- // Track if we're currently redirecting to prevent loopback
9
- let isRedirecting = false;
10
-
11
- /**
12
- * Functional HTTP interceptor for handling 401/403 auth errors.
13
- * Redirects to login page on 401, and to 403 page on 403.
14
- * Includes loopback prevention to avoid infinite redirects.
15
- */
16
- export const mesAuthInterceptor: HttpInterceptorFn = (req, next) => {
17
- const authService = inject(MesAuthService);
18
- const router = inject(Router);
19
-
20
- return next(req).pipe(
21
- catchError((error: HttpErrorResponse) => {
22
- const status = error.status;
23
-
24
- // Check if we should handle this error and prevent loopback
25
- if ((status === 401 || status === 403) && !isRedirecting) {
26
- const config = authService.getConfig();
27
- const baseUrl = config?.userBaseUrl || '';
28
-
29
- const currentUrl = router.url + (window.location.hash || '');
30
- const returnUrl = encodeURIComponent(currentUrl);
31
-
32
- // Avoid loops if already on auth/unauth pages
33
- const isLoginPage = currentUrl.includes('/login');
34
- const is403Page = currentUrl.includes('/403');
35
- const isAuthPage = currentUrl.includes('/auth');
36
- // Skip redirect for the initial /auth/me check (app startup when not logged in)
37
- const isMeAuthPage = req.url.includes('/auth/me');
38
-
39
- if (status === 401 && !isLoginPage && !isAuthPage && !isMeAuthPage) {
40
- // Session expired or not authenticated - redirect to login
41
- // No isAuthenticated check: when session expires, BehaviorSubject still holds
42
- // stale user data, so checking isAuthenticated would block the redirect.
43
- isRedirecting = true;
44
- setTimeout(() => { isRedirecting = false; }, 5000);
45
- window.location.href = `${baseUrl}/login?returnUrl=${returnUrl}`;
46
- } else if (status === 403 && !is403Page) {
47
- isRedirecting = true;
48
- setTimeout(() => { isRedirecting = false; }, 5000);
49
- let redirectUrl = `${baseUrl}/403?returnUrl=${returnUrl}`;
50
- if (error.error && error.error.required) {
51
- redirectUrl += `&required=${encodeURIComponent(error.error.required)}`;
52
- }
53
- window.location.href = redirectUrl;
54
- }
55
- }
56
- return throwError(() => error);
57
- })
58
- );
59
- };
@@ -1,9 +0,0 @@
1
- import { NgModule } from '@angular/core';
2
- import { MesAuthService } from './mes-auth.service';
3
-
4
- @NgModule({
5
- providers: [
6
- MesAuthService
7
- ]
8
- })
9
- export class MesAuthModule {}