adding more stuff and having more production

This commit is contained in:
talksik
2022-06-08 06:03:07 -05:00
parent 82db26e994
commit 9bf2507cdc
12 changed files with 245 additions and 96 deletions
-3
View File
@@ -1,3 +0,0 @@
MONGO_CONNECTION_STRING=mongodb+srv://default:M9iZXokJlZpN4KLX@cluster0.mkuqa.mongodb.net/default?retryWrites=true&w=majority
JWT_TOKEN_SECRET=afajdslfwk1@lkkasdfl21ASDF!2
+16
View File
@@ -0,0 +1,16 @@
{
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"plugin:import/recommended",
"plugin:import/typescript"
],
"parser": "@typescript-eslint/parser"
}
-16
View File
@@ -1,16 +0,0 @@
import dotenv from "dotenv";
if (process.env && process.env.NODE_ENV === "development") {
dotenv.config({ path: ".env.development" });
} else {
dotenv.config({ path: ".env" });
}
export const loadConfig = () => {
return {
MONGO_CONNECTION_STRING: process.env.MONGO_CONNECTION_STRING!,
JWT_TOKEN_SECRET: process.env.JWT_TOKEN_SECRET!,
GOOGLE_AUTH_CLIENT_ID: process.env.GOOGLE_AUTH_CLIENT_ID!,
GOOGLE_AUTH_CLIENT_SECRET: process.env.GOOGLE_AUTH_CLIENT_SECRET!,
};
};
+28
View File
@@ -0,0 +1,28 @@
interface EnvironmentConfig {
MONGO_CONNECTION_STRING: string;
JWT_TOKEN_SECRET: string;
GOOGLE_AUTH_CLIENT_ID: string;
}
// keep private
const getEnvironmentVariables = (): EnvironmentConfig => {
// TODO
if (process.env.NODE_ENV === 'production') {
//
}
if (process.env.NODE_ENV === 'development') {
//
}
return {
GOOGLE_AUTH_CLIENT_ID:
'423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com',
JWT_TOKEN_SECRET: 'afajdslfwk1@lkkasdfl21ASDF!2',
MONGO_CONNECTION_STRING:
'mongodb+srv://default:M9iZXokJlZpN4KLX@cluster0.mkuqa.mongodb.net/default?retryWrites=true&w=majority',
};
};
const environmentVariables: EnvironmentConfig = getEnvironmentVariables();
export default environmentVariables;
+26 -25
View File
@@ -1,18 +1,18 @@
import express, { Application, Request, Response } from "express";
import express, { Application, Request, Response } from 'express';
import GetAllSocketClients from "@nirvana/core/sockets/getAllActiveSocketClients";
import InitializeWs from "./sockets";
import { NextFunction } from "express";
import NirvanaResponse from "@nirvana/core/responses/nirvanaResponse";
import ReceiveSignal from "../core/sockets/receiveSignal";
import SendSignal from "@nirvana/core/sockets/sendSignal";
import SocketChannels from "@nirvana/core/sockets/channels";
import { UserService } from "./services/user.service";
import { UserStatus } from "@nirvana/core/models";
import cors from "cors";
import getLineRoutes from "./routes/line";
import getSearchRoutes from "./routes/search";
import getUserRoutes from "./routes/user";
import GetAllSocketClients from '@nirvana/core/sockets/getAllActiveSocketClients';
import InitializeWs from './services/socket.service';
import { NextFunction } from 'express';
import NirvanaResponse from '@nirvana/core/responses/nirvanaResponse';
import ReceiveSignal from '../core/sockets/receiveSignal';
import SendSignal from '@nirvana/core/sockets/sendSignal';
import SocketChannels from '@nirvana/core/sockets/channels';
import { UserService } from './services/user.service';
import { UserStatus } from '@nirvana/core/models';
import cors from 'cors';
import getLineRoutes from './routes/line';
import getSearchRoutes from './routes/search';
import getUserRoutes from './routes/user';
const app = express();
@@ -20,29 +20,30 @@ app.use(cors());
app.use(express.json());
app.use((req: Request, res: Response, next: NextFunction) => {
console.log("Time: ", new Date());
console.log('Time: ', new Date());
next();
});
app.get("/", (req: Request, res: Response) => {
res.send("hello world.");
app.get('/', (req: Request, res: Response) => {
res.send('hello world.');
});
app.use("/api/status", (req: Request, res: Response) => {
res.json(new NirvanaResponse("wohoo, server is healthy"));
app.use('/api/status', (req: Request, res: Response) => {
res.json(new NirvanaResponse('wohoo, server is healthy'));
});
app.use("/api/user", getUserRoutes());
app.use("/api/search", getSearchRoutes());
app.use("/api/lines", getLineRoutes());
app.use('/api/user', getUserRoutes());
app.use('/api/search', getSearchRoutes());
app.use('/api/lines', getLineRoutes());
const PORT = 5000;
const server = app.listen(PORT, () => console.log("express running"));
const server = app.listen(PORT, () => console.log('express running'));
const io = require("socket.io")(server, {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const io = require('socket.io')(server, {
// todo: add authentication
cors: {
origin: "*",
origin: '*',
},
});
+7 -13
View File
@@ -1,32 +1,26 @@
import { NextFunction, Request, Response } from "express";
import { NextFunction, Request, Response } from 'express';
import { loadConfig } from "../config";
import environmentVariables from '../config/config';
const jwt = require("jsonwebtoken");
const config = loadConfig();
const jwt = require('jsonwebtoken');
// used by specific routes that need to authentication
export const authCheck = async (
req: Request,
res: Response,
next: NextFunction
) => {
export const authCheck = async (req: Request, res: Response, next: NextFunction) => {
try {
const { authorization } = req.headers;
if (!authorization) {
throw Error("No provided header");
throw Error('No provided header');
}
// verify jwt token with our api secret
var decoded: JwtClaims = jwt.verify(authorization, config.JWT_TOKEN_SECRET);
var decoded: JwtClaims = jwt.verify(authorization, environmentVariables.JWT_TOKEN_SECRET);
res.locals.userInfo = decoded;
next();
} catch (error) {
res.status(401).send("unauthorized");
res.status(401).send('unauthorized');
}
};
+17 -14
View File
@@ -3,17 +3,6 @@
"version": "1.0.0",
"main": "index.ts",
"license": "MIT",
"dependencies": {
"@nirvana/core": "*",
"axios": "^0.26.1",
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"google-auth-library": "^7.14.0",
"jsonwebtoken": "^8.5.1",
"mongodb": "^4.4.1",
"socket.io": "^4.4.1"
},
"scripts": {
"dev": "NODE_ENV=development nodemon",
"start": "ts-node index.ts",
@@ -24,9 +13,23 @@
"@types/node": "^17.0.21",
"nodemon": "^2.0.15",
"ts-node": "^10.7.0",
"@types/morgan": "^1.9.3",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-plugin-import": "^2.25.0",
"typescript": "^4.6.2"
},
"workspaces": [
"packages/*"
]
"dependencies": {
"@nirvana/core": "*",
"axios": "^0.26.1",
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"google-auth-library": "^7.14.0",
"jsonwebtoken": "^8.5.1",
"mongodb": "^4.4.1",
"morgan": "^1.10.0",
"socket.io": "^4.4.1"
}
}
+7 -8
View File
@@ -10,13 +10,12 @@ import UserDetailsResponse from '../../core/responses/userDetails.response';
import { UserService } from '../services/user.service';
import { UserStatus } from '../../core/models/user.model';
import { collections } from '../services/database.service';
import { loadConfig } from '../config';
import environmentVariables from '../config/config';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const jwt = require('jsonwebtoken');
const config = loadConfig();
const client = new OAuth2Client(config.GOOGLE_AUTH_CLIENT_ID);
const client = new OAuth2Client(environmentVariables.GOOGLE_AUTH_CLIENT_ID);
export default function getUserRoutes() {
const router = express.Router();
@@ -66,7 +65,7 @@ async function login(req: Request, res: Response) {
try {
const ticket = await client.verifyIdToken({
idToken: (id_token as string) ?? '',
audience: config.GOOGLE_AUTH_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
audience: environmentVariables.GOOGLE_AUTH_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
});
const googleUserId = ticket.getPayload()?.sub as string;
const email = ticket.getPayload()?.email as string;
@@ -77,7 +76,7 @@ async function login(req: Request, res: Response) {
}
// return user details if it passed auth middleware
let user = await UserService.getUserByEmail(email);
const user = await UserService.getUserByEmail(email);
// if no user found, then go ahead and create user
if (!user) {
@@ -119,7 +118,7 @@ async function login(req: Request, res: Response) {
email: newUser.email,
name: newUser.name,
},
config.JWT_TOKEN_SECRET,
environmentVariables.JWT_TOKEN_SECRET,
);
insertResult
@@ -138,7 +137,7 @@ async function login(req: Request, res: Response) {
email: user.email,
name: user.name,
},
config.JWT_TOKEN_SECRET,
environmentVariables.JWT_TOKEN_SECRET,
);
res.status(200).json(new LoginResponse(existingUserJwtToken, user));
+7 -10
View File
@@ -1,7 +1,7 @@
// External Dependencies
import * as mongoDB from "mongodb";
import * as mongoDB from 'mongodb';
import { loadConfig } from "../config";
import environmentVariables from '../config/config';
// Global Variables
export const collections: {
@@ -11,24 +11,21 @@ export const collections: {
} = {};
// Initialize Connection
const config = loadConfig();
export const client: mongoDB.MongoClient = new mongoDB.MongoClient(
config.MONGO_CONNECTION_STRING
environmentVariables.MONGO_CONNECTION_STRING,
);
client.connect();
const db: mongoDB.Db = client.db(process.env.DB_NAME);
const usersCollection: mongoDB.Collection = db.collection("users");
const lineCollection: mongoDB.Collection = db.collection("lines");
const lineMembersCollection: mongoDB.Collection = db.collection("lineMembers");
const usersCollection: mongoDB.Collection = db.collection('users');
const lineCollection: mongoDB.Collection = db.collection('lines');
const lineMembersCollection: mongoDB.Collection = db.collection('lineMembers');
collections.users = usersCollection;
collections.lines = lineCollection;
collections.lineMembers = lineMembersCollection;
console.log(
`Successfully connected to database: ${db.databaseName} and collections`
);
console.log(`Successfully connected to database: ${db.databaseName} and collections`);
@@ -21,18 +21,17 @@ import {
import GetAllSocketClients from '@nirvana/core/sockets/getAllActiveSocketClients';
import { JwtClaims } from '../middleware/auth';
import { LineMemberState } from '@nirvana/core/models/line.model';
import { LineService } from '../services/line.service';
import { LineService } from './line.service';
import ReceiveSignal from '@nirvana/core/sockets/receiveSignal';
import SendSignal from '@nirvana/core/sockets/sendSignal';
import { UserService } from '../services/user.service';
import { UserService } from './user.service';
import { UserStatus } from '@nirvana/core/models/user.model';
import { client } from '../services/database.service';
import { loadConfig } from '../config';
import { client } from './database.service';
import environmentVariables from '../config/config';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const jwt = require('jsonwebtoken');
const config = loadConfig();
// NOTE: client socket connections should never have to deal with socketIds
const socketIdsToUserIds: {
[socketId: string]: string;
@@ -53,7 +52,7 @@ export default function InitializeWs(io: any) {
console.log(token);
// verify jwt token with our api secret
var decoded: JwtClaims = jwt.verify(token, config.JWT_TOKEN_SECRET);
const decoded: JwtClaims = jwt.verify(token, environmentVariables.JWT_TOKEN_SECRET);
socket.userInfo = decoded;
+101
View File
@@ -0,0 +1,101 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
+30
View File
@@ -822,6 +822,13 @@
resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.5.tgz#1001cc5e6a3704b83c236027e77f2f58ea010f40"
integrity sha512-Klz949h02Gz2uZCMGwDUSDS1YBlTdDDgbWHi+81l29tQALUtvz4rAYi5uoVhE5Lagoq6DeqAUlbrHvW/mXDgdQ==
"@types/morgan@^1.9.3":
version "1.9.3"
resolved "https://registry.yarnpkg.com/@types/morgan/-/morgan-1.9.3.tgz#ae04180dff02c437312bc0cfb1e2960086b2f540"
integrity sha512-BiLcfVqGBZCyNCnCH3F4o2GmDLrpy0HeBVnNlyZG4fo88ZiE9SoiBe3C+2ezuwbjlEyT+PDZ17//TAlRxAn75Q==
dependencies:
"@types/node" "*"
"@types/node@*", "@types/node@>=10.0.0", "@types/node@^17.0.21":
version "17.0.21"
resolved "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz"
@@ -1719,6 +1726,13 @@ base64id@2.0.0, base64id@~2.0.0:
resolved "https://registry.yarnpkg.com/base64id/-/base64id-2.0.0.tgz#2770ac6bc47d312af97a8bf9a634342e0cd25cb6"
integrity sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==
basic-auth@~2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/basic-auth/-/basic-auth-2.0.1.tgz#b998279bf47ce38344b4f3cf916d4679bbf51e3a"
integrity sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==
dependencies:
safe-buffer "5.1.2"
batch@0.6.1:
version "0.6.1"
resolved "https://registry.npmjs.org/batch/-/batch-0.6.1.tgz"
@@ -2736,6 +2750,11 @@ depd@^1.1.2, depd@~1.1.2:
resolved "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz"
integrity sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=
depd@~2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df"
integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==
destroy@~1.0.4:
version "1.0.4"
resolved "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz"
@@ -5920,6 +5939,17 @@ mongodb@^4.4.1:
optionalDependencies:
saslprep "^1.0.3"
morgan@^1.10.0:
version "1.10.0"
resolved "https://registry.yarnpkg.com/morgan/-/morgan-1.10.0.tgz#091778abc1fc47cd3509824653dae1faab6b17d7"
integrity sha512-AbegBVI4sh6El+1gNwvD5YIck7nSA36weD7xvIxG4in80j/UoK8AEGaWnnz8v1GxonMCltmlNs5ZKbGvl9b1XQ==
dependencies:
basic-auth "~2.0.1"
debug "2.6.9"
depd "~2.0.0"
on-finished "~2.3.0"
on-headers "~1.0.2"
ms@2.0.0:
version "2.0.0"
resolved "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz"