Skip to content

Commit

Permalink
fix: External db toggle panic (#248)
Browse files Browse the repository at this point in the history
* fix: External db toggle panic

* fix: Null agent condition

* fix: Fix init_agent initialization

* feat: Refactor code
  • Loading branch information
DaevMithran authored Jun 7, 2023
1 parent 1522864 commit a33cd25
Show file tree
Hide file tree
Showing 17 changed files with 336 additions and 244 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { CORS_ERROR_MSG } from './types/constants.js'
import swaggerJSONDoc from '../swagger.json' assert { type: "json" }

import * as dotenv from 'dotenv'
import { Identity } from './services/identity/index.js'
dotenv.config()

class App {
Expand All @@ -28,7 +29,7 @@ class App {

private middleware() {
this.express.use(express.json({ limit: '50mb' }))
this.express.use(express.urlencoded({ extended: false }))
this.express.use(express.urlencoded({ extended: false }))
this.express.use(Helmet())
this.express.use(cors({
origin: function(origin, callback){
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class CredentialController {
]

public async issue(request: Request, response: Response) {
const result = validationResult(request);
const result = validationResult(request)
if (!result.isEmpty()) {
return response.status(400).json({ error: result.array()[0].msg })
}
Expand All @@ -46,7 +46,7 @@ export class CredentialController {
return response.status(405).json({ error: 'Unsupported media type.' })
}

const result = validationResult(request);
const result = validationResult(request)
if (!result.isEmpty()) {
return response.status(400).json({ error: result.array()[0].msg })
}
Expand Down
16 changes: 8 additions & 8 deletions src/controllers/issuer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export class IssuerController {

public async createKey(request: Request, response: Response) {
try {
const key = await Identity.createKey('Ed25519', response.locals.customerId)
const key = await Identity.instance.createKey('Ed25519', response.locals.customerId)
return response.status(200).json(key)
} catch (error) {
return response.status(500).json({
Expand All @@ -57,7 +57,7 @@ export class IssuerController {

public async getKey(request: Request, response: Response) {
try {
const key = await Identity.getKey(request.params.kid, response.locals.customerId)
const key = await Identity.instance.getKey(request.params.kid, response.locals.customerId)
return response.status(200).json(key)
} catch (error) {
return response.status(500).json({
Expand All @@ -83,7 +83,7 @@ export class IssuerController {
if (options.didDocument) {
didDocument = options.didDocument
} else if (verificationMethod) {
const key = await Identity.createKey('Ed25519', response.locals.customerId)
const key = await Identity.instance.createKey('Ed25519', response.locals.customerId)
kids.push(key.kid)
didDocument = generateDidDoc({
verificationMethod: verificationMethod.type,
Expand All @@ -99,7 +99,7 @@ export class IssuerController {
})
}

const did = await Identity.createDid(network, didDocument, response.locals.customerId)
const did = await Identity.instance.createDid(network, didDocument, response.locals.customerId)
return response.status(200).json(did)
} catch (error) {
return response.status(500).json({
Expand All @@ -122,7 +122,7 @@ export class IssuerController {
let resourcePayload: Partial<MsgCreateResourcePayload> = {}
try {
// check if did is registered on the ledger
let resolvedDocument = await Identity.resolveDid(did)
let resolvedDocument: any = await Identity.instance.resolveDid(did)
if(!resolvedDocument?.didDocument || resolvedDocument.didDocumentMetadata.deactivated) {
return response.status(400).send({
error: `${did} is a Deactivated DID`
Expand All @@ -141,7 +141,7 @@ export class IssuerController {
alsoKnownAs
}
network = network || (did.split(':'))[2]
const result = await Identity.createResource( network, resourcePayload, response.locals.customerId)
const result = await Identity.instance.createResource( network, resourcePayload, response.locals.customerId)
if ( result ) {
return response.status(201).json({
resource: resourcePayload
Expand All @@ -162,9 +162,9 @@ export class IssuerController {
try {
let did: any
if(request.params.did) {
did = await Identity.resolveDid(request.params.did)
did = await Identity.instance.resolveDid(request.params.did)
} else {
did = await Identity.listDids(response.locals.customerId)
did = await Identity.instance.listDids(response.locals.customerId)
}

return response.status(200).json(did)
Expand Down
14 changes: 7 additions & 7 deletions src/database/entities/customer.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,26 @@ import { Column, Entity, PrimaryGeneratedColumn, ValueTransformer } from 'typeor
import * as dotenv from 'dotenv'
dotenv.config()

const { ENABLE_EXTERNAL_DB } = process.env;
const { ENABLE_EXTERNAL_DB } = process.env

const arrayToJsonTransformer = (shouldTransform: string): ValueTransformer => {
return {
to: (array: any[]) => {
if (shouldTransform == "false") {
// Convert the array to a JSON string
return JSON.stringify(array);
return JSON.stringify(array)
}
return array;
return array
},
from: (jsonString: string) => {
if (shouldTransform == "false") {
// Parse the JSON string and return the array
return JSON.parse(jsonString);
return JSON.parse(jsonString)
}
return jsonString;
return jsonString
},
};
};
}
}

@Entity('customers')
export class CustomerEntity {
Expand Down
10 changes: 5 additions & 5 deletions src/database/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import { CreateCustomersTable1683723285946 } from '../migrations/CreateCustomers
import * as dotenv from 'dotenv'
dotenv.config()

const { EXTERNAL_DB_CONNECTION_URL, EXTERNAL_DB_CERT } = process.env;
const { EXTERNAL_DB_CONNECTION_URL, EXTERNAL_DB_CERT } = process.env

export interface AbstractDatabase {
setup(): DataSource;
setup(): DataSource
}

export class Memory implements AbstractDatabase {
Expand All @@ -24,13 +24,13 @@ export class Memory implements AbstractDatabase {
migrations: [...migrations],
migrationsRun: true,
logging: ['error', 'info', 'warn']
});
})
}
}

export class Postgres implements AbstractDatabase {
setup(): DataSource {
const { parse } = pkg;
const { parse } = pkg
const config = parse(EXTERNAL_DB_CONNECTION_URL)
if (!(config.host && config.port && config.database)) {
throw new Error(`Error: Invalid Database URL`)
Expand All @@ -49,6 +49,6 @@ export class Postgres implements AbstractDatabase {
migrations: [...migrations, CreateCustomersTable1683723285946],
entities: [...Entities, CustomerEntity],
logging: ['error', 'info', 'warn']
});
})
}
}
14 changes: 7 additions & 7 deletions src/middleware/authentication.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Request, Response, NextFunction } from 'express'
import { expressjwt, Request as JWTRequest } from 'express-jwt'
import { createRemoteJWKSet, jwtVerify } from 'jose';
import { Request as JWTRequest } from 'express-jwt'
import { createRemoteJWKSet, jwtVerify } from 'jose'

import { CustomerService } from '../services/customer.js'
import { IncomingHttpHeaders } from 'http';
import { IncomingHttpHeaders } from 'http'

import * as dotenv from 'dotenv'
dotenv.config()
Expand All @@ -28,8 +28,8 @@ export const extractBearerTokenFromHeaders = ({ authorization }: IncomingHttpHea
throw new Error(`Authorization token type is not supported. Valid type: "${bearerTokenIdentifier}".`)
}

return authorization.slice(bearerTokenIdentifier.length + 1);
};
return authorization.slice(bearerTokenIdentifier.length + 1)
}

export class Authentication {

Expand All @@ -51,7 +51,7 @@ export class Authentication {
}
break
default:
if (request.path != '/account' && !await CustomerService.instance.find(response.locals.customerId, {})) {
if (!['/account', '/', '/store'].includes(request.path) && !await CustomerService.instance.find(response.locals.customerId, {})) {
message = 'Customer not found'
}
break
Expand Down Expand Up @@ -82,7 +82,7 @@ export class Authentication {
// expected audience token, should be the resource indicator of the current API
audience: LOGTO_RESOURCE_URL,
}
);
)

// custom payload logic
response.locals.customerId = payload.sub
Expand Down
6 changes: 3 additions & 3 deletions src/services/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export class Credentials {
credential.expirationDate = request.expirationDate
}

let verifiable_credential = await Identity.createCredential(credential, request.format, agentId)
let verifiable_credential = await Identity.instance.createCredential(credential, request.format, agentId)

if (ENABLE_VERIDA_CONNECTOR === 'true' && request.subjectDid.startsWith('did:vda')) {
await VeridaService.instance.sendCredential(
Expand All @@ -47,13 +47,13 @@ export class Credentials {
}

async verify_credentials(credential: W3CVerifiableCredential | string, agentId: string): Promise<IVerifyResult> {
const result = await Identity.verifyCredential(credential, agentId)
const result = await Identity.instance.verifyCredential(credential, agentId)
delete(result.payload)
return result
}

async verify_presentation(presentation: W3CVerifiablePresentation, agentId: string): Promise<IVerifyResult> {
const result = await Identity.verifyPresentation(presentation, agentId)
const result = await Identity.instance.verifyPresentation(presentation, agentId)
return result
}
}
4 changes: 1 addition & 3 deletions src/services/customer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import { Identity } from './identity/index.js'
import * as dotenv from 'dotenv'
dotenv.config()

const { ENABLE_EXTERNAL_DB } = process.env;

export class CustomerService {
public customerRepository: Repository<CustomerEntity>

Expand All @@ -23,7 +21,7 @@ export class CustomerService {
if(await this.find(customerId, {})) {
throw new Error('Customer exists')
}
const kid = (await Identity.createKey('Secp256k1', customerId)).kid
const kid = (await Identity.instance.createKey('Secp256k1', customerId)).kid
const customer = new CustomerEntity(customerId, kid, getCosmosAccount(kid))
return (await this.customerRepository.insert(customer)).identifiers[0]
}
Expand Down
2 changes: 1 addition & 1 deletion src/services/identity/IIdentity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { CredentialRequest, VeramoAgent } from '../../types/types'
dotenv.config()

export interface IIdentity {
agent: TAgent<any>
agent?: TAgent<any>
privateStore?: AbstractPrivateKeyStore
initAgent(): TAgent<any>
createAgent?(agentId: string): Promise<VeramoAgent>
Expand Down
Loading

0 comments on commit a33cd25

Please sign in to comment.