Skip to content

Docs: Awcog

ng-druid edited this page Aug 8, 2025 · 1 revision

Documentation for Awcog Angular Library


Table of Contents

  1. Introduction
  2. Installation
  3. Overview
  4. Key Concepts
    • AWS Cognito Authentication Integration
    • NGRX Effects for Authentication Handling
    • Cookies Management
  5. Core Components
    • AwcogModule
  6. Key Tokens
    • COGNITO_SETTINGS
  7. Models
    • CognitoSettings
  8. Effects
    • CognitoAuthEffects
  9. Usage
    • Configuring Cognito
    • Authentication Workflow
    • Cookie Management
  10. API Reference
  11. Examples
  12. Testing

1. Introduction

The Awcog Angular library integrates AWS Cognito authentication workflows into Angular applications. Designed to work seamlessly with @ngrx/effects and the Redux pattern, this library simplifies the authentication setup by handling tokens, cookies, and user session management.


2. Installation

Install the necessary dependencies:

npm install awcog @ngrx/effects @rollthecloudinc/auth js-cookie

3. Overview

Awcog provides integration with AWS Cognito and includes logic for managing authentication workflows using NGRX Effects. Key features include:

  • Cognito authentication settings configuration.
  • Loading and managing user sessions through cookies.
  • Dispatching and handling actions using @ngrx/effects.

Features:

  • Automatic cookie management for session persistence.
  • Highly extensible authentication effects.
  • Type-safe injection of settings using Angular's InjectionToken.

4. Key Concepts

4.1 AWS Cognito Authentication Integration

The library uses the COGNITO_SETTINGS token to inject AWS Cognito credentials, such as identity pool ID, user pool ID, and region. These settings configure user authentication with AWS Cognito services.


4.2 NGRX Effects for Authentication Handling

The library utilizes @ngrx/effects to implement side effects for authentication workflows, such as:

  • Triggering SetUser and QUERY_ALL actions.
  • Persisting user cookies for session state management.
  • Observing authentication actions dispatched through NGRX.

4.3 Cookies Management

The CognitoAuthEffects class handles storing authentication cookies dynamically with expiration times using the lightweight js-cookie library.


5. Core Components

AwcogModule

The AwcogModule defines the necessary application setup for integrating AWS Cognito. It includes NGRX effects and handles authentication workflows.

Key Features:

  • Adds Cognito-related effects via EffectsModule.forFeature.
  • Provides infrastructure for handling authentication cookies.

Example:

import { AwcogModule } from 'awcog';

@NgModule({
  imports: [AwcogModule],
  declarations: [],
  exports: [],
})
export class AppModule {}

6. Key Tokens

COGNITO_SETTINGS

This injection token provides AWS Cognito settings, such as the identity pool ID, region, and user pool ID. CognitoSettings is used to configure the authentication service.

Example:

import { COGNITO_SETTINGS } from 'awcog';
import { CognitoSettings } from 'awcog/models';

const cognitoConfig: CognitoSettings = {
  identityPoolId: 'us-east-1:xxxxxx',
  region: 'us-east-1',
  userPoolId: 'us-east-1_xxxxxx',
};

@NgModule({
  providers: [{ provide: COGNITO_SETTINGS, useValue: cognitoConfig }],
})
export class AppModule {}

7. Models

CognitoSettings

This data model defines required fields to configure AWS Cognito authentication.

Properties:

  • identityPoolId: AWS Identity Pool ID.
  • region: AWS region for the Cognito service.
  • userPoolId: AWS User Pool ID.

Example:

const settings = new CognitoSettings({
  identityPoolId: 'us-east-1:xxxxxx',
  region: 'us-east-1',
  userPoolId: 'us-east-1_xxxxxx',
});
console.log(settings);

8. Effects

CognitoAuthEffects

The authentication effects manage key workflows for AWS Cognito. Notable effects include:

  • SetUser: Triggered whenever user data is set, this effect dispatches a query action for cookies (QUERY_ALL).
  • LoadCookies: Observes successful cookie retrieval actions (QUERY_ALL_SUCCESS) and sets user cookies using the js-cookie library.

Example:

@Injectable()
export class CognitoAuthEffects {
  constructor(private actions$: Actions, private entityActionFactory: EntityActionFactory) {}

  setUser = createEffect(() =>
    this.actions$.pipe(
      ofType(AuthActions.AuthActionTypes.SetUser),
      map(() =>
        this.entityActionFactory.create<Cookie>('Cookie', EntityOp.QUERY_ALL)
      )
    )
  );

