Skip to content

Commit

Permalink
Merge pull request #116 from Whats-Cookin/revert-111-dev
Browse files Browse the repository at this point in the history
Revert "Deploying to production"
  • Loading branch information
gvelez17 authored Jul 28, 2024
2 parents 61fcea8 + 44ca2a9 commit 2d91fc7
Show file tree
Hide file tree
Showing 12 changed files with 518 additions and 819 deletions.
27 changes: 8 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Linked Trust Backend

This is an implementation of the OpenTrustClaims schema from https://github.com/blueskyCommunity/OpenTrustClaims/blob/main/open_trust_claim.yaml, and is the backend powering https://live.linkedtrust.us and [dev server](https://live.linkedtrust.us)
This is an implementation of the OpenTrustClaims schema from https://github.com/blueskyCommunity/OpenTrustClaims/blob/main/open_trust_claim.yaml, and is the backend powering https://live.linkedtrust.us

trust_claim_backend is a Node application for adding Claims, and for presenting Nodes and Edges derived from claims in it

Expand All @@ -12,17 +12,7 @@ Claim: a signed set of structured data with the raw claim or attestation, often
Node: an entity that a claim is about. This is created in the app as a view of what a claim is about.
Edge: a representation of a claim that relates to a Node or connects two Nodes. Created in the app as a view of a claim.

## CICD Pipeline with Jenkins

<a name="test, build and deploy"></a> The frontend is fully working with Jenkins CI/CD Integration
The logs can be found on [jenkins last build](http://68.183.144.184:8080/job/Trustclaim_backend/lastBuild/)
And for Auth Details to the pipeline, kindly refer to vault [jenkins logins](https://vault.whatscookin.us/app/passwords/view/63d7e1a5-0fab-45a6-b880-cd55530d7d1d), this creds would help you to gain access into the CI/CD pipeline and figure out why the test didn't run as it should, and also review the console outputs to figure out what the issue might be.

For SSH Access into the dev server, kindly refer to this creds in the vault [dev server ssh creds](https://vault.whatscookin.us/app/passwords/view/cbe52954-3f7a-4e5d-9bb7-039389acc42c) this would help you ssh into the dev serverm while inside, the files would be in the `/data/trust_claim_backend` directory and configured with nginx

*NB: The production version of this is available on [live.linkedtrust.us](live.linkedtrust.us)*

## Run the application locally
## Run the application

Running the application in docker is only important if you don't want to set up postgresql server in your pc. If you choose to not use docker in development, then set the postgresql db url and env variables in `.env` file. Check [Env variables](#env-variables). section.

Expand Down Expand Up @@ -185,13 +175,13 @@ DATABASE_URL="postgresql://postgres:postgres@localhost:5432/claim"

Value for `ACCESS_SECRET` and `REFRESH_SECRET` can be anything.

<a name="Review"></a>
## To review the server files
<a name="deploy"></a>
## PoC Deployment

SSH into the server with the private key. If you don't have the key, ask for it in slack.

```
Check vault for ssh creds, url is inserted above
ssh -l ubuntu -i [key] trustclaims.whatscookin.us
```

cd into the project
Expand All @@ -200,11 +190,10 @@ cd into the project
cd /data/trust_claim_backend
```

inspect the running file
Pull the latest master branch from github

```
pm2 status index
pm2 logs index
git pull origin master
```

Run this command to check for possible changes in packages, and install changed packages.
Expand All @@ -220,7 +209,7 @@ sudo su postgres
pg_dump claim > /postgres/backup_filename.sql
```

Then run the following 2 commands to generate artifacts and deploy migrations [This is already implemented in the CI/CD pipeline, but for local, it's needed].
Then run the following 2 commands to generate artifacts and deploy migrations.

```
npx prisma generate
Expand Down
169 changes: 55 additions & 114 deletions __tests__/Intergration.test.ts
Original file line number Diff line number Diff line change
@@ -1,148 +1,89 @@
import request from "supertest";
import { app } from "../src";
import request from 'supertest';
import { app } from '../src';
import { prisma } from "../src/db/prisma";
import jwt from "jsonwebtoken";

describe("Integration tests", () => {
describe("POST /claims", () => {
let token: string;

describe("Intergration tests", ()=>{
describe('POST /claims', () => {
let token: string;

beforeAll(() => {
// Generate a JWT token for testing
token = jwt.sign({ aud: 1234 }, process.env.ACCESS_SECRET as string);
});

afterAll(async () => {
// Disconnect Prisma client after all tests
await prisma.$disconnect();

describe('claimPost', () => {
afterAll(async () => {
// Disconnect Prisma client after all tests
await prisma.$disconnect();
});

it('should create a new claim', async () => {
const newClaim = {
subject: 'Test Claim',
claim: 'This is a test claim',
};

const response = await request(app)
.post('/api/claim').set('Authorization', `Bearer ${token}`)
.send(newClaim);

// Verify that the response status is 201 Created
expect(response.status).toBe(201);

// Verify that the response body matches the expected claimData
expect(response.body.subject).toBe(newClaim.subject);
expect(response.body.claim).toBe(newClaim.claim);
}, 10000);
});

it("should create a new claim with its name and images", async () => {
const newClaim = {
claim: "test",
effectiveDate: "2024-04-23",
subject: "www.test.com",
name: "test name",
images: [
{
url: "any test url",
metadata: {
description: "test description",
comment: "test comment"
},
effectiveDate: "2024-04-23",
owner: "test owner",
signature: "test signature"
}
]
};

const response = await request(app)
.post("/api/claim")
.set("Authorization", `Bearer ${token}`)
.send(newClaim);

// Log the response for debugging
// console.log(response.body);

// Verify that the response status is 201 Created
expect(response.status).toBe(201);

// Verify that the response body matches the expected claimData
const responseBody = response.body.claim;
expect(responseBody.subject).toBe(newClaim.subject);
expect(responseBody.claim).toBe(newClaim.claim);

expect(response.body.claimData).toEqual(
expect.objectContaining({
name: newClaim.name
})
);

// Verify the images separately since they are nested
const responseImages = response.body.claimImages;
expect(responseImages).toEqual(
expect.arrayContaining([
expect.objectContaining({
url: newClaim.images[0].url,
metadata: expect.objectContaining(newClaim.images[0].metadata),
effectiveDate: new Date(newClaim.images[0].effectiveDate).toISOString(),
owner: newClaim.images[0].owner,
signature: newClaim.images[0].signature
})
])
);
}, 10000);
});

// claimGet function
describe("GET /claims", () => {
afterAll(async () => {
await prisma.$disconnect();
});

it("should get all claims if no query params provided", async () => {
// const response = await request(app).get("/api/claim"); // not working
const response = await request(app).get("/api/claims-all");

const response = await request(app).get("/api/claim");

expect(response.status).toBe(201);
expect(response.body.claimsData.length).toBeGreaterThan(0);
expect(response.body.claimsData[0].claim).toBeDefined();
expect(response.body.claimsData[0].images).toBeDefined();
expect(response.body.claimsData[0].data).toBeDefined();
expect(response.body.claims.length).toBeGreaterThan(0);
expect(response.body.count).toBeGreaterThan(0);
});


// ======== working

it("should return a specific claim if claimId is provided", async () => {

it('should return a specific claim if claimId is provided', async () => {
const claim = await prisma.claim.findFirst();
const data = await prisma.claimData.findFirst({
where: {
claimId: claim?.id
}
});
const images = await prisma.image.findMany({
where: {
claimId: claim?.id
}

const claimWithDates = Object.assign({}, claim, {
createdAt: "2023-03-12T22:55:40.604Z",
lastUpdatedAt: "2023-03-12T22:55:40.604Z"
});

// const claimWithDates = Object.assign({}, claim, {
// createdAt: "2023-03-12T22:55:40.604Z",
// lastUpdatedAt: "2023-03-12T22:55:40.604Z"
// }); // whyyyyyyyyyyy????????
const response = await request(app).get(`/api/claim/${claim?.id}`);
expect(response.status).toBe(201);
// expect(response.body).toEqual(claimWithDates);
expect(response.body.claim.id).toBe(claim?.id);
expect(response.body.claimData).toEqual(data);
expect(response.body.claimImages).toHaveProperty("length", images.length);
expect(response.body).toEqual(claimWithDates);
});


it("should return filtered claims if search query is provided", async () => {
const searchQuery = "test";
const response = await request(app).get(
`/api/claim/search?search=${searchQuery}`
); // Corrected route


it("should return filtered claims if search query is provided", async () => {
const searchQuery = "claim";
const response = await request(app).get(`/api/claim?search=${searchQuery}`);
expect(response.status).toBe(201);
expect(response.body.claims.length).toBeGreaterThan(0);
expect(response.body.count).toBeGreaterThan(0);
expect(response.body.claims[0].images).toBeDefined();
});


it("should return 404 if claim with provided id does not exist", async () => {
const nonExistentClaimId = 999;

const response = await request(app).get(
`/api/claims/${nonExistentClaimId}`
);


const response = await request(app).get(`/api/claims/${nonExistentClaimId}`);

expect(response.status).toBe(404);
expect(response.body.message).toBe("Not Found");
});
});
});


});
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"@glazed/datamodel": "^0.3.0",
"@glazed/devtools": "^0.2.0",
"@glazed/did-datastore": "^0.3.1",
"@prisma/client": "^5.17.0",
"@prisma/client": "^3.15.0",
"axios": "^0.27.2",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
Expand Down Expand Up @@ -67,7 +67,7 @@
"jest": "^29.5.0",
"jest-mock-extended": "^2.0.4",
"nodemon": "^2.0.16",
"prisma": "^5.17.0",
"prisma": "^3.15.2",
"renamer": "^4.0.0",
"supertest": "^6.3.3",
"swagger-jsdoc": "^6.2.8",
Expand Down
62 changes: 1 addition & 61 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ model Claim {
// splat NormalizedRating
aspect String?
score Float? // -1 to 1
stars Int? // 0 to 5
stars Int? // 0 to 5
// splat Measure
amt Float?
Expand Down Expand Up @@ -127,65 +127,6 @@ model Claim {
lastUpdatedAt DateTime @default(now())
}

// this model is to connect between the claim and the data that supports it
// like the name of the claim, the image, the source, etc.
// maybe to add another atts in future like the urls that can be related to the claim, like the website, the social media, etc.
model ClaimData {
id Int @id @default(autoincrement())
claimId Int @unique
name String
// image Image[]
}

// this model is to store the image of the claim
model Image {
id Int @id @default(autoincrement())
claimId Int // @unique
// claimDataId Int
url String
digestMultibase String?
metadata Json?
effectiveDate DateTime
createdDate DateTime @default(now())
owner String
signature String
// claimData ClaimData @relation(fields: [claimDataId], references: [id])
}


// this is for validator service
model CandidUserInfo {
id Int @id @default(autoincrement())
claimId Int? @unique
firstName String
lastName String
email String
profileURL String
}

model ValidationRequest {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
context String
validatorEmail String
claimId Int
validationStatus ValidationStatus @default(PENDING)
response Boolean? @default(false)
validationDate DateTime?
statement String?
}

enum ValidationStatus {
PENDING
COMPLETED
REJECTED
ABANDONED
}

enum IssuerIdType {
DID
ETH
Expand All @@ -206,4 +147,3 @@ enum HowKnown {
OPINION
OTHER
}

Loading

0 comments on commit 2d91fc7

Please sign in to comment.