12 Commits

Author SHA1 Message Date
2b8d7d5ae2 switching auth strategy to oidc 2025-08-26 21:08:05 -05:00
7933198403 switching auth strategy to oidc 2025-08-26 21:07:32 -05:00
7f86bb383e removing public decorator 2025-08-26 12:56:35 -05:00
04d796da6c Upgrading to nest v11 2025-03-08 08:32:45 -06:00
24cde897d5 Updating version number to 1.0.0 2025-02-20 18:28:36 -06:00
361ed27db4 Adding user module and removing msgraph module 2025-02-20 18:27:46 -06:00
30b500bd7f refactoring 2025-02-01 11:07:55 -06:00
533d5d166b updating dynamic module to configurable module builder 2025-01-30 12:46:33 -06:00
41a1b9f807 updating az tables 2024-11-19 20:51:31 -06:00
67014a3080 changing to azure storage connection string (#11) 2024-10-11 18:45:55 -05:00
e192dcdb05 Feature/8 add optional auth guard (#9)
* adding optional auth to guard

* adding optional auth to guard
2024-09-24 08:58:43 -05:00
fcffd65d33 Feature/3 add az table module (#7)
* adding azure table client module

* adding azure table client module

* adding azure table client module

* adding azure table client module

* adding azure table client module
2024-08-11 19:51:23 -05:00
28 changed files with 1796 additions and 1775 deletions

View File

@@ -1,25 +1,14 @@
import { CanActivate } from '@nestjs/common';
import { ExecutionContext, Injectable } from '@nestjs/common'; import { ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard as PassportAuthGuard } from '@nestjs/passport'; import { AuthGuard as PassportAuthGuard } from '@nestjs/passport';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
@Injectable() @Injectable()
export class AuthGuard extends PassportAuthGuard('azure-ad') implements CanActivate { export class AuthGuard extends PassportAuthGuard('oidc') {
constructor(private readonly reflector: Reflector) { constructor() {
super(); super();
} }
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> { canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
const isPublic = this.reflector.get<boolean>(
'isPublic',
context.getHandler()
);
if (isPublic) {
return true;
}
return super.canActivate(context); return super.canActivate(context);
} }
} }

View File

@@ -1,5 +1,10 @@
export interface AuthOptions { export interface AuthModuleOptions {
tenantId: string; authorizationUrl: string;
issuer: string;
callbackUrl: string;
clientId: string; clientId: string;
clientSecret: string; clientSecret: string;
scope: string;
tokenUrl: string;
userInfoUrl: string;
} }

View File

@@ -0,0 +1,4 @@
import { ConfigurableModuleBuilder } from '@nestjs/common';
import { AuthModuleOptions } from './auth.interface';
export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } = new ConfigurableModuleBuilder<AuthModuleOptions>().build()

View File

@@ -1,26 +1,16 @@
import { Module, DynamicModule } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { AuthOptions } from './auth.interface';
import { AUTH_OPTIONS } from './auth.constants';
import { PassportModule } from '@nestjs/passport'; import { PassportModule } from '@nestjs/passport';
import { AzureAdStrategy } from './auth.strategy'; import { OidcStrategy } from './oidc.strategy';
import { ConfigurableModuleClass } from './auth.module-definition';
@Module({}) @Module({
export class AuthModule { imports: [
static register(options: AuthOptions): DynamicModule { PassportModule.register({
return { defaultStrategy: 'oidc'
module: AuthModule, })
imports: [ ],
PassportModule.register({ providers: [
defaultStrategy: 'azure-ad' OidcStrategy
}) ]
], })
providers: [ export class AuthModule extends ConfigurableModuleClass {}
{
provide: AUTH_OPTIONS,
useValue: options
},
AzureAdStrategy
]
};
}
}

View File

@@ -1,25 +0,0 @@
import { Inject, Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { BearerStrategy } from 'passport-azure-ad';
import { AuthOptions } from './auth.interface'
import { AUTH_OPTIONS } from "./auth.constants";
@Injectable()
export class AzureAdStrategy extends PassportStrategy(
BearerStrategy,
'azure-ad'
) {
constructor(@Inject(AUTH_OPTIONS) authOptions: AuthOptions) {
super({
identityMetadata: `https://login.microsoftonline.com/${authOptions.tenantId}/.well-known/openid-configuration`,
clientID: authOptions.clientId,
audience: `api://${authOptions.clientId}`,
loggingLevel: 'info',
loggingNoPII: false
})
}
async validate(data: any): Promise<any> {
return data;
}
}

View File

@@ -0,0 +1,31 @@
import { PassportStrategy } from "@nestjs/passport";
import { Strategy, Profile } from 'passport-openidconnect';
import { MODULE_OPTIONS_TOKEN } from "./auth.module-definition";
import { AuthModuleOptions } from "./auth.interface";
import { Inject, Injectable } from "@nestjs/common";
@Injectable()
export class OidcStrategy extends PassportStrategy(Strategy, 'oidc') {
constructor(@Inject(MODULE_OPTIONS_TOKEN) authModuleOptions: AuthModuleOptions) {
super({
authorizationURL: authModuleOptions.authorizationUrl,
callbackURL: authModuleOptions.callbackUrl,
clientID: authModuleOptions.clientId,
clientSecret: authModuleOptions.clientSecret,
issuer: authModuleOptions.issuer,
scope: authModuleOptions.scope,
tokenURL: authModuleOptions.tokenUrl,
userInfoURL: authModuleOptions.userInfoUrl
})
}
async validate(profile: Profile, done: Function): Promise<any> {
const user = {
id: profile.id,
email: profile.emails,
name: profile.displayName
}
done(null, user)
}
}

View File

@@ -1,3 +1,4 @@
import { SetMetadata } from "@nestjs/common"; import { SetMetadata } from "@nestjs/common";
export const Public = () => SetMetadata('isPublic', true); export const IS_PUBLIC_KEY = 'isPublic'
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);

View File

@@ -1 +0,0 @@
export const APP_CONFIG_OPTIONS = 'APP_CONFIG_OPTIONS';

View File

@@ -1,21 +0,0 @@
import { Module, DynamicModule } from '@nestjs/common';
import { AppConfigService } from './az-app-config.service';
import { AppConfigOptions } from './az-app-config.interface';
import { APP_CONFIG_OPTIONS } from './az-app-config.constants';
@Module({})
export class AppConfigModule {
static register(options: AppConfigOptions): DynamicModule {
return {
module: AppConfigModule,
providers: [
{
provide: APP_CONFIG_OPTIONS,
useValue: options
},
AppConfigService
],
exports: [AppConfigService]
};
}
}

View File

@@ -1,38 +0,0 @@
import { Inject, Injectable } from '@nestjs/common';
import { AppConfigOptions } from './az-app-config.interface';
import { APP_CONFIG_OPTIONS } from './az-app-config.constants';
import axios, { AxiosResponse } from 'axios';
import { AppConfigurationClient, ConfigurationSetting, FeatureFlagValue, GetConfigurationSettingResponse, featureFlagPrefix, isFeatureFlag, parseFeatureFlag } from '@azure/app-configuration';
import { ClientSecretCredential } from '@azure/identity';
@Injectable()
export class AppConfigService {
constructor(
@Inject(APP_CONFIG_OPTIONS)
private appConfigOptions: AppConfigOptions
) { }
async getFeatureFlags(keys: string[], label: string): Promise<{ key: string, enabled: boolean }[]> {
const credential: ClientSecretCredential = new ClientSecretCredential(this.appConfigOptions.tenantId, this.appConfigOptions.clientId, this.appConfigOptions.clientSecret);
const client: AppConfigurationClient = new AppConfigurationClient(this.appConfigOptions.url, credential);
const featureFlags: { key: string, enabled: boolean }[] = await Promise.all(
keys.map(async (key: string) => {
const configSetting: GetConfigurationSettingResponse = await client.getConfigurationSetting({
key: `${featureFlagPrefix}${key}`,
label: label
});
if (isFeatureFlag(configSetting)) {
const parsedFeatureFlag: ConfigurationSetting<FeatureFlagValue> = parseFeatureFlag(configSetting);
return {
key: parsedFeatureFlag.value.id,
enabled: parsedFeatureFlag.value.enabled
}
}
})
);
return featureFlags;
}
}

View File

@@ -1 +0,0 @@
export const TABLE_OPTIONS = 'TABLE_OPTIONS';

View File

@@ -1,4 +0,0 @@
export interface TableOptions {
accountName: string;
accountKey: string;
}

View File

@@ -1,21 +0,0 @@
import { Module, DynamicModule } from '@nestjs/common';
import { TableService } from './az-table.service';
import { TableOptions } from './az-table.interface';
import { TABLE_OPTIONS } from './az-table.constants';
@Module({})
export class TableModule {
static register(options: TableOptions): DynamicModule {
return {
module: TableModule,
providers: [
{
provide: TABLE_OPTIONS,
useValue: options
},
TableService
],
exports: [TableService]
}
}
}

View File

@@ -1,19 +0,0 @@
import { Inject, Injectable } from '@nestjs/common';
import { TableOptions } from './az-table.interface';
import { TABLE_OPTIONS } from './az-table.constants';
import { TableClient, AzureNamedKeyCredential } from '@azure/data-tables';
@Injectable()
export class TableService {
constructor(
@Inject(TABLE_OPTIONS)
private tablesOptions: TableOptions
) {}
async getTableClient(tableName: string): Promise<TableClient> {
const credential: AzureNamedKeyCredential = new AzureNamedKeyCredential(this.tablesOptions.accountName, this.tablesOptions.accountKey);
const tableClient: TableClient = new TableClient(`https://${this.tablesOptions.accountName}.table.core.windows.net`, tableName, credential);
return tableClient;
}
}

View File

@@ -1,22 +1,14 @@
// Azure App Configuration
export * from './azAppConfig/az-app-config.module';
export * from './azAppConfig/az-app-config.service';
// Azure Data Tables
export * from './azTable/az-table.module';
export * from './azTable/az-table.service';
export { TableClient } from '@azure/data-tables';
// Auth // Auth
export * from './auth/auth.module'; export * from './auth/auth.module';
export * from './auth/auth.gaurd'; export * from './auth/auth.gaurd';
export * from './auth/public.decorator'; export * from './auth/public.decorator';
// MS Graph // Custom Error
export * from './msGraph/ms-graph.module'; export * from './util/customError';
export * from './msGraph/ms-graph.service';
export { Client as MsGraphClient } from '@microsoft/microsoft-graph-client'; // User
export * from './user/user.module';
export * from './user/user.service';

View File

@@ -1 +0,0 @@
export const MS_GRAPH_OPTIONS = 'MS_GRAPH_OPTIONS';

View File

@@ -1,5 +0,0 @@
export interface MsGraphOptions {
tenantId: string;
clientId: string;
clientSecret: string;
}

View File

@@ -1,21 +0,0 @@
import { Module, DynamicModule } from '@nestjs/common';
import { MsGraphService } from './ms-graph.service';
import { MsGraphOptions } from './ms-graph.interface';
import { MS_GRAPH_OPTIONS } from './ms-graph.constants';
@Module({})
export class MsGraphModule {
static register(options: MsGraphOptions): DynamicModule {
return {
module: MsGraphModule,
providers: [
{
provide: MS_GRAPH_OPTIONS,
useValue: options
},
MsGraphService
],
exports: [MsGraphService]
}
}
}

View File

@@ -1,41 +0,0 @@
import { Inject, Injectable } from '@nestjs/common';
import { MsGraphOptions } from './ms-graph.interface';
import { MS_GRAPH_OPTIONS } from './ms-graph.constants';
import { Client } from '@microsoft/microsoft-graph-client';
import { AuthenticationResult, ConfidentialClientApplication, OnBehalfOfRequest } from '@azure/msal-node';
@Injectable()
export class MsGraphService {
constructor(@Inject(MS_GRAPH_OPTIONS) private msGraphOptions: MsGraphOptions) {}
async getMsGraphAuth(accessToken: string, scopes: string[]): Promise<string> {
try {
const oboRequest: OnBehalfOfRequest = {
oboAssertion: accessToken,
scopes: scopes
}
const cca = new ConfidentialClientApplication({
auth: {
clientId: this.msGraphOptions.clientId,
clientSecret: this.msGraphOptions.clientSecret,
authority: `https://login.microsoftonline.com/${this.msGraphOptions.tenantId}`
}
});
const authenticationResult: AuthenticationResult = await cca.acquireTokenOnBehalfOf(oboRequest);
return authenticationResult.accessToken
} catch (error) {
return error
}
}
async getMsGraphClientDelegated(accessToken): Promise<Client> {
const client = await Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
return client;
}
}

View File

@@ -0,0 +1 @@
export const USER_MODULE_OPTIONS = 'USER_MODULE_OPTIONS'

View File

@@ -0,0 +1,76 @@
import {
Controller,
Get,
Headers,
Query,
StreamableFile,
UseGuards,
} from '@nestjs/common';
import { UserService } from './user.service';
import { Client as MsGraphClient } from '@microsoft/microsoft-graph-client';
import { AuthGuard } from '../auth/auth.gaurd';
@Controller('user')
export class UserController {
constructor(
private readonly userService: UserService
) {}
@Get('photo')
@UseGuards(AuthGuard)
async getProfilePhoto(@Headers() headers: any): Promise<StreamableFile> {
try {
const graphToken: string = await this.userService.getMsGraphAuth(
headers.authorization.replace('Bearer ', ''),
['user.read']
);
const client: MsGraphClient =
await this.userService.getMsGraphClientDelegated(graphToken);
const blob: Blob = await client.api(`me/photos('48x48')/$value`).get();
const arrayBuffer: ArrayBuffer = await blob.arrayBuffer();
const buffer: Buffer = Buffer.from(arrayBuffer);
return new StreamableFile(buffer, {
type: 'application/json',
disposition: `attachment; filename="user_photo.png"`
});
} catch (error) {
return error;
}
}
@Get('profile')
@UseGuards(AuthGuard)
async getUserProfile(@Headers() headers: any): Promise<any> {
try {
const graphToken: string = await this.userService.getMsGraphAuth(
headers.authorization.replace('Bearer ', ''),
['user.read']
);
const client: MsGraphClient =
await this.userService.getMsGraphClientDelegated(graphToken);
const userProfile = await client.api(`me`).get();
return userProfile;
} catch (error) {
return error;
}
}
@Get('search')
@UseGuards(AuthGuard)
async searchUsers(
@Headers() headers: any,
@Query('search') search: any
): Promise<any> {
try {
const accessToken: string = headers.authorization.replace('Bearer ', '');
const personSearchResults: any[] =
await this.userService.searchUsers(accessToken, search);
return personSearchResults;
} catch (error) {
return error;
}
}
}

View File

@@ -1,6 +1,5 @@
export interface AppConfigOptions { export interface UserModuleOptions {
url: string;
tenantId: string; tenantId: string;
clientId: string; clientId: string;
clientSecret: string; clientSecret: string;
} }

View File

@@ -0,0 +1,4 @@
import { ConfigurableModuleBuilder } from '@nestjs/common';
import { UserModuleOptions } from './user.interface';
export const { ConfigurableModuleClass, ASYNC_OPTIONS_TYPE, MODULE_OPTIONS_TOKEN, OPTIONS_TYPE } = new ConfigurableModuleBuilder<UserModuleOptions>().build()

View File

@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { ConfigurableModuleClass } from './user.module-definition';
import { UserController } from './user.controller';
@Module({
controllers: [UserController],
providers: [UserService],
exports: [UserService]
})
export class UserModule extends ConfigurableModuleClass {}

View File

@@ -0,0 +1,96 @@
import { Inject, Injectable, StreamableFile } from '@nestjs/common';
import { UserModuleOptions } from './user.interface';
import { Client } from '@microsoft/microsoft-graph-client';
import { AuthenticationResult, ConfidentialClientApplication, OnBehalfOfRequest } from '@azure/msal-node';
import { MODULE_OPTIONS_TOKEN } from './user.module-definition';
@Injectable()
export class UserService {
constructor(@Inject(MODULE_OPTIONS_TOKEN) private userModuleOptions: UserModuleOptions) {}
async getMsGraphAuth(accessToken: string, scopes: string[]): Promise<string> {
try {
const oboRequest: OnBehalfOfRequest = {
oboAssertion: accessToken,
scopes: scopes
}
const cca = new ConfidentialClientApplication({
auth: {
clientId: this.userModuleOptions.clientId,
clientSecret: this.userModuleOptions.clientSecret,
authority: `https://login.microsoftonline.com/${this.userModuleOptions.tenantId}`
}
});
const authenticationResult: AuthenticationResult = await cca.acquireTokenOnBehalfOf(oboRequest);
return authenticationResult.accessToken
} catch (error) {
return error
}
}
async getMsGraphClientDelegated(accessToken): Promise<Client> {
const client = await Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
return client;
}
async getProfilePhoto(accessToken: string, scopes: string[]): Promise<Buffer> {
try {
const graphToken: string = await this.getMsGraphAuth(accessToken, scopes);
const client: Client = await this.getMsGraphClientDelegated(graphToken);
const blob: Blob = await client.api(`me/photos('48x48)/$value`).get();
const arrayBuffer: ArrayBuffer = await blob.arrayBuffer();
const buffer: Buffer = Buffer.from(arrayBuffer);
return buffer;
} catch (error) {
return error;
}
}
async getUserProfile(accessToken): Promise<any> {
try {
const graphToken: string = await this.getMsGraphAuth(accessToken, ['user.read']);
const client: Client = await this.getMsGraphClientDelegated(graphToken);
const userProfile = await client.api(`me`).get();
return userProfile
} catch (error) {
return error;
}
}
async searchUsers(accessToken, searchText: string): Promise<any> {
try {
const graphToken: string = await this.getMsGraphAuth(accessToken, ['user.read']);
const client: Client = await this.getMsGraphClientDelegated(graphToken);
const results: any = await client
.api('users')
.header('ConsistencyLevel', 'eventual')
.search(`"displayName:${searchText}"`)
.orderby('displayName')
.select(['displayName', 'userPrincipalName'])
.get();
let personResults: any[];
if (results.value) {
personResults = results.value.filter((result: any) => {
if (result.userPrincipalName !== null) {
return result;
}
});
} else {
personResults = []
}
return personResults;
} catch (error) {
throw new Error(error);
}
}
}

View File

@@ -0,0 +1,9 @@
export class CustomError extends Error {
statusCode: number;
constructor(message, name, statusCode) {
super(message);
this.name = name;
this.statusCode = statusCode;
}
}

3024
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "@noahspan/noahspan-modules", "name": "@noahspan/noahspan-modules",
"version": "0.3.9", "version": "1.2.0",
"description": "", "description": "",
"author": "", "author": "",
"license": "UNLICENSED", "license": "UNLICENSED",
@@ -24,28 +24,29 @@
"test:e2e": "jest --config ./test/jest-e2e.json" "test:e2e": "jest --config ./test/jest-e2e.json"
}, },
"dependencies": { "dependencies": {
"@azure/app-configuration": "^1.6.0",
"@azure/data-tables": "^13.2.2",
"@azure/identity": "^4.2.0", "@azure/identity": "^4.2.0",
"@azure/msal-node": "^2.9.2", "@azure/msal-node": "^2.9.2",
"@microsoft/microsoft-graph-client": "^3.0.7", "@microsoft/microsoft-graph-client": "^3.0.7",
"@nestjs/common": "^10.0.0", "@nestjs/common": "^11.0.11",
"@nestjs/core": "^10.0.0", "@nestjs/core": "^11.0.11",
"@nestjs/passport": "^10.0.3", "@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^10.0.0", "@nestjs/platform-express": "^11.0.11",
"axios": "^1.7.2", "axios": "^1.7.2",
"passport-azure-ad": "^4.3.5", "passport": "^0.7.0",
"reflect-metadata": "^0.2.0", "passport-jwt": "^4.0.1",
"passport-openidconnect": "^0.1.2",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1" "rxjs": "^7.8.1"
}, },
"devDependencies": { "devDependencies": {
"@microsoft/microsoft-graph-types": "^2.40.0", "@microsoft/microsoft-graph-types": "^2.40.0",
"@nestjs/cli": "^10.0.0", "@nestjs/cli": "^11.0.5",
"@nestjs/schematics": "^10.0.0", "@nestjs/schematics": "^11.0.2",
"@nestjs/testing": "^10.0.0", "@nestjs/testing": "^11.0.11",
"@types/express": "^4.17.17", "@types/express": "^4.17.17",
"@types/jest": "^29.5.2", "@types/jest": "^29.5.2",
"@types/node": "^20.3.1", "@types/node": "^20.3.1",
"@types/passport-openidconnect": "^0.1.3",
"@types/supertest": "^6.0.0", "@types/supertest": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^6.0.0", "@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0", "@typescript-eslint/parser": "^6.0.0",