Skip to content
This repository has been archived by the owner on Jan 21, 2024. It is now read-only.

Commit

Permalink
Implement database authentication support.
Browse files Browse the repository at this point in the history
  • Loading branch information
MitchTalmadge committed Jul 4, 2020
1 parent a390170 commit aa714aa
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
5 changes: 4 additions & 1 deletion config/config.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@

"database": {
"address": "127.0.0.1:27017",
"name": "studybot"
"name": "studybot",
"auth": true,
"username": "admin",
"password": "foobar"
},

"web": {
Expand Down
3 changes: 3 additions & 0 deletions src/models/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ export interface Config {
export interface DatabaseConfig {
address: string;
name: string;
auth: boolean;
username?: string;
password?: string;
}

export interface WebConfig {
Expand Down
8 changes: 8 additions & 0 deletions src/services/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ export class ConfigService {
if (!this.config.database.name) {
throw Error("The database name is missing or empty.");
}
if(this.config.database.auth) {
if(!this.config.database.username) {
throw Error("Database auth is enabled but username is missing or empty.");
}
if(!this.config.database.password) {
throw Error("Database auth is enabled but password is missing or empty.");
}
}
}

private static validateWebConfig(): void {
Expand Down
8 changes: 7 additions & 1 deletion src/services/database/database.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import mongoose, { Connection, Mongoose } from "mongoose";
import { DatabaseConfig } from "models/config";
import mongoose, { Connection, Mongoose } from "mongoose";

export class DatabaseService {
private static mongooseInstance: Mongoose;

public static async connect(dbConfig: DatabaseConfig) {
const auth: {user: string, password: string} | undefined = !dbConfig.auth ? undefined : {
user: dbConfig.username,
password: dbConfig.password
};

this.mongooseInstance = await mongoose.connect(`mongodb://${dbConfig.address}/${dbConfig.name}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
auth
});
}

Expand Down

0 comments on commit aa714aa

Please sign in to comment.