# Angular

{% hint style="info" %}
This tutorial is based on the [example app](https://github.com/LanderDK/blitzware-angular-sdk/tree/master/projects/blitzware-angular-example).
{% endhint %}

1. [**Configure BlitzWare**](#configure-blitzware)
2. [**Install the BlitzWare Angular SDK**](#install-the-blitzware-angular-sdk)
3. [**Add Login to your application**](#add-login-to-your-application)
4. [**Show User profile info and add Logout to your application**](#show-user-profile-info-and-add-logout-to-your-application)
5. [**Add Protection to your routes**](#add-protection-to-your-routes)

## 1) Configure BlitzWare <a href="#configure-blitzware" id="configure-blitzware"></a>

### Get Your Application Keys <a href="#get-your-application-keys" id="get-your-application-keys"></a>

You will need some details about your application to communicate with BlitzWare. You can get these details from the Application Settings section in the BlitzWare dashboard.

<figure><img src="/files/2wZRoRqdmWpuTXY4PW2j" alt=""><figcaption></figcaption></figure>

You need the **Client ID**.

### Configure Redirect URIs

A redirect URI is a URL in your application where BlitzWare redirects the user after they have authenticated. The redirect URI for your app must be added to the **Redirect URIs** list in your **Application Settings** under the **Security** tab. If this is not set, users will be unable to log in to the application and will get an error.

## 2) Install the BlitzWare Angular SDK

Run the following command within your project directory to install the [BlitzWare Angular SDK](https://www.npmjs.com/package/blitzware-angular-sdk):

{% code title="npm" overflow="wrap" lineNumbers="true" %}

```
npm install blitzware-angular-sdk
```

{% endcode %}

{% code title="yarn" lineNumbers="true" %}

```
yarn add blitzware-angular-sdk
```

{% endcode %}

The SDK exposes several types that help you integrate BlitzWare with your Angular application idiomatically, including a module and an authentication service.

### Register and providing BlitzWare

The SDK exports `provideBlitzWareAuth`, which is a provide function that contains all the services required for the SDK to function. To register this with your application:

1. Open the `app.config.ts` file.
2. Import the `provideBlitzWareAuth` function from the `blitzware-angular-sdk` package.
3. Add  `provideBlitzWareAuth` to the application by adding it to the `providers` array.

{% code title="app.config.ts" lineNumbers="true" %}

```typescript
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideBlitzWareAuth } from 'blitzware-angular-sdk';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideBlitzWareAuth({
      clientId: 'your-client-id',
      redirectUri: 'your-redirect-uri',
      responseType: 'code', // or "token" for implicit flow
    }),
  ],
};
```

{% endcode %}

The `provideBlitzWareAuth` function takes the properties `clientId` and `redirectUri` ; the values of these properties correspond to the **Client ID** and **Redirect URI** values that you can find under **Settings** in the Single Page Web Application (SPA) that you registered with BlitzWare.

## 3) Add Login to your application

The BlitzWare Angular SDK gives you tools to quickly implement user authentication in your Angular application, such as creating a login button using the `login()` method from the `BlitzWareAuthService` service class. Executing `login()` redirects your users to the BlitzWare Universal Login Page, where BlitzWare can authenticate them. Upon successful authentication, BlitzWare will redirect your users back to your application.

{% code title="login.component.ts" lineNumbers="true" %}

```typescript
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { BlitzWareAuthService } from 'blitzware-angular-sdk';
import { NgIf, AsyncPipe } from '@angular/common';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [NgIf, AsyncPipe],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css',
})
export class LoginComponent implements OnInit {
  constructor(
    public auth: BlitzWareAuthService,
    private router: Router
  ) {}

  ngOnInit() {
    // Check if user is already authenticated after component loads
    this.auth.isAuthenticated.subscribe(isAuthenticated => {
      if (isAuthenticated) {
        // User is authenticated, redirect to dashboard
        this.router.navigate(['/dashboard']);
      }
    });
  }

  async login() {
    try {
      await this.auth.login();
    } catch (error) {
      console.error('Login failed:', error);
    }
  }
}
```

{% endcode %}

{% code title="login.component.html" lineNumbers="true" %}

```html
<div *ngIf="auth.isLoading | async; else loaded">
  <div class="loading">
    <h2>Loading...</h2>
    <p>Checking authentication status...</p>
  </div>
</div>

<ng-template #loaded>
  <div *ngIf="!(auth.isAuthenticated | async)">
    <h1>Welcome to BlitzWare</h1>
    <p>Please log in to access your dashboard.</p>
    <button (click)="login()" class="btn btn-primary">
      Login with BlitzWare
    </button>
  </div>
  
  <div *ngIf="auth.isAuthenticated | async">
    <h1>You're already logged in!</h1>
    <p>Redirecting to your dashboard...</p>
    <a routerLink="/dashboard" class="btn btn-secondary">
      Go to Dashboard
    </a>
  </div>
</ng-template>

```

{% endcode %}

## 4) Show User profile info and add Logout to your application

The BlitzWare Angular SDK helps you retrieve the profile information associated with logged-in users quickly in whatever component you need, such as their name or profile picture, to personalize the user interface. The profile information is available through `currentUser` exposed by the `BlitzWareAuthService` service.

You also need a way to log out. You can create a logout button using the `logout()` method from the `BlitzWareAuthService` service. Executing `logout()` clears the session and makes sure that the user can not access protected resources.

Take this `Dashboard` component as an example of how to use it:

{% code title="dashboard.component.ts" lineNumbers="true" fullWidth="false" %}

```typescript
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { BlitzWareAuthService } from 'blitzware-angular-sdk';
import { NgIf, AsyncPipe } from '@angular/common';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [NgIf, AsyncPipe],
  templateUrl: './dashboard.component.html',
  styleUrl: './dashboard.component.css',
})
export class DashboardComponent {
  constructor(public auth: BlitzWareAuthService, private router: Router) {}

  async logout() {
    try {
      await this.auth.logout();
      // Redirect to login page after successful logout
      this.router.navigate(['/login']);
    } catch (error) {
      console.error('Logout failed:', error);
      // Even if logout fails, redirect to login page
      this.router.navigate(['/login']);
    }
  }
}
```

{% endcode %}

{% code title="dashboard.component.html" lineNumbers="true" %}

```html
<div class="container mt-5" *ngIf="auth.currentUser | async as user">
  <div
    class="row align-items-center profile-header mb-5 text-center text-md-left"
  >
    <div class="col-md">
      <h1>Dashboard</h1>
      <p>Welcome to the protected dashboard, {{ user.username }}!</p>
      <button (click)="logout()">Logout</button>
    </div>
  </div>
</div>
```

{% endcode %}

## 5) Add Protection to your routes

The BlitzWare Angular SDK exports the `BlitzWareAuthGuard` class used to protect routes by preventing unauthorized users from accessing certain pages or components within your application. Here is how you can do it:

{% code title="app.routes.ts" lineNumbers="true" %}

```typescript
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { BlitzWareAuthGuard, BlitzWareLoginGuard } from 'blitzware-angular-sdk';

export const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent,
    canActivate: [BlitzWareLoginGuard], // Prevent authenticated users from seeing login
  },
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [BlitzWareAuthGuard], // Protect dashboard for authenticated users only
  },
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, // Redirect to dashboard first
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}
```

{% endcode %}

As you can see, we simply added `BlitzWareAuthGuard` between the `canActivate` brackets.

That's it!


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.blitzware.xyz/oauth/quickstart/spa/angular.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
