Skip to content

feat: support ng-add for standalone applications #1800

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

Merged
merged 6 commits into from
Jul 14, 2023
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
40 changes: 40 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,46 @@ jobs:
- name: Create Angular Project
run: sudo ng new angular-auth-oidc-client-test --skip-git

- name: Npm Install & Install Library from local artefact
run: |
sudo cp -R angular-auth-oidc-client-artefact angular-auth-oidc-client-test/
cd angular-auth-oidc-client-test
sudo npm install --unsafe-perm=true
sudo ng add ./angular-auth-oidc-client-artefact --authority-url-or-tenant-id "my-authority-url" --flow-type "Default config" --use-local-package=true --skip-confirmation

- name: Test Angular Application
working-directory: ./angular-auth-oidc-client-test
run: npm test -- --watch=false --browsers=ChromeHeadless

- name: Build Angular Application
working-directory: ./angular-auth-oidc-client-test
run: sudo npm run build

AngularLatestVersionWithStandaloneSchematics:
needs: build_job
runs-on: ubuntu-latest
name: Angular latest Standalone & Schematics Job
steps:
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: 16

- name: Download Artefact
uses: actions/download-artifact@v2
with:
name: angular_auth_oidc_client_artefact
path: angular-auth-oidc-client-artefact

- name: Install AngularCLI globally
run: sudo npm install -g @angular/cli

- name: Show ng Version
run: ng version

- name: Create Angular Project
run: sudo ng new angular-auth-oidc-client-test --skip-git --standalone

- name: Npm Install & Install Library from local artefact
run: |
sudo cp -R angular-auth-oidc-client-artefact angular-auth-oidc-client-test/
Expand Down
1 change: 1 addition & 0 deletions projects/angular-auth-oidc-client/src/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Public classes.

export { PassedInitialConfig } from './auth-config';
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needed to be used to configure a standalone application in a type-safe way.

