From b72f4340bafdf697b8c1f5c982771d3cbe2a65ba Mon Sep 17 00:00:00 2001 From: vikastc Date: Wed, 10 Jan 2024 16:44:19 +0530 Subject: [PATCH] Update document by cred identifier Signed-off-by: vikastc --- src/controller/credential_controller.ts | 156 ++++++++++++------------ src/controller/schema_controller.ts | 9 +- src/entity/Cred.ts | 3 + src/index.ts | 18 +-- src/init.ts | 10 +- 5 files changed, 108 insertions(+), 88 deletions(-) diff --git a/src/controller/credential_controller.ts b/src/controller/credential_controller.ts index dd3b712..60c3c48 100644 --- a/src/controller/credential_controller.ts +++ b/src/controller/credential_controller.ts @@ -7,6 +7,9 @@ import { authorIdentity, addDelegateAsRegistryDelegate, issuerKeysProperty, + delegateDid, + delegateSpaceAuth, + delegateKeysProperty, } from '../init'; import { getConnection } from 'typeorm'; @@ -14,20 +17,12 @@ import { Cred } from '../entity/Cred'; const { CHAIN_SPACE_ID, CHAIN_SPACE_AUTH } = process.env; export async function issueVD(req: express.Request, res: express.Response) { - const data = req.body; - - if (!data.schemaId) { - return res - .status(400) - .json({ error: 'schemaId is a required field and should be a string' }); - } - if (!authorIdentity) { await addDelegateAsRegistryDelegate(); } try { - const newCredContent = data; + const newCredContent = req.body; newCredContent.issuanceDate = new Date().toISOString(); const serializedCred = Cord.Utils.Crypto.encodeObjectAsStr(newCredContent); const credHash = Cord.Utils.Crypto.hashStr(serializedCred); @@ -36,7 +31,7 @@ export async function issueVD(req: express.Request, res: express.Response) { credHash, CHAIN_SPACE_ID as `space:cord:${string}`, issuerDid.uri, - data.schemaId + req.params.id as `schema:cord:${string}` ); console.dir(statementEntry, { @@ -58,6 +53,7 @@ export async function issueVD(req: express.Request, res: express.Response) { console.log(`✅ Statement element registered - ${statement}`); const cred = new Cred(); + cred.schemaId = req.params.id; cred.identifier = statement; cred.active = true; cred.fromDid = issuerDid.uri; @@ -65,13 +61,17 @@ export async function issueVD(req: express.Request, res: express.Response) { cred.newCredContent = newCredContent; cred.credentialEntry = statementEntry; - await getConnection().manager.save(cred); - return res - .status(200) - .json({ result: 'success', identifier: cred.identifier }); + if (statement) { + await getConnection().manager.save(cred); + return res + .status(200) + .json({ result: 'success', identifier: cred.identifier }); + } else { + return res.status(400).json({ error: 'Credential not issued' }); + } } catch (err) { console.log('Error: ', err); - throw new Error('VD not issued'); + throw new Error('Error in VD issuence'); } // const url: any = WALLET_URL; @@ -107,78 +107,82 @@ export async function getCredById(req: express.Request, res: express.Response) { .getRepository(Cred) .findOne({ identifier: req.params.id }); + if (!cred) { + return res.status(400).json({ error: 'Cred not found' }); + } + return res.status(200).json({ credential: cred }); } catch (error) { console.log('Error: ', error); - return res.status(400).json({ status: 'Credential not found' }); + throw new Error('Error in cred fetch'); } } -// export async function updateCred(req: express.Request, res: express.Response) { -// const data = req.body; +export async function updateCred(req: express.Request, res: express.Response) { + const data = req.body; -// try { -// let schemaProp: any = undefined; -// let credProp: any = undefined; - -// const updatedContent = data.property; - -// if (data.schemaId) { -// const schemaId = data.schemaId ? data.schemaId : ''; -// schemaProp = await getSchema(schemaId); -// if (!schemaProp) { -// return res.status(400).json({ result: 'No Schema found' }); -// } -// } - -// if (data.credId) { -// const credId = data.credId ? data.credId : ''; -// credProp = await getCredential(credId); -// if (!credProp) { -// return res.status(400).json({ result: 'No Cred found' }); -// } -// } - -// const schema = JSON.parse(schemaProp.cordSchema); -// const document = JSON.parse(credProp.credential); - -// const keyUri = -// `${issuerDid.uri}${issuerDid.authentication[0].id}` as Cord.DidResourceUri; - -// const updatedDocument: any = await updateStream( -// document, -// updatedContent, -// schema, -// async ({ data }) => ({ -// signature: issuerKeys.authentication.sign(data), -// keyType: issuerKeys.authentication.type, -// keyUri, -// }), -// issuerDid?.uri, -// authorIdentity, -// issuerKeys -// ); + try { + const cred = await getConnection() + .getRepository(Cred) + .findOne({ identifier: req.params.id }); -// credProp.identifier = updatedDocument.identifier; -// credProp.credential = JSON.stringify(updatedDocument); -// credProp.hash = updatedDocument.documentHash; -// credProp.details = { -// meta: 'endpoint-received', -// }; + if (!cred) { + return res.status(400).json({ error: 'Cred not found' }); + } + + console.log(`\n❄️ Statement Updation `); + let updateCredContent = cred.newCredContent; + updateCredContent.issuanceDate = new Date().toISOString(); + updateCredContent.property = data.property; + const serializedUpCred = + Cord.Utils.Crypto.encodeObjectAsStr(updateCredContent); + const upCredHash = Cord.Utils.Crypto.hashStr(serializedUpCred); + + const updatedStatementEntry = Cord.Statement.buildFromUpdateProperties( + cred.credentialEntry.elementUri, + upCredHash, + CHAIN_SPACE_ID as `space:cord:${string}`, + delegateDid.uri + ); -// await getConnection().manager.save(credProp); + console.dir(updatedStatementEntry, { + depth: null, + colors: true, + }); -// console.log('\n✅ Document updated!'); + const updatedStatement = await Cord.Statement.dispatchUpdateToChain( + updatedStatementEntry, + delegateDid.uri, + authorIdentity, + delegateSpaceAuth as Cord.AuthorizationUri, + async ({ data }) => ({ + signature: delegateKeysProperty.authentication.sign(data), + keyType: delegateKeysProperty.authentication.type, + }) + ); + console.log(`✅ Statement element registered - ${updatedStatement}`); -// return res.status(200).json({ -// result: 'Updated successufully', -// identifier: credProp.identifier, -// }); -// } catch (error) { -// console.log('error: ', error); -// return res.status(400).json({ err: error }); -// } -// } + if (updatedStatement) { + cred.identifier = updatedStatement; + cred.credHash = upCredHash; + cred.newCredContent = updateCredContent; + cred.credentialEntry = updatedStatementEntry; + + await getConnection().manager.save(cred); + + console.log('\n✅ Document updated!'); + + return res.status(200).json({ + result: 'Updated successufully', + identifier: cred.identifier, + }); + } + return res.status(400).json({ error: 'Document not updated' }); + } catch (error) { + console.log('error: ', error); + throw new Error('Error in updating document'); + } +} // export async function revokeCred(req: express.Request, res: express.Response) { // const data = req.body; diff --git a/src/controller/schema_controller.ts b/src/controller/schema_controller.ts index 91f1fdf..0be3c53 100644 --- a/src/controller/schema_controller.ts +++ b/src/controller/schema_controller.ts @@ -71,9 +71,8 @@ export async function createSchema( result: 'SUCCESS', identifier: schemaData.identifier, }); - } else { - res.status(400).json({ error: 'SchemaDetails not created' }); } + return res.status(400).json({ error: 'SchemaDetails not created' }); } catch (error) { console.log('err: ', error); throw new Error('Schema not created'); @@ -89,9 +88,13 @@ export async function getSchemaById( .getRepository(Schema) .findOne({ identifier: req.params.id }); + if (!schema) { + return res.status(400).json({ error: 'Schema not found' }); + } + return res.status(200).json({ schema: schema }); } catch (error) { console.log('err: ', error); - return res.status(400).json({ status: 'Schema not found' }); + throw new Error('Schema not found'); } } diff --git a/src/entity/Cred.ts b/src/entity/Cred.ts index 4738515..9808f09 100644 --- a/src/entity/Cred.ts +++ b/src/entity/Cred.ts @@ -25,6 +25,9 @@ export class Cred { @Column() active?: boolean; + @Column() + schemaId?: string; + @Column() identifier?: string; diff --git a/src/index.ts b/src/index.ts index da7738c..82aa67c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,7 @@ import { createSchema, getSchemaById } from './controller/schema_controller'; import { createConnection } from 'typeorm'; import { dbConfig } from './dbconfig'; import { addDelegateAsRegistryDelegate } from './init'; -import { issueVD } from './controller/credential_controller'; +import { getCredById, issueVD, updateCred } from './controller/credential_controller'; const app = express(); export const { PORT } = process.env; @@ -18,19 +18,21 @@ app.use(express.json()); const credentialRouter = express.Router({ mergeParams: true }); const schemaRouter = express.Router({ mergeParams: true }); -credentialRouter.post('/', async (req, res) => { +credentialRouter.post('/:id', async (req, res) => { return await issueVD(req, res); }); -// credentialRouter.get('/:id', async (req, res) => { -// return await getCredById(req, res); -// }); +credentialRouter.get('/:id', async (req, res) => { + return await getCredById(req, res); +}); + +credentialRouter.put('/update/:id', async (req, res) => { + return await updateCred(req, res); +}); + // credentialRouter.post('/revoke', async (req, res) => { // return await revokeCred(req, res); // }); -// credentialRouter.put('/update', async (req, res) => { -// return await updateCred(req, res); -// }); schemaRouter.post('/', async (req, res) => { return await createSchema(req, res); diff --git a/src/init.ts b/src/init.ts index 6ab14f3..1d9503d 100644 --- a/src/init.ts +++ b/src/init.ts @@ -21,6 +21,9 @@ const { export let authorIdentity: any = undefined; export let issuerDid: any = undefined; export let issuerKeysProperty: any = undefined; +export let delegateDid: any = undefined; +export let delegateKeysProperty: any = undefined; +export let delegateSpaceAuth: any = undefined; function generateKeyAgreement(mnemonic: string) { const secretKeyPair = ed25519PairFromSeed(mnemonicToMiniSecret(mnemonic)); @@ -151,6 +154,9 @@ export async function createDid( throw new Error('DID was not successfully created.'); } + delegateDid = document; + delegateKeysProperty = delegateKeys; + return { mnemonic, delegateKeys, document }; } catch (err) { console.log('Error: ', err); @@ -231,9 +237,11 @@ export async function addDelegateAsRegistryDelegate() { }) ); + delegateSpaceAuth = delegateAuth; + console.log(`✅ Space Authorization added!`); - return { delegateMnemonic, delegateAuth }; + return { delegateMnemonic }; } catch (error) { console.log('err: ', error); throw new Error('Failed to create Delegate Registry');