  loadCookies$ = createEffect(
    () =>
      this.actions$.pipe(
        ofEntityType('Cookie'),
        ofEntityOp([EntityOp.QUERY_ALL_SUCCESS]),
        tap((action) => {
          action.payload.data.forEach((cookie) =>
            Cookies.set(cookie.name, cookie.value, {
              expires: new Date(new Date().getTime() + 3600 * 1000),
            })
          );
        })
      ),
    { dispatch: false }
  );
}

9. Usage

9.1 Configuring Cognito

Define the Cognito settings in your Angular application using COGNITO_SETTINGS.

import { COGNITO_SETTINGS } from 'awcog';
import { CognitoSettings } from 'awcog/models';

@NgModule({
  providers: [
    {
      provide: COGNITO_SETTINGS,
      useValue: {
        identityPoolId: 'us-east-1:xxxxxx',
        region: 'us-east-1',
        userPoolId: 'us-east-1_xxxxxx',
      },
    },
  ],
})
export class AppModule {}

9.2 Authentication Workflow

Use NGRX actions and effects to trigger authentication workflows.

Example:

import { Store } from '@ngrx/store';
import { AuthActions } from '@rollthecloudinc/auth';

constructor(private store: Store) {}

login() {
  this.store.dispatch({
    type: AuthActions.AuthActionTypes.SetUser,
    payload: { username: 'testUser', token: 'tokenValue' },
  });
}

9.3 Cookie Management

Cookies are automatically managed by CognitoAuthEffects. Expired cookies are handled and refreshed dynamically.

Example:

import * as Cookies from 'js-cookie';

Cookies.get('sessionCookie'); // Retrieve the stored cookie
Cookies.remove('sessionCookie'); // Remove the cookie

10. API Reference

CognitoSettings Class

  1. Properties

    • identityPoolId: Specifies the AWS Cognito Identity Pool ID.
    • region: AWS region where Cognito is hosted.
    • userPoolId: AWS Cognito User Pool ID.
  2. Constructor

    • Params: data?: CognitoSettings - Optional settings for initialization.

11. Examples

Example 1: Configuring Cognito Settings

const cognitoSettings = {
  identityPoolId: 'us-east-1:xxxxxx',
  region: 'us-east-1',
  userPoolId: 'us-east-1_xxxxxx',
};

@NgModule({
  providers: [{ provide: COGNITO_SETTINGS, useValue: cognitoSettings }],
})
export class AppModule {}

Example 2: Dispatching Authentication Actions

Use NGRX Actions to trigger authentication effects:

import { Store } from '@ngrx/store';
import { AuthActions } from '@rollthecloudinc/auth';

constructor(private store: Store) {}

authenticateUser() {
  this.store.dispatch({
    type: AuthActions.AuthActionTypes.SetUser,
    payload: { username: 'testUser', token: 'abc123' },
  });
}

Example 3: Handling Cookies

Retrieve, set, and manipulate cookies with js-cookie:

import * as Cookies from 'js-cookie';

Cookies.set('sessionCookie', 'sessionValue', { expires: 1 });
console.log(Cookies.get('sessionCookie'));
Cookies.remove('sessionCookie');

12. Testing

Testing Cognito Effects

Example test for verifying the setUser effect:

import { CognitoAuthEffects } from './effects/cognito-auth.effects';
import { ActionsSubject } from '@ngrx/store';

describe('CognitoAuthEffects', () => {
  let effects: CognitoAuthEffects;
  let actions$: ActionsSubject;

  beforeEach(() => {
    actions$ = new ActionsSubject();
    effects = new CognitoAuthEffects(actions$, {
      create: jest.fn(() => ({ type: 'QUERY_ALL' })),
    } as any);
  });

  it('should dispatch QUERY_ALL when SetUser is triggered', () => {
    actions$.next({
      type: AuthActions.AuthActionTypes.SetUser,
    });

    effects.setUser.subscribe((action) => {
      expect(action.type).toEqual('QUERY_ALL');
    });
  });
});

Conclusion

The Awcog library offers seamless integration with AWS Cognito authentication, session management via cookies, and NGRX Effects for efficient workflows. Its modular architecture is ideal for building scalable and secure applications.

For any issues, feature requests, or contributions, feel free to reach out or open a pull request!

Clone this wiki locally