export * from './auth-options';
export * from './auth-state/auth-result';
export * from './auth-state/auth-state';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function addModuleToImports(options: NgAddOptions): Rule {
return (host: Tree, context: SchematicContext) => {
const project = getProject(host);

const { moduleFileName, moduleName } = options.moduleInfo;
const { moduleFileName, moduleName } = options.moduleInfo!;

const modulesToImport = [
{
Expand Down
78 changes: 78 additions & 0 deletions projects/schematics/src/ng-add/actions/add-standalone-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics';
import {
addFunctionalProvidersToStandaloneBootstrap,
callsProvidersFunction,
} from '@schematics/angular/private/standalone';
import { insertImport } from '@schematics/angular/utility/ast-utils';
import { InsertChange } from '@schematics/angular/utility/change';
import * as ts from 'typescript';
import { getProject, readIntoSourceFile } from '../../utils/angular-utils';
import { NgAddOptions } from '../models/ng-add-options';

export function addStandaloneConfigsToProviders(options: NgAddOptions): Rule {
return (host: Tree, context: SchematicContext) => {
const project = getProject(host);

const { fileName, configName } = options.standaloneInfo!;

const standaloneConfigs = [
{
target: `${project.sourceRoot}/main.ts`,
configName,
configPath: `./auth/${fileName}`,
},
];

standaloneConfigs.forEach(({ target, configName, configPath }) => {
addProvider(host, context, configName, configPath, target);
});

context.logger.info(`✅️ All imports done, please add the 'provideRouter()' as well if you don't have it provided yet.`);

return host;
};
}

function addProvider(host: Tree, context: SchematicContext, configName: string, configPath: string, target: string) {
const sourcefile = readIntoSourceFile(host, target);
const providerFn = 'provideAuth';
if (callsProvidersFunction(host, sourcefile.fileName, providerFn)) {
// exit because the store config is already provided
return host;
}

const patchedConfigFile = addFunctionalProvidersToStandaloneBootstrap(
host,
sourcefile.fileName,
providerFn,
'angular-auth-oidc-client',
[ts.factory.createIdentifier('authConfig')]
);

const configFileContent = host.read(patchedConfigFile);
const source = ts.createSourceFile(
patchedConfigFile,
configFileContent?.toString('utf-8') || '',
ts.ScriptTarget.Latest,
true
);


const change = insertImport(
source,
patchedConfigFile,
configName,
configPath
);

const recorder = host.beginUpdate(patchedConfigFile);

if (change instanceof InsertChange) {
recorder.insertLeft(change.pos, change.toAdd);
}

host.commitUpdate(recorder);

return host;

}
6 changes: 3 additions & 3 deletions projects/schematics/src/ng-add/actions/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const IFRAME_SILENT_RENEW = `{

const AZURE_AD_SILENT_RENEW = `{
authority: 'https://login.microsoftonline.com/<authorityUrlOrTenantId>/v2.0',
authWellknownEndpoint: 'https://login.microsoftonline.com/common/v2.0',
authWellknownEndpointUrl: 'https://login.microsoftonline.com/common/v2.0',
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While testing the migration this gave a compile error, so I renamed this property to match the type.

redirectUrl: window.location.origin,
clientId: 'please-enter-clientId',
scope: 'please-enter-scopes', // 'openid profile ' + your scopes
Expand All @@ -41,7 +41,7 @@ const AZURE_AD_SILENT_RENEW = `{

const AZURE_AD_REFRESH_TOKENS = `{
authority: 'https://login.microsoftonline.com/<authorityUrlOrTenantId>/v2.0',
authWellknownEndpoint: 'https://login.microsoftonline.com/common/v2.0',
authWellknownEndpointUrl: 'https://login.microsoftonline.com/common/v2.0',
redirectUrl: window.location.origin,
clientId: 'please-enter-clientId',
scope: 'please-enter-scopes', // 'openid profile offline_access ' + your scopes
Expand Down Expand Up @@ -93,5 +93,5 @@ const OIDC_PLAIN = `{
renewTimeBeforeTokenExpiresInSeconds: 10,
}`;

export { DEFAULT_CONFIG, AZURE_AD_SILENT_RENEW, IFRAME_SILENT_RENEW, AZURE_AD_REFRESH_TOKENS, OIDC_PLAIN, AUTH_0, OAUTH_PAR };
export { AUTH_0, AZURE_AD_REFRESH_TOKENS, AZURE_AD_SILENT_RENEW, DEFAULT_CONFIG, IFRAME_SILENT_RENEW, OAUTH_PAR, OIDC_PLAIN };

4 changes: 2 additions & 2 deletions projects/schematics/src/ng-add/actions/copy-module-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function copyModuleFile(options: NgAddOptions): Rule {
return (host: Tree, context: SchematicContext) => {
const project = getProject(host);

const { moduleFileName, moduleFolder } = options.moduleInfo;
const { moduleFileName, filesFolder } = options.moduleInfo!;

const filePath = `${project.sourceRoot}/app/auth/${moduleFileName}.ts`;
if (host.exists(filePath)) {
Expand All @@ -32,7 +32,7 @@ export function copyModuleFile(options: NgAddOptions): Rule {

context.logger.info(`✅️ '${filePath}' will be created`);

const templateSource = apply(url(`./files/${moduleFolder}`), [
const templateSource = apply(url(`./files/${filesFolder}`), [
template(templateConfig),
move(normalize(`${project.sourceRoot}/app/auth`)),
]);
Expand Down
106 changes: 106 additions & 0 deletions projects/schematics/src/ng-add/actions/copy-standalone-file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { normalize } from '@angular-devkit/core';
import {
apply,
chain,
mergeWith,
move,
Rule,
SchematicContext,
SchematicsException,
template,
Tree,
url
} from '@angular-devkit/schematics';
import { getProject } from '../../utils/angular-utils';
import { NgAddOptions } from '../models/ng-add-options';
import { FlowType } from '../schema';
import { AUTH_0, AZURE_AD_REFRESH_TOKENS, AZURE_AD_SILENT_RENEW, DEFAULT_CONFIG, IFRAME_SILENT_RENEW, OAUTH_PAR, OIDC_PLAIN } from './configs';

export function copyStandaloneFile(options: NgAddOptions): Rule {
return (host: Tree, context: SchematicContext) => {
const project = getProject(host);

const { fileName, filesFolder } = options.standaloneInfo!;

const filePath = `${project.sourceRoot}/app/auth/${fileName}.ts`;
if (host.exists(filePath)) {
context.logger.info(`✅️ '${filePath}' already existing - skipping file create`);
return host;
}

const templateConfig = getTemplateConfig(options);

context.logger.info(`✅️ '${filePath}' will be created`);

const templateSource = apply(url(`./files/${filesFolder}`), [
template(templateConfig),
move(normalize(`${project.sourceRoot}/app/auth`)),
]);

return chain([mergeWith(templateSource)]);
};
}

function getTemplateConfig(options: NgAddOptions) {
const { authorityUrlOrTenantId, flowType } = options;

if (options.isHttpOption) {
return { ts: 'ts', authorityUrlOrTenantId };
}

const authConfig = getConfig(flowType, authorityUrlOrTenantId);

return { ts: 'ts', authConfig };
}

function getConfig(flowType: FlowType, authorityUrlOrTenantId: string) {
let config = DEFAULT_CONFIG;

switch (flowType) {
case FlowType.OidcCodeFlowPkceAzureAdUsingIframeSilentRenew: {
config = AZURE_AD_SILENT_RENEW;
break;
}

case FlowType.OidcCodeFlowPkceAzureAdUsingRefreshTokens: {
config = AZURE_AD_REFRESH_TOKENS;
break;
}

case FlowType.OAuthPushAuthorizationRequestsUsingRefreshTokens: {
config = OAUTH_PAR;
break;
}

case FlowType.OidcCodeFlowPkceUsingIframeSilentRenew: {
config = IFRAME_SILENT_RENEW;
break;
}

case FlowType.OidcCodeFlowPkceUsingIframeSilentRenewGettingConfigFromHttp: {
throw new SchematicsException(`With HTTP another module is used. No config but another module`);
}

case FlowType.OIDCCodeFlowPkce: {
config = OIDC_PLAIN;
break;
}

case FlowType.Auth0: {
config = AUTH_0;
break;
}

case FlowType.OidcCodeFlowPkceUsingRefreshTokens:
case FlowType.DefaultConfig: {
config = DEFAULT_CONFIG;
break;
}

default: {
throw new SchematicsException(`Could not parse flowType '${flowType}'`);
}
}

return config.replace('<authorityUrlOrTenantId>', authorityUrlOrTenantId);
}
16 changes: 12 additions & 4 deletions projects/schematics/src/ng-add/actions/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
import { Tree, noop } from '@angular-devkit/schematics';
import { Schema } from '../schema';
import { addPackageJsonDependencies } from './add-dependencies';
import { addModuleToImports } from './add-module-import';
import { addStandaloneConfigsToProviders } from './add-standalone-import';
import { addSilentRenewHtmlToAssetsArrayInAngularJson } from './adding-entry-to-assets';
import { copyModuleFile } from './copy-module-file';
import { copySilentRenewHtmlToRoot } from './copy-silent-renew-html';
import { copyStandaloneFile } from './copy-standalone-file';
import { installPackageJsonDependencies } from './install-dependencies';
import { runChecks } from './run-checks';
import { parseSchema } from './schema-parser';

export function getAllActions(options: Schema) {
const ngAddOptions = parseSchema(options);
export async function getAllActions(host: Tree, options: Schema) {
const ngAddOptions = await parseSchema(host, options);

return [
runChecks(),
addPackageJsonDependencies(ngAddOptions),
installPackageJsonDependencies(),
copyModuleFile(ngAddOptions),
addModuleToImports(ngAddOptions),

ngAddOptions.moduleInfo ? copyModuleFile(ngAddOptions) : noop(),
ngAddOptions.moduleInfo ? addModuleToImports(ngAddOptions) : noop(),

ngAddOptions.standaloneInfo ? copyStandaloneFile(ngAddOptions) : noop(),
ngAddOptions.standaloneInfo ? addStandaloneConfigsToProviders(ngAddOptions) : noop(),

addSilentRenewHtmlToAssetsArrayInAngularJson(ngAddOptions),
copySilentRenewHtmlToRoot(ngAddOptions),
];
Expand Down
42 changes: 35 additions & 7 deletions projects/schematics/src/ng-add/actions/schema-parser.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
import { NgAddOptions } from '../models/ng-add-options';
import { Tree } from '@angular-devkit/schematics';
import { isStandaloneSchematic } from '../../utils/angular-utils';
import { ModuleInfo, NgAddOptions, StandaloneInfo } from '../models/ng-add-options';
import { FlowType, Schema } from '../schema';

const AUTH_CONFIG_MODULE = { moduleFileName: 'auth-config.module', moduleName: 'AuthConfigModule', moduleFolder: 'auth-config' };
const AUTH_HTTP_CONFIG_MODULE = {
const AUTH_CONFIG_MODULE: ModuleInfo = {
moduleFileName: 'auth-config.module',
moduleName: 'AuthConfigModule',
filesFolder: 'auth-config-module'
};
const AUTH_HTTP_CONFIG_MODULE: ModuleInfo = {
moduleFileName: 'auth-http-config.module',
moduleName: 'AuthHttpConfigModule',
moduleFolder: 'auth-http-config',
filesFolder: 'auth-http-config-module',
};

const AUTH_CONFIG_STANDALONE: StandaloneInfo = {
fileName: 'auth.config',
configName: 'authConfig',
filesFolder: 'auth-config-standalone'
};
const AUTH_HTTP_CONFIG_STANDALONE: StandaloneInfo = {
fileName: 'auth-http.config',
configName: 'authHttpConfig',
filesFolder: 'auth-http-config-standalone',
};

function needsHttp(flowType: FlowType) {
Expand All @@ -22,19 +39,30 @@ function needsSilentRenewHtml(flowType: FlowType) {
return optionsWithSilentRenewHtml.includes(flowType);
}

function getModuleInfo(flowType: FlowType) {
function getModuleInfo(flowType: FlowType):ModuleInfo {
if (needsHttp(flowType)) {
return AUTH_HTTP_CONFIG_MODULE;
}

return AUTH_CONFIG_MODULE;
}

export function parseSchema(options: Schema): NgAddOptions {
function getStandaloneInfo(flowType: FlowType):StandaloneInfo {
if (needsHttp(flowType)) {
return AUTH_HTTP_CONFIG_STANDALONE;
}

return AUTH_CONFIG_STANDALONE;
}

export async function parseSchema(host: Tree, options: Schema): Promise<NgAddOptions> {
const { flowType } = options;
const isStandalone = await isStandaloneSchematic(host, options);

return {
...options,
moduleInfo: getModuleInfo(flowType),
moduleInfo: isStandalone ? undefined : getModuleInfo(flowType),
standaloneInfo: isStandalone ? getStandaloneInfo(flowType) : undefined,
isHttpOption: needsHttp(flowType),
needsSilentRenewHtml: needsSilentRenewHtml(flowType),
};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { PassedInitialConfig } from 'angular-auth-oidc-client';

export const authConfig: PassedInitialConfig = {
config: <%= authConfig %>
}
Loading