npm package: @medha-analytics/medhasso-auth
Description: Angular authentication library for MedHasso SSO integration
Author: Medha Analytics
Latest version: 1.0.0

# MedHasso Authentication Library

Angular authentication library for seamless integration with MedHasso SSO services. This library provides JWT token management, route guards, HTTP interceptors, and user management utilities.

## Features

- 🔐 **JWT Token Management** - Automatic token refresh and storage
- 🛡️ **Route Guards** - Protect routes with authentication and role-based access
- 🔄 **HTTP Interceptor** - Automatic token attachment to HTTP requests
- 👤 **User Management** - Extract and manage user information from JWT tokens
- ⚙️ **Configurable** - Extensive configuration options for different environments
- 📱 **Angular 14+ Support** - Compatible with Angular 14 through latest versions

## Installation

```bash
npm install @medha-analytics/medhasso-auth
```

## Quick Start

### 1. Import and Configure

In your `app.config.ts` (Angular 17+ standalone) or `app.module.ts`:

#### Standalone Bootstrap (Angular 17+)
```typescript
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { MedHassoAuthModule } from '@medha-analytics/medhasso-auth';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';
import { environment } from './environments/environment';

bootstrapApplication(AppComponent, {
  providers: [
    provideRouter(routes),
    provideHttpClient(withInterceptorsFromDi()),
    ...MedHassoAuthModule.forStandalone({
      ssoUrl: environment.ssoUrl,
      refreshUrl: environment.refreshUrl,
      applicationName: 'Your App Name'
    })
  ]
});
```

#### Module-based (Angular 14-16)
```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { MedHassoAuthModule } from '@medha-analytics/medhasso-auth';
import { AppComponent } from './app.component';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    MedHassoAuthModule.forRoot({
      ssoUrl: environment.ssoUrl,
      refreshUrl: environment.refreshUrl,
      applicationName: 'Your App Name'
    })
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

### 2. Protect Routes

```typescript
import { Routes } from '@angular/router';
import { MedHassoAuthGuard, MedHassoRoleGuard, MedHassoAdminGuard } from '@medha-analytics/medhasso-auth';

export const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [MedHassoAuthGuard]
  },
  {
    path: 'admin',
    component: AdminComponent,
    canActivate: [MedHassoAdminGuard]
  },
  {
    path: 'manager',
    component: ManagerComponent,
    canActivate: [MedHassoRoleGuard],
    data: { roles: ['manager', 'admin'] }
  }
];
```

### 3. Use in Components

```typescript
import { Component } from '@angular/core';
import { MedHassoAuthService } from '@medha-analytics/medhasso-auth';

@Component({
  selector: 'app-user-profile',
  template: `
    <div *ngIf="authService.isAuthenticated()">
      <h2>Welcome, {{ authService.getUserDisplayName() }}!</h2>
      <p>Email: {{ authService.getUserEmail() }}</p>
      <div *ngIf="authService.isAdmin()">
        <button>Admin Panel</button>
      </div>
      <button (click)="logout()">Logout</button>
    </div>
  `
})
export class UserProfileComponent {
  constructor(public authService: MedHassoAuthService) {}

  logout() {
    this.authService.logout();
  }
}
```

## Configuration Options

### Environment Setup
First, configure your environment files:

```typescript
// src/environments/environment.ts
export const environment = {
  production: false,
  ssoUrl: 'https://your-dev-sso.domain.com:3000',
  refreshUrl: 'https://your-dev-refresh.domain.com:4000',
  // ... other config
};

// src/environments/environment.production.ts
export const environment = {
  production: true,
  ssoUrl: 'https://your-prod-sso.domain.com:3000',
  refreshUrl: 'https://your-prod-refresh.domain.com:4000',
  // ... other config
};
```

### Basic Configuration
```typescript
{
  ssoUrl: environment.ssoUrl,
  refreshUrl: environment.refreshUrl,
  applicationName: 'Your Application Name'
}
```

### Advanced Configuration
```typescript
{
  ssoUrl: environment.ssoUrl,
  refreshUrl: environment.refreshUrl,
  applicationName: 'Your Application Name',
  
  // Token configuration
  tokenConfig: {
    storageType: 'localStorage', // or 'sessionStorage'
    idTokenKey: 'idToken',
    refreshTokenKey: 'refreshToken',
    refreshBeforeExpiryMinutes: 5,
    autoRefresh: true
  },
  
  // HTTP Interceptor configuration
  interceptorConfig: {
    enabled: true,
    authHeaderPrefix: 'Bearer',
    excludeUrls: ['*/public/*', '*/assets/*'],
    includeUrls: ['*/api/*'] // Optional: if specified, only these URLs get tokens
  },
  
  // Security configuration
  securityConfig: {
    httpsOnly: true,
    secureCookies: true,
    additionalCspSources: ['https://your-cdn.com']
  }
}
```

## Guards

### MedHassoAuthGuard
Basic authentication guard that ensures user is logged in.

### MedHassoRoleGuard
Role-based access guard. Use with route data:
```typescript
{
  path: 'admin',
  component: AdminComponent,
  canActivate: [MedHassoRoleGuard],
  data: { 
    role: 'admin', // Single role
    roles: ['admin', 'manager'] // Multiple roles (OR condition)
  }
}
```

### MedHassoAdminGuard
Admin-only access guard.

## Services

### MedHassoAuthService
Main authentication service with methods:
- `isAuthenticated(): boolean`
- `getCurrentUser(): MedHassoUser | null`
- `hasRole(role: string): boolean`
- `isAdmin(): boolean`
- `login(returnUrl?: string): void`
- `logout(): void`
- `getUserEmail(): string | null`
- `getUserDisplayName(): string | null`

### TokenManagementService
Low-level token management (usually not needed directly):
- `getTokenInfo(): TokenInfo | null`
- `refreshToken(): Observable<any>`
- `setTokens(idToken: string, refreshToken?: string): void`

## Environment-Specific Setup

### Development
```typescript
// src/environments/environment.ts
export const environment = {
  production: false,
  ssoUrl: 'https://dev-sso.your-domain.com:3000',
  refreshUrl: 'https://dev-refresh.your-domain.com:4000'
};

// Usage in module/config
MedHassoAuthModule.forRoot({
  ssoUrl: environment.ssoUrl,
  refreshUrl: environment.refreshUrl,
  applicationName: 'Your App (Dev)'
})
```

### Production
```typescript
// src/environments/environment.production.ts
export const environment = {
  production: true,
  ssoUrl: 'https://sso.your-domain.com:3000',
  refreshUrl: 'https://refresh.your-domain.com:4000'
};

// Usage in module/config
MedHassoAuthModule.forRoot({
  ssoUrl: environment.ssoUrl,
  refreshUrl: environment.refreshUrl,
  applicationName: 'Your App'
})
```

## CSP Configuration

For server-side Content Security Policy, include these domains:

```javascript
// In your server configuration (e.g., Express.js)
const cspSources = [
  process.env.SSO_URL || 'https://your-sso.domain.com:3000',
  process.env.REFRESH_URL || 'https://your-refresh.domain.com:4000'
];
```

## Migration Guide

### From Custom Implementation
1. Remove your existing auth guard, interceptor, and token service
2. Install this library
3. Update your imports and module configuration
4. Update route guards to use library guards
5. Update components to use `MedHassoAuthService`

## Contributing

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

## License

MIT License - see [LICENSE](LICENSE) file for details.