Skip to content

Commit 7f3d1ba

Browse files
committed
mongo implementation 🐺
1 parent db9f805 commit 7f3d1ba

File tree

9 files changed

+218
-49
lines changed

9 files changed

+218
-49
lines changed

.env.local

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
MAKEFILE_OVERWRITE_DOCKERNAME=
22
INITIAL_BEARER_TOKEN=
3+
MONGO_URI=

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"form-data": "^4.0.0",
1818
"google-auth-library": "^9.14.0",
1919
"googleapis": "^140.0.1",
20+
"mongodb": "^6.9.0",
2021
"open": "^10.1.0",
2122
"whatwg-url": "^14.0.0"
2223
},

src/app.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
import express from 'express';
22
import routes from './routes';
3-
import { checkRequiredEnvVariables } from './dbcode/dbSetup';
3+
import { checkRequiredEnvVariables, initializeDatabase } from './dbcode/dbSetup';
44

55
// Check required environment variables
66
checkRequiredEnvVariables();
77

8+
// Initialize database connection
9+
await initializeDatabase();
10+
811
const app = express();
912
const PORT = 8080;
1013

src/dbcode/dbSetup.ts

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,23 @@
1-
// src/dbCode/dbSetup.ts
1+
// src/dbcode/dbSetup.ts
2+
23
import fs from 'fs';
34
import path from 'path';
45
import dotenv from 'dotenv';
5-
import dbClient from '../dbcode/dbClient';
6+
import MongoDbClient from './mongoDbClient';
67

78
const envPath = path.resolve(process.cwd(), '.env');
89
const envLocalPath = path.resolve(process.cwd(), '.env.local');
910

1011
if (fs.existsSync(envPath)) {
1112
dotenv.config({ path: envPath });
12-
//console.log('.env file found and loaded');
1313
} else if (fs.existsSync(envLocalPath)) {
1414
dotenv.config({ path: envLocalPath });
15-
//console.log('.env.local file found and loaded');
1615
} else {
1716
console.log('Neither .env nor .env.local file found.');
1817
}
1918

