@hichchi/ngx-auth
v0.0.9
Published
A utility library for Angular applications with common services, interceptors, and state management
Downloads
923
Readme
📦 Installation
npm install @hichchi/ngx-auth🌟 Overview
This library provides a collection of utilities for Angular applications, including HTTP interceptors, authentication services, state management, and form utilities. It helps streamline common tasks in Angular development and promotes consistent implementation patterns.
✨ Key Features
- 🌐 HTTP Interceptors: Pre-configured interceptors for API URLs, authentication, error handling, and response transformation
- 🔐 Authentication Services: Services for handling user authentication and authorization
- 📊 State Management: State management utilities for authentication and other application states
- 📝 Form Utilities: Helper functions for working with Angular forms
- 📋 Interface Definitions: TypeScript interfaces for consistent typing
🚀 Usage
HTTP Interceptors
import { NgModule } from "@angular/core";
import { HTTP_INTERCEPTORS } from "@angular/common/http";
import {
apiInterceptor,
AuthInterceptor,
ErrorInterceptor,
ResponseInterceptor,
} from "@hichchi/ngx-auth/interceptors";
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: apiInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ResponseInterceptor, multi: true },
],
})
export class AppModule {}Authentication Service
import { Component } from "@angular/core";
import { AuthService } from "@hichchi/ngx-auth/services";
@Component({
selector: "app-sign-in",
template: `
<form (submit)="signIn()">
<input [(ngModel)]="username" name="username" placeholder="Username" />
<input
[(ngModel)]="password"
name="password"
type="password"
placeholder="Password"
/>
<button type="submit">Sign In</button>
</form>
`,
})
export class SignInComponent {
username = "";
password = "";
constructor(private authService: AuthService) {}
signIn() {
this.authService
.signIn({
email: this.username,
password: this.password,
})
.subscribe(
(response) => console.log("Sign in successful", response),
(error) => console.error("Sign in failed", error),
);
}
}State Management
import { Component, OnInit } from "@angular/core";
import { AuthState } from "@hichchi/ngx-auth/state";
@Component({
selector: "app-header",
template: `
<nav>
<a routerLink="/">Home</a>
<a *ngIf="isLoggedIn" routerLink="/profile">Profile</a>
<button *ngIf="isLoggedIn" (click)="signOut()">Sign Out</button>
<a *ngIf="!isLoggedIn" routerLink="/sign-in">Sign In</a>
</nav>
`,
})
export class HeaderComponent implements OnInit {
isLoggedIn = false;
constructor(private authState: AuthState) {}
ngOnInit() {
this.isLoggedIn = this.authState.signedIn();
}
signOut() {
this.authState.signOut();
}
}🔧 Development
Building
nx build ngx-authRunning unit tests
nx test ngx-authTests are executed via Jest.
Made with ❤️ by Hichchi Dev
Building the future of Angular authentication, one commit at a time
📖 API Documentation
Complete technical reference for all classes, interfaces, methods, and types in this library.
Auto-generated by TypeDoc - Browse through detailed API references, code examples, and implementation guides below.
📋 API Table of Contents
Classes
AuthFormComponent
Defined in: libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:97
Constructors
Constructor
new AuthFormComponent(): AuthFormComponent;Defined in: libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:146
Returns
Methods
handleError()
handleError(error): void;Defined in: libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:318
Handles authentication errors and updates component state
This method is called when any authentication operation fails. It updates the component's loading and error states, stores the error for display, and emits the onError event to notify parent components of the failure.
Parameters
error
HttpError
The HTTP error object containing error details
Returns
void
Example
// Called automatically by authentication methods on error
// Can also be called manually to handle custom errors
const customError = new HttpError("Custom error message");
this.handleError(customError);handleGoogleSignIn()
handleGoogleSignIn(): Promise<void>;Defined in: libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:183
Handles Google OAuth sign-in authentication
This method initiates the Google OAuth flow, retrieves an access token, and authenticates the user with the backend service. It manages loading states and emits appropriate events based on the authentication result.
Returns
Promise<void>
Promise that resolves when the Google sign-in process completes
Example
// Called automatically when user clicks Google sign-in button
await this.handleGoogleSignIn();handleLocalAuth()
handleLocalAuth(signInBody): void;Defined in: libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:213
Handles local authentication sign-in process
This method processes local authentication using username/email and password. It sets loading and error states, then calls the AuthState service to perform the sign-in operation.
Parameters
signInBody
SignInBody
The sign-in data containing authentication credentials
Returns
void
Example
const signInData = {
email: "[email protected]",
password: "password123",
};
this.handleLocalAuth(signInData);handleSignUp()
handleSignUp(signUpBody): void;Defined in: libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:248
Handles user registration (sign-up) process
This method processes user registration with the provided sign-up data. It sets loading and error states, calls the AuthService to create a new user, and emits the onSignUp event upon successful registration.
Parameters
signUpBody
SignUpBody
The sign-up data containing user registration information
Returns
void
Example
const signUpData = {
firstName: "John",
lastName: "Doe",
email: "[email protected]",
password: "password123",
};
this.handleSignUp(signUpData);handleSubmit()
handleSubmit(e): void;Defined in: libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:278
Handles form submission for both sign-in and sign-up modes
This method processes form submission by preventing the default browser behavior, validating the form data, and routing to the appropriate authentication method based on the current mode (sign-in or sign-up). It extracts form data and calls either handleSignUp() or handleLocalAuth() accordingly.
Parameters
e
SubmitEvent
The form submit event to prevent default behavior
Returns
void
Example
// Called automatically when form is submitted
// In template: <form (submit)="handleSubmit($event)">
handleSubmit(event);Properties
authField
WritableSignal<AuthField>
Writable signal containing the current authentication field type (EMAIL or USERNAME)
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:132
authFieldLabel
WritableSignal<string>
Writable signal containing the display label for the authentication field
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:135
authForm
DataFormGroup<AuthFormData>
Reactive form group for handling authentication form data
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:144
authState
object & StateSource<{ accessToken: AccessToken | null; accessTokenExpiresOn: Date | null; data: object; refreshToken: RefreshToken | null; refreshTokenExpiresOn: Date | null; sessionId: string | null; signedIn: boolean; user: User<string, string, TenantSlug> | null; }>
Injected AuthState service for managing authentication state
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:141
error
WritableSignal<HttpError | null>
Writable signal containing the current error object, if any
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:138
facebook
InputSignal<boolean>
Input signal to control whether Facebook authentication is enabled
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:111
google
InputSignal<boolean>
Input signal to control whether Google OAuth authentication is enabled
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:108
isError
WritableSignal<boolean>
Writable signal indicating whether an error state is currently active
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:129
isLoading
WritableSignal<boolean>
Writable signal indicating whether an authentication operation is in progress
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:123
isSignUp
WritableSignal<boolean>
Writable signal indicating whether the form is in sign-up mode (true) or sign-in mode (false)
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:126
local
InputSignal<boolean>
Input signal to control whether local authentication (username/email + password) is enabled
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:105
onError
OutputEmitterRef<HttpError>
Output emitter that fires when an authentication error occurs
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:114
onSignIn
OutputEmitterRef<AuthResponse>
Output emitter that fires when a user successfully signs in
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:117
onSignUp
OutputEmitterRef<User<string, string, TenantSlug>>
Output emitter that fires when a user successfully signs up
libs/ngx-auth/src/lib/components/auth-form/auth-form.component.ts:120
AuthService
Defined in: libs/ngx-auth/src/lib/services/auth.service.ts:72
Angular authentication service for client-side authentication operations
This service provides methods for handling authentication operations in Angular applications, including user sign-in, sign-up, Google OAuth authentication, token management, and sign-out. It communicates with the backend authentication API and handles the client-side aspects of the authentication flow.
The service is configured through the AuthConfig interface and automatically handles token expiration date parsing and HTTP request management. It integrates seamlessly with the @hichchi/nest-auth backend module.
Key features:
- Local authentication (email/username and password)
- Google OAuth authentication with popup flow
- Token refresh functionality
- User registration
- Automatic token expiration handling
- RESTful API communication
Example
// In a component
export class LoginComponent {
constructor(private authService: AuthService) {}
async signIn() {
try {
const response = await this.authService
.signIn({
email: "[email protected]",
password: "password123",
})
.toPromise();
console.log("Signed in:", response.user);
} catch (error) {
console.error("Sign in failed:", error);
}
}
}See
- AuthConfig Configuration interface for the authentication service
- NgxHichchiAuthModule Module that provides this service
- AuthState State management service for authentication
- AuthResponse Response interface for authentication operations
Extends
CrudHttpService
Constructors
Constructor
new AuthService(config): AuthService;Defined in: libs/ngx-auth/src/lib/services/auth.service.ts:82
Creates an instance of AuthService
Parameters
config
The authentication configuration injected from AUTH_CONFIG token
Returns
See
- AUTH_CONFIG Injection token for authentication configuration
- AuthConfig Interface defining the configuration structure
Overrides
CrudHttpService.constructor;Methods
delete()
Call Signature
delete<Res>(url, options?): Observable<Res>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:95
Type Parameters
Res
unknown
Parameters
url
string | string[]
options?
HttpOptions
Returns
Observable<Res>
Inherited from
CrudHttpService.delete;Call Signature
delete<Res>(url, options?): Promise<Res>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:97
Type Parameters
Res
unknown
Parameters
url
string | string[]
options?
HttpOptionsPromise
Returns
Promise<Res>
Inherited from
CrudHttpService.delete;get()
Call Signature
get<Res>(url, options?): Observable<Res>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:48
Type Parameters
Res
unknown
Parameters
url
string | string[]
options?
HttpGetOptions<Model>
Returns
Observable<Res>
Inherited from
CrudHttpService.get;Call Signature
get<Res>(url, options?): Promise<Res>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:50
Type Parameters
Res
unknown
Parameters
url
string | string[]
options?
HttpGetOptionsPromise<Model>
Returns
Promise<Res>
Inherited from
CrudHttpService.get;getAuthResponse()
getAuthResponse(accessToken, skipNotify?): Observable<AuthResponse>;Defined in: libs/ngx-auth/src/lib/services/auth.service.ts:265
Retrieves the complete authentication response using an access token
This method exchanges an access token for a complete authentication response containing user information and token details. It's typically used after Google OAuth authentication to get the full user profile and session data.
The method automatically converts token expiration timestamps to JavaScript Date objects for easier handling in the client application.
Parameters
accessToken
AccessToken
The access token to exchange for authentication response
skipNotify?
boolean
Optional flag to skip error notifications for this request
Returns
Observable<AuthResponse>
Observable that emits the complete authentication response
Example
// Get auth response after Google sign-in
const accessToken = await this.authService.googleSignIn();
this.authService.getAuthResponse(accessToken).subscribe({
next: (response) => {
console.log("User:", response.user);
console.log("Tokens:", {
access: response.accessToken,
refresh: response.refreshToken,
});
},
error: (error) => {
console.error("Failed to get auth response:", error);
},
});See
- AccessToken Type representing access tokens
- AuthResponse Interface for complete authentication response
- AuthEndpoint.GET_AUTH_RESPONSE Backend endpoint for token exchange
- googleSignIn Method that provides access tokens for this operation
googleSignIn()
googleSignIn(): Promise<AccessToken>;Defined in: libs/ngx-auth/src/lib/services/auth.service.ts:183
Initiates Google OAuth authentication using a popup window
This method opens a popup window that navigates to the Google OAuth authentication endpoint. It handles the OAuth flow by monitoring the popup window and extracting the access token from the callback URL when authentication is successful.
The popup is automatically positioned in the center of the screen and has predefined dimensions for optimal user experience. The method polls the popup window to detect when authentication is complete or if the user closes the popup.
Returns
Promise<AccessToken>
Promise that resolves with the access token when authentication succeeds
Throws
If authentication fails or the popup is blocked
Examples
// Initiate Google sign-in
try {
const accessToken = await this.authService.googleSignIn();
console.log("Google authentication successful:", accessToken);
// Use the token to get full auth response
const authResponse = await this.authService
.getAuthResponse(accessToken)
.toPromise();
console.log("User data:", authResponse.user);
} catch (error) {
console.error("Google authentication failed:", error);
}// In a component with error handling
async signInWithGoogle() {
try {
const token = await this.authService.googleSignIn();
// Handle successful authentication
this.router.navigate(['/dashboard']);
} catch (error) {
if (error.message.includes('popup')) {
this.showError('Please allow popups for Google sign-in');
} else {
this.showError('Google sign-in failed. Please try again.');
}
}
}See
- getAuthResponse Method to get full authentication response using the access token
- AuthEndpoint.GOOGLE_SIGN_IN Backend endpoint for Google OAuth initiation
- GOOGLE_AUTH_POPUP_WIDTH Constant defining popup window width
- GOOGLE_AUTH_POPUP_HEIGHT Constant defining popup window height
- POPUP_POLLING_INTERVAL_MS Constant defining popup polling interval
patch()
Call Signature
patch<Res, B>(
url,
body,
options?): Observable<Res>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:83
Type Parameters
Res
unknown
B
unknown
Parameters
url
string | string[]
body
B
options?
HttpOptions
Returns
Observable<Res>
Inherited from
CrudHttpService.patch;Call Signature
patch<Res, B>(
url,
body,
options?): Promise<Res>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:85
Type Parameters
Res
unknown
B
unknown
Parameters
url
string | string[]
body
B
options?
HttpOptionsPromise
Returns
Promise<Res>
Inherited from
CrudHttpService.patch;post()
Call Signature
post<Res, B>(
url,
body,
options?): Observable<Res>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:59
Type Parameters
Res
unknown
B
unknown
Parameters
url
string | string[]
body
B
options?
HttpOptions
Returns
Observable<Res>
Inherited from
CrudHttpService.post;Call Signature
post<Res, B>(
url,
body,
options?): Promise<Res>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:61
Type Parameters
Res
unknown
B
unknown
Parameters
url
string | string[]
body
B
options?
HttpOptionsPromise
Returns
Promise<Res>
Inherited from
CrudHttpService.post;put()
Call Signature
put<Res, B>(
url,
body,
options?): Observable<Res>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:71
Type Parameters
Res
unknown
B
unknown
Parameters
url
string | string[]
body
B
options?
HttpOptions
Returns
Observable<Res>
Inherited from
CrudHttpService.put;Call Signature
put<Res, B>(
url,
body,
options?): Promise<Res>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:73
Type Parameters
Res
unknown
B
unknown
Parameters
url
string | string[]
body
B
options?
HttpOptionsPromise
Returns
Promise<Res>
Inherited from
CrudHttpService.put;refreshToken()
refreshToken(refreshToken, skipNotify?): Observable<TokenResponse>;Defined in: libs/ngx-auth/src/lib/services/auth.service.ts:371
Refreshes an expired access token using a refresh token
This method exchanges a valid refresh token for a new set of access and refresh tokens. It's typically used when the current access token has expired but the refresh token is still valid, allowing the user to maintain their session without re-authenticating.
The refresh token mechanism provides a secure way to maintain long-lived sessions while keeping access tokens short-lived for better security.
Parameters
refreshToken
RefreshToken
The refresh token to exchange for new tokens
skipNotify?
boolean
Optional flag to skip error notifications for this request
Returns
Observable<TokenResponse>
Observable that emits the new token response
Example
// Refresh tokens when access token expires
const storedRefreshToken = localStorage.getItem("refreshToken");
if (storedRefreshToken) {
this.authService.refreshToken(storedRefreshToken).subscribe({
next: (tokenResponse) => {
console.log("Tokens refreshed successfully");
// Store new tokens
localStorage.setItem("accessToken", tokenResponse.accessToken);
localStorage.setItem("refreshToken", tokenResponse.refreshToken);
},
error: (error) => {
console.error("Token refresh failed:", error);
// Redirect to login page
this.router.navigate(["/login"]);
},
});
}See
- RefreshToken Type representing refresh tokens
- TokenResponse Interface for token refresh response
- AuthEndpoint.REFRESH_TOKEN Backend endpoint for token refresh
- signIn Method to get initial tokens through authentication
request()
protected request<Res, Body>(
type,
url,
body,
options?): Promise<Res> | Observable<Res>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:23
Type Parameters
Res
unknown
Body
unknown
Parameters
type
RequestType
url
string | string[]
body
Body
options?
HttpGetOptions<Model> | HttpGetOptionsPromise<Model>
Returns
Promise<Res> | Observable<Res>
Inherited from
CrudHttpService.request;signIn()
signIn(dto, skipNotify?): Observable<AuthResponse>;Defined in: libs/ngx-auth/src/lib/services/auth.service.ts:118
Authenticates a user with email/username and password
This method sends a sign-in request to the backend authentication API with the provided credentials. It automatically converts the token expiration timestamps from the response into JavaScript Date objects for easier handling in the client application.
Parameters
dto
SignInBody
The sign-in data containing user credentials
skipNotify?
boolean
Optional flag to skip error notifications for this request
Returns
Observable<AuthResponse>
Observable that emits the authentication response with user data and tokens
Example
// Sign in with email and password
this.authService
.signIn({
email: "[email protected]",
password: "password123",
})
.subscribe({
next: (response) => {
console.log("User signed in:", response.user);
console.log("Access token expires:", response.accessTokenExpiresOn);
},
error: (error) => {
console.error("Sign in failed:", error);
},
});See
- SignInBody Interface for sign-in request data
- AuthResponse Interface for authentication response
- AuthEndpoint.SIGN_IN Backend endpoint for user authentication
signOut()
signOut(skipNotify?): Observable<SuccessResponse | null>;Defined in: libs/ngx-auth/src/lib/services/auth.service.ts:439
Signs out the current user and invalidates their session
This method sends a sign-out request to the backend API to invalidate the user's current session and tokens. It effectively logs the user out of the application and clears their authentication state on the server.
After calling this method, you should also clear any client-side authentication data such as tokens stored in localStorage, sessionStorage, or application state.
Parameters
skipNotify?
boolean
Optional flag to skip error notifications for this request
Returns
Observable<SuccessResponse | null>
Observable that emits a success response when sign-out is complete
Examples
// Sign out the current user
this.authService.signOut().subscribe({
next: (response) => {
console.log("User signed out successfully");
// Clear client-side authentication data
localStorage.removeItem("accessToken");
localStorage.removeItem("refreshToken");
// Redirect to login page
this.router.navigate(["/login"]);
},
error: (error) => {
console.error("Sign out failed:", error);
// Even if server sign-out fails, clear local data
localStorage.clear();
this.router.navigate(["/login"]);
},
});// Sign out with state management
async signOut() {
try {
await this.authService.signOut().toPromise();
// Clear authentication state
this.authState.clearUser();
this.notificationService.showSuccess('Signed out successfully');
} catch (error) {
console.error('Sign out error:', error);
} finally {
// Always redirect to login
this.router.navigate(['/login']);
}
}See
- SuccessResponse Interface for success response
- AuthEndpoint.SIGN_OUT Backend endpoint for user sign-out
- signIn Method to authenticate user after sign-out
signUp()
signUp(dto, skipNotify?): Observable<User<string, string, TenantSlug>>;Defined in: libs/ngx-auth/src/lib/services/auth.service.ts:325
Registers a new user account
This method sends a registration request to the backend API with the provided user information. It creates a new user account and returns the user data upon successful registration.
Note that this method only creates the user account and does not automatically sign the user in. After successful registration, you may need to call signIn or handle email verification depending on your application's configuration.
Parameters
dto
SignUpBody
The sign-up data containing user registration information
skipNotify?
boolean
Optional flag to skip error notifications for this request
Returns
Observable<User<string, string, TenantSlug>>
Observable that emits the newly created user data
Example
// Register a new user
this.authService
.signUp({
email: "[email protected]",
password: "securePassword123",
firstName: "John",
lastName: "Doe",
})
.subscribe({
next: (user) => {
console.log("User registered successfully:", user);
// Optionally redirect to sign-in or email verification page
this.router.navigate(["/verify-email"]);
},
error: (error) => {
console.error("Registration failed:", error);
// Handle registration errors (email already exists, etc.)
},
});See
- SignUpBody Interface for user registration data
- User Interface for user data returned after registration
- AuthEndpoint.SIGN_UP Backend endpoint for user registration
- signIn Method to authenticate user after registration
parseQuery()
static parseQuery<T>(options?): HttpQuery<Model>;Defined in: libs/ngx-utils/src/lib/services/crud-http.service.ts:106
Type Parameters
T
Parameters
options?
HttpGetOptions<T> | HttpGetOptionsPromise<T>
Returns
HttpQuery<Model>
Inherited from
CrudHttpService.parseQuery;Properties
http
protected
HttpClient
CrudHttpService.http;libs/ngx-utils/src/lib/services/crud-http.service.ts:21
NgxHichchiAuthModule
Defined in: libs/ngx-auth/src/lib/auth.module.ts:93
Angular module for authentication functionality
This module provides comprehensive authentication features for Angular applications, including authentication forms, permission-based directives, and authentication services. It integrates with the Hichchi authentication system and provides both components and directives for building secure Angular applications.
The module exports:
- AuthFormComponent: A ready-to-use authentication form component
- PermissionDirective: A structural directive for permission-based conditional rendering
The module must be configured using the forRoot() method to provide the necessary authentication configuration.
Tenant handling:
tenantcan be provided in the configuration or dynamically set in requests via a custom HTTP header (x-tenant, controlled byTENANT_HEADER_KEY).- This approach replaces previous subdomain-based tenant resolution.
Examples
// Basic module configuration
@NgModule({
imports: [
NgxHichchiAuthModule.forRoot({
apiBaseURL: "https://api.example.com",
}),
],
})
export class AppModule {}// Advanced configuration with custom authentication field
@NgModule({
imports: [
NgxHichchiAuthModule.forRoot({
apiBaseURL: "https://api.example.com",
authField: AuthField.EMAIL,
}),
],
})
export class AppModule {}// Optional static tenant header
@NgModule({
imports: [
NgxHichchiAuthModule.forRoot({
apiBaseURL: "https://api.example.com",
tenant: "tenant-a",
}),
],
})
export class AppModule {}See
- AuthConfig Configuration interface for the authentication module
- AuthFormComponent Authentication form component
- PermissionDirective Permission-based conditional rendering directive
- AuthService Authentication service for managing user sessions
Constructors
Constructor
new NgxHichchiAuthModule(): NgxHichchiAuthModule;Returns
Methods
forRoot()
static forRoot(config): ModuleWithProviders<NgxHichchiAuthModule>;Defined in: libs/ngx-auth/src/lib/auth.module.ts:135
Configures the NgxHichchiAuthModule with the provided authentication configuration
This static method sets up the module with the necessary providers and configuration
for authentication functionality. The configuration includes the apiBaseURL for
all authentication requests, and optionally a tenant string that is attached
to requests via the TENANT_HEADER_KEY header.
Parameters
config
The authentication configuration object containing API endpoints, tenant, and other settings
Returns
ModuleWithProviders<NgxHichchiAuthModule>
A ModuleWithProviders object configured with authentication providers
Examples
// Basic configuration
NgxHichchiAuthModule.forRoot({
apiBaseURL: "https://api.example.com",
});// Configuration with environment variables and authentication field
NgxHichchiAuthModule.forRoot({
apiBaseURL: environment.apiUrl,
authField: AuthField.USERNAME,
});// Configuration with static tenant
NgxHichchiAuthModule.forRoot({
apiBaseURL: "https://api.example.com",
tenant: "tenant-a",
});See
- AuthConfig Interface defining the configuration structure
- AUTH_CONFIG Injection token for the authentication configuration
- AuthService Service that uses the provided configuration
PermissionDirective
Defined in: libs/ngx-auth/src/lib/directives/permission.directive.ts:67
Angular structural directive for permission-based conditional rendering
This directive conditionally displays or hides DOM elements based on the current user's permissions. It integrates with the authentication state to check if the authenticated user has the required permission to view the content. The directive uses Angular's structural directive pattern and automatically updates when the user's authentication state or permissions change.
The directive works by checking the user's role permissions against the required permission string. If the user has the required permission, the template content is rendered; otherwise, it's removed from the DOM.
Examples
<!-- Basic usage - show content only if user has 'users.read' permission -->
<div *hcPermission="'users.read'">
<p>This content is only visible to users with read permission</p>
</div><!-- Using with component properties -->
<button *hcPermission="'users.delete'" (click)="deleteUser()">
Delete User
</button><!-- Using with multiple permissions (user needs at least one) -->
<div *hcPermission="['users.read', 'users.write']">
<p>This content is visible to users with either read OR write permission</p>
</div><!-- Using with dynamic permissions -->
<ng-container *hcPermission="requiredPermission">
<app-admin-panel></app-admin-panel>
</ng-container>// Component usage with dynamic permission
export class UserListComponent {
requiredPermission = "users.manage";
// Or with multiple permissions
requiredPermissions = ["users.read", "users.write"];
}See
- AuthState Authentication state service that provides user information
- User User interface that contains role and permission information
- isRoleObject Utility function to check if role is an object with permissions
- NgxHichchiAuthModule Module that provides this directive
Constructors
Constructor
new PermissionDirective(): PermissionDirective;Defined in: libs/ngx-auth/src/lib/directives/permission.directive.ts:114
Constructor that sets up the permission checking effect
Initializes an Angular effect that automatically re-evaluates permission whenever the authentication state or required permission changes. This ensures the UI stays in sync with the user's current permissions.
Returns
Properties
hcPermission
InputSignal<string | string[]>
Required permission string or array of strings input signal
This input defines the permission(s) that the current user must have for the template content to be displayed. The permission string(s) should match the permissions defined in the user's role.
When an array is provided, the user needs to have at least one of the specified permissions (OR logic).
Example
<!-- Single permission -->
<div *hcPermission="'users.read'">Content</div>
<!-- Multiple permissions (user needs at least one) -->
<div *hcPermission="['users.read', 'users.write']">Content</div>libs/ngx-auth/src/lib/directives/permission.directive.ts:105
Enumerations
AuthGuardCondition
Defined in: libs/ngx-auth/src/lib/enums/auth-guard-condition.enum.ts:33
Enumeration of authentication guard conditions
This enum defines the different conditions that authentication guards can check to determine whether a user should be allowed to access a route. Each condition represents a different aspect of the user's authentication state.
These conditions are used in conjunction with AuthGuardOption to create flexible route protection rules that can handle various authentication scenarios.
Examples
// Check if user is signed in
const guardOption: AuthGuardOption = {
condition: AuthGuardCondition.SIGNED_IN,
state: true,
redirect: "/login",
};// Check if user has a valid token
const tokenGuardOption: AuthGuardOption = {
condition: AuthGuardCondition.HAS_TOKEN,
state: true,
redirect: "/unauthorized",
};See
AuthGuardOption Interface that uses these conditions
Enumeration Members
HAS_TOKEN
"has-token"
Check if the user has a valid access token
libs/ngx-auth/src/lib/enums/auth-guard-condition.enum.ts:37
SIGNED_IN
"signed-in"
Check if the user is signed in to the application
libs/ngx-auth/src/lib/enums/auth-guard-condition.enum.ts:35
Functions
authGuard()
Authentication guard factory function for Angular route protection
This function creates a route guard that protects routes based on authentication state. It supports both simple single-condition guards and complex multi-condition guards. The guard evaluates authentication conditions and redirects users when conditions are not met.
The guard integrates with the AuthState service to check the current authentication status and uses the Angular Router for navigation when redirects are needed. It supports checking whether users are signed in, have valid tokens, and other authentication-related conditions.
Key features:
- Multiple authentication condition support
- Automatic redirection on failed conditions
- Integration with AuthState for reactive authentication checks
- Support for both simple and complex guard configurations
- Type-safe condition checking
Param
Either a single AuthGuardCondition or an array of AuthGuardOption objects
Param
Required state for single condition (ignored when using options array)
Param
Redirect path for single condition (ignored when using options array)
Examples
// Protecting a route that requires authentication
const routes: Routes = [
{
path: "dashboard",
component: DashboardComponent,
canActivate: [authGuard(AuthGuardCondition.SIGNED_IN, true, "/login")],
},
];// Complex guard with multiple conditions
const routes: Routes = [
{
path: "admin",
component: AdminComponent,
canActivate: [
authGuard([
{
condition: AuthGuardCondition.SIGNED_IN,
state: true,
redirect: "/login",
},
{
condition: AuthGuardCondition.HAS_TOKEN,
state: true,
redirect: "/unauthorized",
},
]),
],
},
];// Preventing authenticated users from accessing login page
const routes: Routes = [
{
path: "login",
component: LoginComponent,
canActivate: [authGuard(AuthGuardCondition.SIGNED_IN, false, "/dashboard")],
},
];See
- AuthState Service that provides authentication state information
- AuthGuardOption Interface for configuring guard options
- AuthGuardCondition Enum defining available authentication conditions
- getAllAuthGuardOptions Utility function for extracting guard options from routes
- AUTH_GUARD_OPTIONS_KEY Constant for storing guard options in route data
Call Signature
function authGuard(options): CanActivateFn;Defined in: libs/ngx-auth/src/lib/guards/auth.guard.ts:37
Creates an authentication guard function with multiple configuration options
This overload accepts an array of AuthGuardOption objects, allowing for complex authentication rules with multiple conditions. Each option can specify different conditions, states, and redirect paths.
Parameters
options
Array of authentication guard options to evaluate
Returns
CanActivateFn
A CanActivateFn that can be used in Angular route guards
Example
// Multiple conditions guard
const routes: Routes = [
{
path: "admin",
component: AdminComponent,
canActivate: [
authGuard([
{
condition: AuthGuardCondition.SIGNED_IN,
state: true,
redirect: "/login",
},
{
condition: AuthGuardCondition.HAS_TOKEN,
state: true,
redirect: "/unauthorized",
},
]),
],
},
];See
- AuthGuardOption Interface defining guard configuration options
- AuthGuardCondition Enum of available authentication conditions
Call Signature
function authGuard(condition, state, fallbackRedirect): CanActivateFn;Defined in: libs/ngx-auth/src/lib/guards/auth.guard.ts:77
Creates an authentication guard function with a single condition
This overload provides a simplified way to create guards with a single authentication condition. It's more convenient when you only need to check one condition.
Parameters
condition
The authentication condition to check
state
boolean
The required state of the condition (true/false)
fallbackRedirect
string
The path to redirect to if the condition is not met
Returns
CanActivateFn
A CanActivateFn that can be used in Angular route guards
Examples
// Simple signed-in guard
const routes: Routes = [
{
path: "profile",
component: ProfileComponent,
canActivate: [authGuard(AuthGuardCondition.SIGNED_IN, true, "/login")],
},
];// Redirect signed-in users away from login page
const routes: Routes = [
{
path: "login",
component: LoginComponent,
canActivate: [authGuard(AuthGuardCondition.SIGNED_IN, false, "/dashboard")],
},
];See
- AuthGuardCondition Enum of available authentication conditions
- AuthGuardOption Interface for more complex guard configurations
authInterceptor()
function authInterceptor(redirect, onRedirect?): HttpInterceptorFn;Defined in: libs/ngx-auth/src/lib/interceptors/auth.interceptor.ts:167
Creates an HTTP interceptor for handling authentication tokens and automatic token refresh
This interceptor automatically adds authentication tokens to outgoing HTTP requests and handles token refresh when requests fail due to expired tokens. It provides seamless authentication management for Angular applications using JWT tokens.
Key features:
- Automatic token attachment to HTTP requests
- Automatic token refresh on authentication errors
- Prevention of multiple simultaneous refresh operations
- Coordinated handling of multiple failed requests during token refresh
- Automatic redirect to login page when refresh fails
- Configurable redirect behavior with optional callback
The interceptor works by:
- Adding the current access token to outgoing requests
- Monitoring responses for authentication errors
- Attempting token refresh when authentication errors occur
- Retrying failed requests with the new token
- Redirecting to login when refresh fails or no refresh token is available
Parameters
redirect
string
The path to redirect to when authentication fails completely
onRedirect?
() => void
Optional callback function to execute before redirecting
Returns
HttpInterceptorFn
An HttpInterceptorFn that can be used in Angular HTTP interceptor configuration
Examples
// Basic usage in app configuration
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient(withInterceptors([authInterceptor("/login")]))],
};// With custom redirect callback
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withInterceptors([
authInterceptor("/login", () => {
console.log("Redirecting to login due to authentication failure");
// Clear any cached data
localStorage.clear();
}),
]),
),
],
};// In a module-based application
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useValue: authInterceptor("/auth/login"),
multi: true,
},
],
})
export class AppModule {}See
- AuthState Service that provides authentication state and tokens
- AuthService Service that handles token refresh operations
- HttpInterceptorFn Angular HTTP interceptor function type
- SKIPPED_ERRORS Array of error codes that trigger token refresh
roleGuard()
function roleGuard(role, options): CanActivateFn;Defined in: libs/ngx-auth/src/lib/guards/role.guard.ts:76
Creates a role-based authorization guard function for Angular route protection
This function creates a route guard that protects routes based on user roles. It checks if the current user's role matches the required role, and if not, it evaluates the provided options to determine the appropriate action (redirect or sign out).
The guard integrates with the AuthState service to check the current user's role and uses the Angular Router for navigation when redirects are needed. If no matching role or redirect option is found, the user is automatically signed out.
Key features:
- Role-based route protection
- Configurable redirect options based on user roles
- Automatic sign-out for unauthorized access
- Integration with AuthState for reactive role checking
- Support for multiple role-based redirect scenarios
Parameters
role
string
The required role name that the user must have to access the route
options
Array of role guard options that define redirect behavior for different user roles
Returns
CanActivateFn
A CanActivateFn that evaluates role-based authorization and handles navigation
