Skip to content

Commit

Permalink
🐛 Fixed api keys across the project
Browse files Browse the repository at this point in the history
  • Loading branch information
naelob committed Dec 25, 2023
1 parent e089a44 commit a8b6779
Show file tree
Hide file tree
Showing 9 changed files with 120 additions and 25 deletions.
21 changes: 20 additions & 1 deletion apps/webapp/src/components/api-keys/data/columns.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ import { ApiKey } from "./schema"
import { DataTableColumnHeader } from "../../shared/data-table-column-header"
import { DataTableRowActions } from "../../shared/data-table-row-actions"

function insertDots(originalString: string): string {
if (originalString.length <= 50) {
return originalString;
}
return originalString.substring(0, 50 - 3) + '...';
}

export const columns: ColumnDef<ApiKey>[] = [
{
accessorKey: "name",
Expand All @@ -23,7 +30,19 @@ export const columns: ColumnDef<ApiKey>[] = [
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Token" />
),
cell: ({ row }) => <div className="w-[200px]"><Badge variant="outline">{row.getValue("token")}</Badge></div>,
cell: ({ row }) =>
<div className="w-[400px] flex">
<div className=" truncate mr-2">
<Badge variant="outline">{insertDots(row.getValue("token"))}</Badge>
</div>
<div
className="h-5 w-5 cursor-pointer mt-1"
onClick={() => navigator.clipboard.writeText(row.getValue("token"))}
>
<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M10.6788 2.95419C10.0435 2.53694 9.18829 2.54594 8.51194 3.00541C8.35757 3.11027 8.1921 3.27257 7.7651 3.69957L7.14638 4.31829C6.95112 4.51355 6.63454 4.51355 6.43928 4.31829C6.24401 4.12303 6.24401 3.80645 6.43928 3.61119L7.058 2.99247C7.0725 2.97797 7.08679 2.96366 7.1009 2.94955C7.47044 2.57991 7.70691 2.34336 7.95001 2.17822C8.94398 1.50299 10.2377 1.46813 11.2277 2.11832C11.4692 2.27689 11.7002 2.508 12.0515 2.85942C12.0662 2.8741 12.081 2.88898 12.0961 2.90408C12.1112 2.91917 12.1261 2.93405 12.1408 2.94871C12.4922 3.30001 12.7233 3.53102 12.8819 3.77248C13.5321 4.76252 13.4972 6.05623 12.822 7.0502C12.6568 7.2933 12.4203 7.52976 12.0507 7.89929C12.0366 7.9134 12.0222 7.92771 12.0077 7.94221L11.389 8.56093C11.1938 8.7562 10.8772 8.7562 10.6819 8.56093C10.4867 8.36567 10.4867 8.04909 10.6819 7.85383L11.3006 7.23511C11.7276 6.80811 11.8899 6.64264 11.9948 6.48827C12.4543 5.81192 12.4633 4.95675 12.046 4.32141C11.9513 4.17714 11.8009 4.02307 11.389 3.61119C10.9771 3.1993 10.8231 3.04893 10.6788 2.95419ZM4.31796 6.43961C4.51322 6.63487 4.51322 6.95146 4.31796 7.14672L3.69924 7.76544C3.27224 8.19244 3.10993 8.35791 3.00507 8.51227C2.54561 9.18863 2.53661 10.0438 2.95385 10.6791C3.0486 10.8234 3.19896 10.9775 3.61085 11.3894C4.02274 11.8012 4.17681 11.9516 4.32107 12.0464C4.95642 12.4636 5.81158 12.4546 6.48794 11.9951C6.6423 11.8903 6.80777 11.728 7.23477 11.301L7.85349 10.6823C8.04875 10.487 8.36533 10.487 8.5606 10.6823C8.75586 10.8775 8.75586 11.1941 8.5606 11.3894L7.94188 12.0081C7.92738 12.0226 7.91307 12.0369 7.89897 12.051C7.52943 12.4206 7.29296 12.6572 7.04986 12.8223C6.05589 13.4976 4.76219 13.5324 3.77214 12.8822C3.53068 12.7237 3.29967 12.4925 2.94837 12.1411C2.93371 12.1264 2.91883 12.1116 2.90374 12.0965C2.88865 12.0814 2.87377 12.0665 2.8591 12.0518C2.50766 11.7005 2.27656 11.4695 2.11799 11.2281C1.4678 10.238 1.50265 8.94432 2.17788 7.95035C2.34303 7.70724 2.57957 7.47077 2.94922 7.10124C2.96333 7.08713 2.97763 7.07283 2.99213 7.05833L3.61085 6.43961C3.80611 6.24435 4.12269 6.24435 4.31796 6.43961Z" fill="currentColor" fillRule="evenodd" clipRule="evenodd"></path></svg>
</div>
</div>
,

},
{
Expand Down
13 changes: 5 additions & 8 deletions apps/webapp/src/components/api-keys/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,18 @@ export default function ApiKeysPage() {
}

const handleSubmit = (e: React.FormEvent) => {
console.log("ddd")
e.preventDefault(); // Prevent default form submission
//console.log("submitting with project "+ selectedProject.id_project);
mutate({
userId: profile!.id_user,
projectId: idProject
//keyName: keyName
projectId: idProject,
keyName: keyName
});
};

const tsApiKeys = apiKeys?.map((key) => ({
name: key.id_api_key,// key.name
token: key.api_key_hash, // or any other property that corresponds to 'token'
created: new Date().toISOString() // or any other property that corresponds to 'created'
name: key.name || "",
token: key.api_key_hash,
created: new Date().toISOString()
}))

return (
Expand Down Expand Up @@ -93,7 +91,6 @@ export default function ApiKeysPage() {
</DialogContent>
</Dialog>
</div>
{/*isLoading && <DataTableLoading data={[]} columns={columns}/>*/}
{tsApiKeys && <DataTable data={tsApiKeys} columns={columns} />}
</div>
</div>
Expand Down
9 changes: 5 additions & 4 deletions apps/webapp/src/hooks/mutations/useApiKeyMutation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,26 @@ import toast from 'react-hot-toast';
interface IApiKeyDto {
projectId: string;
userId: string;
//keyName: string;
keyName?: string;
}
const useApiKeyMutation = () => {
const addApiKey = async (data: IApiKeyDto) => {
console.log("user id is " + data.userId )

//TODO: in cloud environment this step must be done when user logs in directly inside his dashboard
// Fetch the token
const loginResponse = await fetch(`${config.API_URL}/auth/login`, {
method: 'POST',
body: JSON.stringify({ id_user: data.userId.trim(), password_hash: 'pwd_audrey123' }),
body: JSON.stringify({ id_user: data.userId.trim(), password_hash: 'my_password' }),
headers: {
'Content-Type': 'application/json',
'Content-Type': 'application/json',
},
});

if (!loginResponse.ok) {
throw new Error('Failed to login');
}
const { access_token } = await loginResponse.json();
//console.log("token is "+ access_token)

const response = await fetch(`${config.API_URL}/auth/generate-apikey`, {
method: 'POST',
Expand Down
60 changes: 60 additions & 0 deletions packages/api/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ datasource db {
model api_keys {
id_api_key String @id(map: "id_") @db.Uuid
api_key_hash String @unique(map: "unique_api_keys")
name String?
id_project String @db.Uuid
id_user String @db.Uuid
projects projects @relation(fields: [id_project], references: [id_project], onDelete: NoAction, onUpdate: NoAction, map: "fk_7")
Expand Down Expand Up @@ -449,3 +450,62 @@ model webhooks_reponses {
http_status_code String
webhook_delivery_attempts webhook_delivery_attempts[]
}

/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
model tcg_comments {
id_tcg_comment String @id(map: "pk_tcg_comments") @db.Uuid
remote_id String?
body String?
html_body String?
is_private Boolean?
created_at DateTime? @db.Timestamp(6)
modified_at DateTime? @db.Timestamp(6)
id_tcg_ticket String? @db.Uuid
id_tcg_contact String? @db.Uuid
tcg_tickets tcg_tickets? @relation(fields: [id_tcg_ticket], references: [id_tcg_ticket], onDelete: NoAction, onUpdate: NoAction, map: "fk_40_1")
tcg_contacts tcg_contacts? @relation(fields: [id_tcg_contact], references: [id_tcg_contact], onDelete: NoAction, onUpdate: NoAction, map: "fk_41")
@@index([id_tcg_contact], map: "fk_tcg_comment_tcg_contact")
@@index([id_tcg_ticket], map: "fk_tcg_comment_tcg_ticket")
}

model tcg_contacts {
id_tcg_contact String @id(map: "pk_tcg_contact") @db.Uuid
remote_id String?
name String?
email_address String?
phone_number String?
details String?
created_at DateTime? @db.Timestamp(6)
modified_at DateTime? @db.Timestamp(6)
tcg_comments tcg_comments[]
}

/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
model tcg_tickets {
id_tcg_ticket String @id(map: "pk_tcg_tickets") @db.Uuid
remote_id String?
name String?
status String?
description String?
due_date DateTime? @db.Timestamp(6)
ticket_type String?
parent_ticket String? @db.Uuid
tags String?
completed_at DateTime? @db.Timestamp(6)
priority String?
created_at DateTime @db.Timestamp(6)
modified_at DateTime @db.Timestamp(6)
assigned_to String[]
tcg_comments tcg_comments[]
}

/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
model tcg_users {
id_tcg_user String @id(map: "pk_tcg_users") @db.Uuid
remote_id String?
name String?
email_address String?
created_at DateTime? @db.Timestamp(6)
modified_at DateTime? @db.Timestamp(6)
}
2 changes: 1 addition & 1 deletion packages/api/scripts/seed.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ INSERT INTO organizations (id_organization, name, stripe_customer_id) VALUES
('55222419-795d-4183-8478-361626363e58', 'Acme Inc', 'cust_stripe_acme_56604f75-7bf8-4541-9ab4-5928aade4bb8' );

INSERT INTO users (id_user, email, password_hash, first_name, last_name, id_organization) VALUES
('0ce39030-2901-4c56-8db0-5e326182ec6b', '[email protected]', 'pwd_audrey123', 'Audrey', 'Aubry',
('0ce39030-2901-4c56-8db0-5e326182ec6b', '[email protected]', 'my_password', 'Audrey', 'Aubry', '55222419-795d-4183-8478-361626363e58'
(SELECT id_organization FROM organizations WHERE name = 'Acme Inc'));

DO $$
Expand Down
13 changes: 7 additions & 6 deletions packages/api/src/@core/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export class AuthService {
password_hash: hashedPassword,
first_name: user.first_name,
last_name: user.last_name,
id_organization: user.id_organisation || null,
},
});
if (!res) {
Expand Down Expand Up @@ -124,7 +125,7 @@ export class AuthService {
async generateApiKeyForUser(
userId: string,
projectId: string,
keyName?: string,
keyName: string,
): Promise<{ api_key: string }> {
try {
const foundProject = await this.prisma.projects.findUnique({
Expand All @@ -150,12 +151,12 @@ export class AuthService {
// Generate a new API key (use a secure method for generation)
const { access_token } = await this.generateApiKey(projectId, userId);
// Store the API key in the database associated with the user
const hashed_token = this.hashApiKey(access_token);
//const hashed_token = this.hashApiKey(access_token);
const new_api_key = await this.prisma.api_keys.create({
data: {
id_api_key: uuidv4(),
api_key_hash: hashed_token,
//name: keyName,
api_key_hash: access_token,
name: keyName,
id_project: projectId as string,
id_user: userId as string,
},
Expand All @@ -177,10 +178,10 @@ export class AuthService {
secret: process.env.JWT_SECRET,
});

const hashed_api_key = this.hashApiKey(apiKey);
//const hashed_api_key = this.hashApiKey(apiKey);
const saved_api_key = await this.prisma.api_keys.findUnique({
where: {
api_key_hash: hashed_api_key,
api_key_hash: apiKey,
},
});
if (!saved_api_key) {
Expand Down
6 changes: 3 additions & 3 deletions packages/api/src/@core/auth/dto/api-key.dto.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ApiProperty } from '@nestjs/swagger';

export class ApiKeyDto {
@ApiProperty()
projectId: string;
@ApiProperty()
userId: string;
@ApiPropertyOptional()
keyName?: string;
@ApiProperty()
keyName: string;
}
4 changes: 3 additions & 1 deletion packages/api/src/@core/auth/dto/create-user.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';

export class CreateUserDto {
@ApiProperty()
Expand All @@ -9,4 +9,6 @@ export class CreateUserDto {
email: string;
@ApiProperty()
password_hash: string;
@ApiPropertyOptional()
id_organisation?: string;
}
17 changes: 16 additions & 1 deletion packages/api/swagger/swagger-spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@
}
}
},
"/protected": {
"get": {
"operationId": "AppController_getHello2",
"parameters": [],
"responses": {
"200": {
"description": ""
}
}
}
},
"/auth/register": {
"post": {
"operationId": "signUp",
Expand Down Expand Up @@ -936,6 +947,9 @@
},
"password_hash": {
"type": "string"
},
"id_organisation": {
"type": "string"
}
},
"required": [
Expand Down Expand Up @@ -977,7 +991,8 @@
},
"required": [
"projectId",
"userId"
"userId",
"keyName"
]
},
"WebhookDto": {
Expand Down

0 comments on commit a8b6779

Please sign in to comment.