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

refactor: update code to remove errors #79

Merged
merged 1 commit into from
Sep 8, 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
5 changes: 5 additions & 0 deletions src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,9 @@ export class AppController {
async createAdmin(@Body() data: { username: string; password: string }) {
return await this.appService.createAdmin(data);
}

@Post('login')
async confirmLogin(@Req() req: Request){
console.log(req.body);
}
}
3 changes: 2 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { TenantModule } from './tenant/tenant.module';
import { ApiKeysModule } from './api-keys/api-keys.module';
import { UtilsService } from './utils/utils.service';
import { OidcModule } from './oidc/oidc.module';
import { InteractionController } from './oidc/interaction/interaction.controller';

@Module({
imports: [
Expand All @@ -39,7 +40,7 @@ import { OidcModule } from './oidc/oidc.module';
TenantModule,
ApiKeysModule,
],
controllers: [AppController],
controllers: [AppController, InteractionController],
providers: [AppService, PrismaService, MemoryMonitorService, UtilsService],
})
export class AppModule {}
4 changes: 2 additions & 2 deletions src/key/key.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ export class KeyService {
keyFields = (key: any) => ({
privateKey: jwkToPem(key, { private: true }),
publicKey: jwkToPem(key),
data: JSON.stringify(this.removeSensitiveRSAFields(key)),
data: JSON.stringify(key),
});
break;
case 'ES256':
Expand All @@ -289,7 +289,7 @@ export class KeyService {
keyFields = (key: any) => ({
privateKey: jwkToPem(key, { private: true }),
publicKey: jwkToPem(key),
data: JSON.stringify(this.removeSensitiveECFields(key)),
data: JSON.stringify(key),
});
break;
default:
Expand Down
36 changes: 36 additions & 0 deletions src/oidc/interaction/interaction.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Controller, Get, Param, Post, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';

@Controller('interaction')
export class InteractionController {
@Get(':id')
serveLoginPage(@Param('id') id: string, @Res() res: Response) {
const loginHtml = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<style>
body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
form { background: #f0f0f0; padding: 20px; border-radius: 5px; }
input { display: block; margin: 10px 0; padding: 5px; width: 200px; }
button { background: #007bff; color: white; border: none; padding: 10px; cursor: pointer; }
</style>
</head>
<body>
<form action="/login" method="POST">
<h2>Login</h2>
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="hidden" name="interaction_id" value="${id}">
<button type="submit">Log In</button>
</form>
</body>
</html>
`;

res.type('text/html').send(loginHtml);
}
}
18 changes: 9 additions & 9 deletions src/oidc/oidc.adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ const types = [
const prepare = (doc: OidcModel) => {
doc.payload = JSON.parse(doc.payload);
const isPayloadJson =
doc.payload &&
typeof doc.payload === 'object' &&
!Array.isArray(JSON.parse(doc.payload));

const payload = isPayloadJson ? JSON.parse(doc.payload) : {};
doc.payload &&
typeof doc.payload === 'object' &&
!Array.isArray(doc.payload);
const payload = isPayloadJson ? doc.payload : {};

return {
...payload,
Expand All @@ -56,7 +56,7 @@ export class PrismaAdapter implements Adapter {
constructor(name: string) {
this.type = types[name];
this.name = name;
//console.log('Constructor', name);
// console.log('Constructor', name);
}

async upsert(
Expand All @@ -72,7 +72,7 @@ export class PrismaAdapter implements Adapter {
uid: payload.uid,
expiresAt: expiresAt(expiresIn),
};
//console.log('upsert', id, this.name, payload);
// console.log('upsert', id, this.name, payload);
await prisma.oidcModel.upsert({
where: {
id_type: {
Expand All @@ -91,7 +91,7 @@ export class PrismaAdapter implements Adapter {
}

async find(id: string): Promise<AdapterPayload | undefined> {
//console.log('find', this.name, id);
// console.log('find', this.name, id);
if (this.name === 'Client') {
// can do domain pinning here
const client = await PrismaAdapter.prismaService.application.findUnique({
Expand Down Expand Up @@ -134,7 +134,7 @@ export class PrismaAdapter implements Adapter {
// do domain pinning here or cors?
if (!client) return undefined;
}

if (!doc || (doc.expiresAt && doc.expiresAt < new Date())) {
return undefined;
}
Expand Down
183 changes: 93 additions & 90 deletions src/oidc/oidc.config.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Injectable } from '@nestjs/common';
import { Configuration } from 'oidc-provider';
import Provider, { Configuration, Interaction, JWKS } from 'oidc-provider';
import { PrismaAdapter } from './oidc.adapter';
import Account from './findAccount';
import { PrismaService } from 'src/prisma/prisma.service';
Expand All @@ -8,111 +8,114 @@ import { ApplicationDataDto } from 'src/application/application.dto';
@Injectable()
export class OidcConfigService {
private provider;
private client_ttlMap: Map<string, ApplicationDataDto>;
private configuration: Configuration = {
interactions: {
url(ctx, interaction) {
return `/interaction/${interaction.uid}`;
},
},
adapter: (modelName: string) => new PrismaAdapter(modelName),
findAccount: (ctx, sub, token) =>
Account.findAccount(ctx as unknown as any, sub, token),
claims: {
address: ['address'],
email: ['email', 'email_verified'],
phone: ['phone_number', 'phone_number_verified'],
profile: [
'birthdate',
'family_name',
'gender',
'given_name',
'locale',
'middle_name',
'name',
'nickname',
'picture',
'preferred_username',
'profile',
'updated_at',
'website',
'zoneinfo',
],
},
clientBasedCORS(ctx, origin, client) {
console.log('CLORS', ctx, origin, client);
return false;
},
pkce: {
required(ctx, client) {
return false;
private async returnConfiguration(): Promise<Configuration> {
const client_ttlMap: Map<string, ApplicationDataDto> = await this.returnTTL();

const jwksArray = await this.prismaService.key.findMany();
const jwksFinal = jwksArray.map(jwk => JSON.parse(jwk.data));
const jwks: JWKS = jwksFinal.length > 0 ? {keys: jwksFinal}: undefined;
return {
interactions: {
url(ctx, interaction) {
return `/interaction/${interaction.uid}`;
},
},
},
features: {
introspection: { enabled: true },
jwtIntrospection: { enabled: true },
userinfo: { enabled: true },
// resource Indicators?
revocation: { enabled: true },
devInteractions: {
enabled: true,
adapter: (modelName: string) => new PrismaAdapter(modelName),
findAccount: (ctx, sub, token) =>
Account.findAccount(ctx as unknown as any, sub, token),
claims: {
address: ['address'],
email: ['email', 'email_verified'],
phone: ['phone_number', 'phone_number_verified'],
profile: [
'birthdate',
'family_name',
'gender',
'given_name',
'locale',
'middle_name',
'name',
'nickname',
'picture',
'preferred_username',
'profile',
'updated_at',
'website',
'zoneinfo',
],
},
},
issueRefreshToken: async (ctx, client, code) => {
return true;
},
// loadExistingGrant(ctx) { // runs after giving consent
// console.log(ctx);
// return undefined;
// },
ttl: {
AccessToken: (ctx, token, client) => {
const clientData = this.client_ttlMap.get(client.clientId);
return clientData.jwtConfiguration.timeToLiveInSeconds || 10000;
clientBasedCORS(ctx, origin, client) {
console.log('CLORS', ctx, origin, client);
return false;
},
RefreshToken: (ctx, token, client) => {
const clientData = this.client_ttlMap.get(client.clientId);
return (
clientData.jwtConfiguration.refreshTokenTimeToLiveInMinutes * 60 ||
60000
);
pkce: {
required(ctx, client) {
return false;
},
},
Grant: (ctx, token, client) => {
return 300000;
features: {
introspection: { enabled: true },
jwtIntrospection: { enabled: true },
userinfo: { enabled: true },
// resource Indicators?
revocation: { enabled: true },
devInteractions: {
enabled: false,
},
},
AuthorizationCode: (ctx, token, client) => {
return 300000;
issueRefreshToken: async (ctx, client, code) => {
return true;
},
Session: (ctx, token, client) => {
return 300000;
}, // id token ka set kr
IdToken: (ctx, token, client) => {
return 300000;
// loadExistingGrant(ctx) { // runs after giving consent
// console.log(ctx);
// return undefined;
// },
ttl: {
AccessToken: (ctx, token, client) => {
const clientData = client_ttlMap.get(client.clientId);
return clientData.jwtConfiguration.timeToLiveInSeconds || 10000;
},
RefreshToken: (ctx, token, client) => {
const clientData = client_ttlMap.get(client.clientId);
return (
clientData.jwtConfiguration.refreshTokenTimeToLiveInMinutes * 60 ||
60000
);
},
Grant: (ctx, token, client) => {
return 300000;
},
AuthorizationCode: (ctx, token, client) => {
return 300000;
},
Session: (ctx, token, client) => {
return 300000;
}, // id token ka set kr
IdToken: (ctx, token, client) => {
return 300000;
},
},
},
};

constructor(private readonly prismaService: PrismaService) {
this.client_ttlMap = new Map();
this.prismaService.application.findMany().then((data) => {
data.forEach((client) => {
this.client_ttlMap.set(
client.id,
JSON.parse(client.data) as ApplicationDataDto,
);
});
});
jwks,
};
}

constructor(private readonly prismaService: PrismaService) {}

async returnOidc() {
if (typeof this.provider !== 'undefined') {
return this.provider;
}
const mod = await eval(`import('oidc-provider')`);
this.provider = mod.default;
const oidc = new this.provider(process.env.FULL_URL, this.configuration);
const configuration: Configuration = await this.returnConfiguration();
const oidc = new this.provider(process.env.FULL_URL, configuration);
return oidc;
}

private async returnTTL() {}
private async returnTTL() {
const client_ttlMap: Map<string, ApplicationDataDto> = new Map();
const clients = await this.prismaService.application.findMany();
clients.forEach(client => client_ttlMap.set(client.id,JSON.parse(client.data) as ApplicationDataDto))
return client_ttlMap;
}
}
34 changes: 34 additions & 0 deletions swagger-spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,40 @@
]
}
},
"/login": {
"post": {
"operationId": "AppController_confirmLogin",
"parameters": [],
"responses": {
"201": {
"description": ""
}
},
"tags": [
"OIDC Wrapper"
]
}
},
"/interaction/{id}": {
"get": {
"operationId": "InteractionController_serveLoginPage",
"parameters": [
{
"name": "id",
"required": true,
"in": "path",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": ""
}
}
}
},
"/oidc/*": {
"get": {
"operationId": "OidcController_mountedOidc_get",
Expand Down
Loading