Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: angular sample #624

Merged
merged 2 commits into from
Feb 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/tricky-spoons-pay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@logto/js": minor
---

add `buildAngularAuthConfig()` to build `angular-auth-oidc-client` config in a Logto way

Also add a new type `LogtoAngularConfig`.
8 changes: 7 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ node_modules
/packages/*/dist
/packages/*/lib
/packages/*/build
/packages/*/tmp
/packages/*/out-tsc
/packages/*/bazel-out

# logs
logs
Expand All @@ -22,13 +25,16 @@ yarn-error.log*
.pnpm-debug.log*

# misc
.angular/cache
.sass-cache/
cache
.*cache
.DS_Store
Thumbs.db
*.env
.idea/
*.pem
.history
.vercel
.next
*.local
*.local
35 changes: 35 additions & 0 deletions packages/angular-sample/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Logto Angular sample

A sample Angular application that demonstrates how to integrate Logto with `angular-auth-oidc-client`.

**Configuration**: See [app.config.ts](src/app/app.config.ts).
**Usage**: See [app.component.ts](src/app/app.component.ts).

For more information about `angular-auth-oidc-client`, see its [repository](https://github.com/damienbod/angular-auth-oidc-client) and official [documentation](https://angular-auth-oidc-client.com/).

> *[!Note]
> This project is excluded from the workspace. To run the sample, you need to manually install project dependencies.

---

This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 17.2.0.

## Development server

Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.

## Code scaffolding

Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.

## Build

Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.

## Running unit tests

Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).

## Running end-to-end tests

Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
106 changes: 106 additions & 0 deletions packages/angular-sample/angular.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"@logto/angular-sample": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/logto/angular-sample",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": [],
"server": "src/main.server.ts",
"prerender": true,
"ssr": {
"entry": "server.ts"
}
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "@logto/angular-sample:build:production"
},
"development": {
"buildTarget": "@logto/angular-sample:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "@logto/angular-sample:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
}
}
}
}
}
46 changes: 46 additions & 0 deletions packages/angular-sample/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "@logto/angular-sample",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"serve:ssr:@logto/angular-sample": "node dist/logto/angular-sample/server/server.mjs"
},
"private": true,
"dependencies": {
"@angular/animations": "^17.2.0",
"@angular/common": "^17.2.0",
"@angular/compiler": "^17.2.0",
"@angular/core": "^17.2.0",
"@angular/forms": "^17.2.0",
"@angular/platform-browser": "^17.2.0",
"@angular/platform-browser-dynamic": "^17.2.0",
"@angular/platform-server": "^17.2.0",
"@angular/router": "^17.2.0",
"@angular/ssr": "^17.2.0",
"@logto/js": "workspace:^",
"angular-auth-oidc-client": "^17.0.0",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.2.0",
"@angular/cli": "^17.2.0",
"@angular/compiler-cli": "^17.2.0",
"@types/express": "^4.17.17",
"@types/jasmine": "~5.1.0",
"@types/node": "^18.18.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.3.2"
}
}
56 changes: 56 additions & 0 deletions packages/angular-sample/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr';
import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import bootstrap from './src/main.server';

// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const server = express();
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const indexHtml = join(serverDistFolder, 'index.server.html');

const commonEngine = new CommonEngine();

server.set('view engine', 'html');
server.set('views', browserDistFolder);

// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
server.get('*.*', express.static(browserDistFolder, {
maxAge: '1y'
}));

// All regular routes use the Angular engine
server.get('*', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;

commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});

return server;
}

function run(): void {
const port = process.env['PORT'] || 4000;

// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}

run();
9 changes: 9 additions & 0 deletions packages/angular-sample/src/app/app.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<h1>Hello, {{ title }}</h1>
<p>Congratulations! Your app is running. 🎉</p>
<button *ngIf="!isAuthenticated" (click)="signIn()">Sign in</button>
<ng-container *ngIf="isAuthenticated">
<pre>{{ userData | json }}</pre>
<p>Access token: {{ accessToken }}</p>
<button (click)="signOut()">Sign out</button>
</ng-container>
<router-outlet />
Empty file.
29 changes: 29 additions & 0 deletions packages/angular-sample/src/app/app.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});

it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});

it(`should have the '@logto/angular-sample' title`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('@logto/angular-sample');
});

it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, @logto/angular-sample');
});
});
43 changes: 43 additions & 0 deletions packages/angular-sample/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';
import { OidcSecurityService } from 'angular-auth-oidc-client';
import type { UserInfoResponse } from '@logto/js';

@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, CommonModule],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent implements OnInit {
title = '@logto/angular-sample';
isAuthenticated = false;
userData?: UserInfoResponse;
idToken?: string;
accessToken?: string;

constructor(public oidcSecurityService: OidcSecurityService) { }

ngOnInit() {
this.oidcSecurityService.checkAuth().subscribe(({ isAuthenticated, userData, idToken, accessToken }) => {
console.log('app authenticated', isAuthenticated, userData);
this.isAuthenticated = isAuthenticated;
this.userData = userData;
this.idToken = idToken;
this.accessToken = accessToken;
});
}

signIn() {
this.oidcSecurityService.authorize();
}

signOut() {
this.oidcSecurityService.logoff().subscribe((result) => {
console.log('app sign-out', result);
this.isAuthenticated = false;
});
}
}
11 changes: 11 additions & 0 deletions packages/angular-sample/src/app/app.config.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';

const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering()
]
};

export const config = mergeApplicationConfig(appConfig, serverConfig);
Loading
Loading