Skip to content

Commit

Permalink
feat: Refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
DaevMithran committed Jun 7, 2023
1 parent 5777b9a commit da3a336
Show file tree
Hide file tree
Showing 12 changed files with 285 additions and 203 deletions.
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
2 changes: 1 addition & 1 deletion src/controllers/issuer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export class IssuerController {
let resourcePayload: Partial<MsgCreateResourcePayload> = {}
try {
// check if did is registered on the ledger
let resolvedDocument = await Identity.instance.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 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']
});
})
}
}
12 changes: 6 additions & 6 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 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
2 changes: 0 additions & 2 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 Down
174 changes: 174 additions & 0 deletions src/services/identity/agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import {
createAgent,
CredentialPayload,
DIDDocument,
IAgentPlugin,
IDIDManager,
IIdentifier,
IKeyManager,
IResolver,
IVerifyResult,
ManagedKeyInfo,
MinimalImportableIdentifier,
MinimalImportableKey,
TAgent,
VerifiableCredential,
VerifiablePresentation,
} from '@veramo/core'

import { Cheqd, getResolver as CheqdDidResolver, ResourcePayload } from '@cheqd/did-provider-cheqd'
import { CheqdNetwork } from '@cheqd/sdk'

import { cheqdDidRegex, CreateAgentRequest, CredentialRequest, VeramoAgent } from '../../types/types.js'
import { VC_PROOF_FORMAT, VC_REMOVE_ORIGINAL_FIELDS } from '../../types/constants.js'
import { KeyManager } from '@veramo/key-manager'
import { DIDStore, KeyStore } from '@veramo/data-store'
import { DIDManager } from '@veramo/did-manager'
import { DIDResolverPlugin } from '@veramo/did-resolver'
import { Resolver, ResolverRegistry } from 'did-resolver'
import { CredentialPlugin } from '@veramo/credential-w3c'
import { CredentialIssuerLD, LdDefaultContexts, VeramoEd25519Signature2018 } from '@veramo/credential-ld'

export class Veramo {

static instance = new Veramo()

public createVeramoAgent({ providers, kms, dbConnection, cheqdProviders, enableResolver, enableCredential }: CreateAgentRequest) : VeramoAgent {
const plugins: IAgentPlugin[] = []

if(providers) {
plugins.push(new DIDManager({
store: new DIDStore(dbConnection),
defaultProvider: 'did:cheqd:testnet',
providers
}))
}

if(kms) {
plugins.push(new KeyManager({
store: new KeyStore(dbConnection),
kms
}))
}

if(cheqdProviders) {
plugins.push(new Cheqd({
providers: cheqdProviders
}))
}

if (enableResolver) {
plugins.push(
new DIDResolverPlugin({
resolver: new Resolver({
...CheqdDidResolver({ url: process.env.RESOLVER_URL }) as ResolverRegistry
})
})
)
}

if (enableCredential) {
plugins.push(
new CredentialPlugin(),
new CredentialIssuerLD({
contextMaps: [LdDefaultContexts],
suites: [new VeramoEd25519Signature2018()]
})
)
}
return createAgent({ plugins })
}

async createKey(agent: TAgent<IKeyManager>, type: 'Ed25519' | 'Secp256k1'='Ed25519'): Promise<ManagedKeyInfo> {
const [kms] = await agent.keyManagerGetKeyManagementSystems()
const key = await agent.keyManagerCreate({
type: type || 'Ed25519',
kms,
})
return key
}

async getKey(agent: TAgent<IKeyManager>, kid: string) {
return await agent.keyManagerGet({ kid })
}

async createDid(agent: TAgent<IDIDManager>, network: string, didDocument: DIDDocument): Promise<IIdentifier> {
try {
const [kms] = await agent.keyManagerGetKeyManagementSystems()

const identifier: IIdentifier = await agent.didManagerCreate({
provider: `did:cheqd:${network}`,
kms,
options: {
document: didDocument
}
})
return identifier
} catch (error) {
throw new Error(`${error}`)
}
}

async listDids(agent: TAgent<IDIDManager>) {
return (await agent.didManagerFind()).map((res)=>res.did)
}

async resolveDid(agent: TAgent<IResolver>, did: string) {
return await agent.resolveDid({ didUrl: did })
}

async getDid(agent: TAgent<IDIDManager>, did: string) {
return await agent.didManagerGet({ did })
}

async importDid(agent: TAgent<IDIDManager>, did: string, privateKeyHex: string, publicKeyHex: string): Promise<IIdentifier> {
const [kms] = await agent.keyManagerGetKeyManagementSystems()

if (!did.match(cheqdDidRegex)) {
throw new Error('Invalid DID')
}

const key: MinimalImportableKey = { kms: kms, type: 'Ed25519', privateKeyHex, publicKeyHex }
const identifier: IIdentifier = await agent.didManagerImport({ keys: [key], did, controllerKeyId: key.kid } as MinimalImportableIdentifier)
return identifier
}

async createResource(agent: VeramoAgent, network: string, payload: ResourcePayload) {
try {
const [kms] = await agent.keyManagerGetKeyManagementSystems()

const result: boolean = await agent.cheqdCreateLinkedResource({
kms,
payload,
network: network as CheqdNetwork
})
return result
} catch (error) {
throw new Error(`${error}`)
}
}

async createCredential(agent: VeramoAgent, credential: CredentialPayload, format: CredentialRequest['format']): Promise<VerifiableCredential> {
try {
const verifiable_credential = await agent.createVerifiableCredential(
{
save: false,
credential,
proofFormat: format == 'jsonld' ? 'lds' : VC_PROOF_FORMAT,
removeOriginalFields: VC_REMOVE_ORIGINAL_FIELDS
}
)
return verifiable_credential
} catch (error) {
throw new Error(`${error}`)
}
}

async verifyCredential(agent: VeramoAgent, credential: string | VerifiableCredential): Promise<IVerifyResult> {
return await agent.verifyCredential({ credential, fetchRemoteContexts: true })
}

async verifyPresentation(agent: VeramoAgent, presentation: VerifiablePresentation | string): Promise<IVerifyResult> {
return await agent.verifyPresentation({ presentation, fetchRemoteContexts: true })
}
}
Loading

0 comments on commit da3a336

Please sign in to comment.