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

Update document by cred identifier #25

Merged
merged 1 commit into from
Jan 10, 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
156 changes: 80 additions & 76 deletions src/controller/credential_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,22 @@ import {
authorIdentity,
addDelegateAsRegistryDelegate,
issuerKeysProperty,
delegateDid,
delegateSpaceAuth,
delegateKeysProperty,
} from '../init';

import { getConnection } from 'typeorm';
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);
Expand All @@ -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, {
Expand All @@ -58,20 +53,25 @@ 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;
cred.credHash = credHash;
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;
Expand Down Expand Up @@ -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;
Expand Down
9 changes: 6 additions & 3 deletions src/controller/schema_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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');
}
}
3 changes: 3 additions & 0 deletions src/entity/Cred.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ export class Cred {
@Column()
active?: boolean;

@Column()
schemaId?: string;

@Column()
identifier?: string;

Expand Down
18 changes: 10 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
Expand Down
10 changes: 9 additions & 1 deletion src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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');
Expand Down
Loading