2019
export function checkRequiredEnvVariables() {
21-
const requiredVariables: string[] = [
22-
// Add your required variables here
23-
// For example: 'DATABASE_URL', 'API_KEY', etc.
24-
];
20+
const requiredVariables = ['MONGO_URI' ];
2521

2622
for (const variable of requiredVariables) {
2723
if (!process.env[variable]) {
@@ -33,17 +29,26 @@ export function checkRequiredEnvVariables() {
3329
console.log('All required environment variables are set.');
3430
}
3531

36-
export function initializeTokens() {
37-
const bearerToken = process.env.INITIAL_BEARER_TOKEN;
32+
let dbClient: MongoDbClient;
33+
34+
export async function initializeDatabase() {
35+
const mongoUri = process.env.MONGO_URI as string;
3836

37+
dbClient = new MongoDbClient(mongoUri);
38+
await dbClient.connect();
39+
40+
const bearerToken = process.env.INITIAL_BEARER_TOKEN;
3941
if (bearerToken) {
40-
if (dbClient.getCurrentBearerTokenDB() === null) {
41-
dbClient.setBearerTokenDB(bearerToken);
42+
const currentToken = await dbClient.getCurrentBearerTokenDB();
43+
if (currentToken === null) {
44+
await dbClient.setBearerTokenDB(bearerToken);
4245
console.log('Initial bearer token set from environment variable');
4346
}
4447
} else {
4548
console.log('No initial bearer token provided in environment variables');
4649
}
4750
}
4851

52+
export { dbClient };
53+
4954
console.log('Database setup module loaded');

src/dbcode/mongoDbClient.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// src/dbcode/mongoDbClient.ts
2+
3+
import { MongoClient, Db } from 'mongodb';
4+
import { IDbClient } from '../types/dbInterfaces';
5+
6+
class MongoDbClient implements IDbClient {
7+
private client: MongoClient;
8+
private db: Db | null = null;
9+
10+
constructor(uri: string) {
11+
this.client = new MongoClient(uri);
12+
}
13+
14+
async connect() {
15+
await this.client.connect();
16+
this.db = this.client.db('yourDatabaseName');
17+
console.log('Connected to MongoDB');
18+
}
19+
20+
async setBearerTokenDB(token: string): Promise<boolean> {
21+
if (!this.db) throw new Error('Database not connected');
22+
const collection = this.db.collection('bearer_tokens');
23+
const existingToken = await collection.findOne({});
24+
if (existingToken) return false;
25+
await collection.insertOne({ token });
26+
return true;
27+
}
28+
29+
async isValidBearerTokenDB(token: string): Promise<boolean> {
30+
if (!this.db) throw new Error('Database not connected');
31+
const collection = this.db.collection('bearer_tokens');
32+
const result = await collection.findOne({ token });
33+
return !!result;
34+
}
35+
36+
async getCurrentBearerTokenDB(): Promise<string | null> {
37+
if (!this.db) throw new Error('Database not connected');
38+
const collection = this.db.collection('bearer_tokens');
39+
const result = await collection.findOne({});
40+
return result ? result.token : null;
41+
}
42+
43+
async changeBearerTokenDB(currentToken: string, newToken: string): Promise<boolean> {
44+
if (!this.db) throw new Error('Database not connected');
45+
const collection = this.db.collection('bearer_tokens');
46+
const result = await collection.updateOne({ token: currentToken }, { $set: { token: newToken } });
47+
return result.modifiedCount > 0;
48+
}
49+
}
50+
51+
export default MongoDbClient;

src/handlers/basicHandler.ts

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,47 @@
11
import { Request, Response } from 'express';
2-
import dbClient from '../dbcode/dbClient';
2+
import { dbClient } from '../dbcode/dbSetup';
33

4-
export function ping(req: Request, res: Response) {
4+
export async function ping(req: Request, res: Response) {
55
res.send('Pong!');
66
}
77

8-
export function safePing(req: Request, res: Response) {
8+
export async function safePing(req: Request, res: Response) {
99
res.send('Safe Pong!');
1010
}
1111

12-
export function getCurrentToken(req: Request, res: Response) {
13-
const token = dbClient.getCurrentBearerTokenDB();
14-
if (token) {
15-
res.json({ token });
16-
} else {
17-
res.status(404).json({ error: 'No Bearer Token set' });
12+
export async function getCurrentToken(req: Request, res: Response) {
13+
try {
14+
const token = await dbClient.getCurrentBearerTokenDB();
15+
if (token) {
16+
res.json({ token });
17+
} else {
18+
res.status(404).json({ error: 'No Bearer Token set' });
19+
}
20+
} catch (error) {
21+
res.status(500).json({ error: 'Internal Server Error' });
1822
}
1923
}
2024

21-
export function setNewBearerToken(req: Request, res: Response) {
25+
export async function setNewBearerToken(req: Request, res: Response) {
2226
const { token } = req.body;
2327

2428
if (!token) {
2529
return res.status(400).json({ error: 'Token is required' });
2630
}
2731

28-
const result = dbClient.setBearerTokenDB(token);
29-
30-
if (result) {
31-
res.status(201).json({ message: 'Bearer Token set successfully' });
32-
} else {
33-
res.status(409).json({ error: 'Bearer Token has already been set' });
32+
try {
33+
const result = await dbClient.setBearerTokenDB(token);
34+
if (result) {
35+
res.status(201).json({ message: 'Bearer Token set successfully' });
36+
} else {
37+
res.status(409).json({ error: 'Bearer Token has already been set' });
38+
}
39+
} catch (error) {
40+
res.status(500).json({ error: 'Internal Server Error' });
3441
}
3542
}
3643

37-
export function changeBearerToken(req: Request, res: Response) {
44+
export async function changeBearerToken(req: Request, res: Response) {
3845
const authHeader = req.headers.authorization;
3946
const { newToken } = req.body;
4047

@@ -48,15 +55,19 @@ export function changeBearerToken(req: Request, res: Response) {
4855

4956
const currentToken = authHeader.split(' ')[1];
5057

51-
if (!dbClient.isValidBearerTokenDB(currentToken)) {
52-
return res.status(401).json({ error: 'Invalid Bearer Token' });
53-
}
54-
55-
const result = dbClient.changeBearerTokenDB(currentToken, newToken);
58+
try {
59+
const isValid = await dbClient.isValidBearerTokenDB(currentToken);
60+
if (!isValid) {
61+
return res.status(401).json({ error: 'Invalid Bearer Token' });
62+
}
5663

57-
if (result) {
58-
res.json({ message: 'Bearer Token changed successfully' });
59-
} else {
60-
res.status(500).json({ error: 'Failed to change Bearer Token' });
64+
const result = await dbClient.changeBearerTokenDB(currentToken, newToken);
65+
if (result) {
66+
res.json({ message: 'Bearer Token changed successfully' });
67+
} else {
68+
res.status(500).json({ error: 'Failed to change Bearer Token' });
69+
}
70+
} catch (error) {
71+
res.status(500).json({ error: 'Internal Server Error' });
6172
}
6273
}

src/middleware/auth.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
import { Request, Response, NextFunction } from 'express';
2-
import dbClient from '../dbcode/dbClient';
2+
import { dbClient } from '../dbcode/dbSetup';
33

4-
export function authenticateToken(req: Request, res: Response, next: NextFunction) {
4+
export async function authenticateToken(req: Request, res: Response, next: NextFunction) {
55
const authHeader = req.headers.authorization;
66
if (!authHeader || !authHeader.startsWith('Bearer ')) {
77
return res.status(401).json({ error: 'Unauthorized: No bearer token provided' });
88
}
99

1010
const bearerToken = authHeader.split(' ')[1];
11-
if (!dbClient.isValidBearerTokenDB(bearerToken)) {
12-
return res.status(401).json({ error: 'Unauthorized: Invalid bearer token' });
11+
try {
12+
const isValid = await dbClient.isValidBearerTokenDB(bearerToken);
13+
if (!isValid) {
14+
return res.status(401).json({ error: 'Unauthorized: Invalid bearer token' });
15+
}
16+
next();
17+
} catch (error) {
18+
return res.status(500).json({ error: 'Internal Server Error' });
1319
}
14-
15-
next();
1620
}

src/types/dbInterfaces.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ export interface ITokenResult {
55
}
66

77
export interface IDbClient {
8-
setBearerTokenDB(token: string): boolean;
9-
isValidBearerTokenDB(token: string): boolean;
10-
getCurrentBearerTokenDB(): string | null;
11-
changeBearerTokenDB(currentToken: string, newToken: string): boolean;
8+
setBearerTokenDB(token: string): Promise<boolean>;
9+
isValidBearerTokenDB(token: string): Promise<boolean>;
10+
getCurrentBearerTokenDB(): Promise<string | null>;
11+
changeBearerTokenDB(currentToken: string, newToken: string): Promise<boolean>;
1212
}

0 commit comments

Comments
 (0)