Skip to content

Commit

Permalink
Merge pull request #20 from ThreeDify/dev
Browse files Browse the repository at this point in the history
Dev => Master
  • Loading branch information
silwalanish authored Dec 19, 2020
2 parents 8f57ca6 + 87e2e54 commit 3d21329
Show file tree
Hide file tree
Showing 36 changed files with 978 additions and 75 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,6 @@ export async function down(knex: Knex): Promise<void> {
table.dropColumn('state');
}
);

await knex.schema.raw('DROP TYPE "ReconstructionState";');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as Knex from 'knex';

export async function up(knex: Knex): Promise<void> {
await knex.schema.table(
'reconstructions',
(table: Knex.AlterTableBuilder) => {
table.string('reconstruction_file').nullable();
}
);
}

export async function down(knex: Knex): Promise<void> {
await knex.schema.table(
'reconstructions',
(table: Knex.AlterTableBuilder) => {
table.dropColumn('reconstruction_file');
}
);
}
16 changes: 16 additions & 0 deletions migrations/20201215192946_create_apps_table.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import * as Knex from 'knex';

export async function up(knex: Knex): Promise<void> {
await knex.schema.createTable('apps', (table: Knex.CreateTableBuilder) => {
table.bigIncrements('id').primary();
table.string('name').notNullable();
table.string('domain').notNullable();
table.string('key', 2000).notNullable().unique();
table.string('secret', 2000).notNullable();
table.timestamps(false, true);
});
}

export async function down(knex: Knex): Promise<void> {
await knex.schema.dropTableIfExists('apps');
}
15 changes: 12 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,19 @@
"description": "REST API for ThreeDify",
"scripts": {
"build": "tsc -p .",
"migrate:up": "knex migrate:up",
"migrate:list": "knex migrate:list",
"migrate:down": "knex migrate:down",
"migrate:make": "knex migrate:make",
"migrate:latest": "knex migrate:latest",
"migrate:rollback": "knex migrate:rollback",
"start": "node -r dotenv/config dist/src/index.js",
"start:dev": "nodemon -r dotenv/config src/index.ts",
"lint": "pretty-quick --check --pattern \"src/**/*\" && eslint",
"script:generateApp": "ts-node -r dotenv/config scripts/generateApp.ts",
"lint:fix": "pretty-quick --write --pattern \"src/**/*\" && eslint --fix",
"listDriveFiles": "ts-node -r dotenv/config scripts/listDriveFiles.ts",
"generateGoogleToken": "ts-node -r dotenv/config scripts/generateGoogleToken.ts"
"script:listDriveFiles": "ts-node -r dotenv/config scripts/listDriveFiles.ts",
"script:generateGoogleToken": "ts-node -r dotenv/config scripts/generateGoogleToken.ts"
},
"private": "true",
"license": "MIT",
Expand All @@ -30,6 +37,7 @@
"@types/range-parser": "^1.2.3",
"@types/swagger-jsdoc": "^3.0.2",
"@types/swagger-ui-express": "^4.1.2",
"@types/uuid": "^8.3.0",
"@typescript-eslint/eslint-plugin": "^3.8.0",
"@typescript-eslint/parser": "^3.8.0",
"eslint": "^7.6.0",
Expand Down Expand Up @@ -62,7 +70,8 @@
"pg": "^8.3.3",
"range-parser": "^1.2.1",
"swagger-jsdoc": "^4.3.0",
"swagger-ui-express": "^4.1.4"
"swagger-ui-express": "^4.1.4",
"uuid": "^8.3.2"
},
"husky": {
"hooks": {
Expand Down
63 changes: 63 additions & 0 deletions scripts/generateApp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import readline from 'readline';
import { ValidationResult } from 'joi';
import Debug, { Debugger } from 'debug';

import db from '../src/utils/db';
import NewApp from '../src/domain/NewApp';
import appAuth from '../src/services/appAuth';
import NewAppValidationSchema from '../src/validationSchema/NewAppValidationSchema';

const debug: Debugger = Debug('threedify:script:generateApp');

async function question(
rl: readline.Interface,
question: string
): Promise<string> {
return new Promise((resolve) => {
rl.question(question, (answer) => resolve(answer));
});
}

(async () => {
const reader = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

try {
debug('Connecting to database...');
db.init();

debug('Enter app details...');
const newApp: NewApp = {
name: await question(reader, 'App name? '),
domain: await question(reader, 'App domain? '),
};
reader.close();

debug('Validating app details...');
const result: ValidationResult = NewAppValidationSchema.validate(newApp, {
abortEarly: false,
});

if (result.error) {
debug('Validation failed...');
debug('Validation Errors: %O', result.error.details);

process.exit(1);
}

debug('Creating app...');
const validatedApp: NewApp = result.value;
const app = await appAuth.createNewApp(validatedApp);

debug('Save the app key and secret...');
debug('App Key: %s', app?.key);
debug('App Secret: %s', app?.rawSecret);
} catch (err) {
debug('Oops! an error occurred: %O', err);
process.exit(2);
}

process.exit(0);
})();
35 changes: 30 additions & 5 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,40 @@ import { Options as SwaggerOptions } from 'swagger-jsdoc';

import packageJson from '../package.json';

import apps from './services/apps';
import { SortOrder } from './domain/PaginationQuery';
import GoogleAPIConfig from './domain/GoogleAPIConfig';
import PaginationConfig from './domain/PaginationConfig';
import { AvailableStorageAPI } from './domain/StorageAPI';
import SupportedMimeTypes from './domain/SupportedMimeTypes';

interface Config {
port: number;
baseUrl: string;
saltRound: number;
storageAPI: string;
corsConfig: CorsOptions;
uploadDirectory: string;
requestLogFormat: string;
accessTokenSecret: string;
refreshTokenSecret: string;
multerConfig: MulterOptions;
supportedMimeTypes: string[];
swaggerConfig: SwaggerOptions;
accessTokenConfig: SignOptions;
storageAPI: AvailableStorageAPI;
refreshTokenConfig: SignOptions;
googleAPIConfig?: GoogleAPIConfig;
paginationConfig: PaginationConfig;
supportedMimeTypes: SupportedMimeTypes;
}

const config: Config = {
saltRound: 10,
requestLogFormat: 'tiny',
baseUrl: process.env.BASE_URL || '',
port: +(process.env?.PORT || 3000),
storageAPI: process.env.STORAGE_API || 'local',
storageAPI:
(process.env.STORAGE_API?.trim().toUpperCase() as AvailableStorageAPI) ||
AvailableStorageAPI.LOCAL,
accessTokenSecret: process.env.ACCESS_TOKEN_SECRET || '',
refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET || '',
accessTokenConfig: {
Expand All @@ -46,10 +51,30 @@ const config: Config = {
expiresIn: 7 * 24 * 60 * 60,
},
corsConfig: {
origin: process.env.APP_BASE_URL,
credentials: true,
origin: async (origin, callback) => {
if (!origin) {
callback(null, false);
return;
}
try {
const domains = await apps.fetchAllowedDomains();
for (let domain of domains) {
if (domain.test(origin)) {
callback(null, true);
return;
}
}
callback(null, false);
} catch (err) {
callback(err, false);
}
},
},
supportedMimeTypes: {
image: ['image/jpeg', 'image/png'],
reconstruction: ['text/plain'],
},
supportedMimeTypes: ['image/jpeg', 'image/png'],
uploadDirectory: resolve(__dirname, '../uploads'),
multerConfig: {
dest: resolve(__dirname, '../uploads', 'tmp'),
Expand Down
8 changes: 4 additions & 4 deletions src/controllers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import { NextFunction, Request, Response } from 'express';

import User from '../models/User';
import Token from '../models/Token';
import authService from '../services/auth';
import { NewUser } from '../domain/NewUser';
import tokenService from '../services/tokens';
import UserResponse from '../domain/UserResponse';
import userAuthService from '../services/userAuth';
import { LoginCredential, TokenCredential } from '../domain/login';
import { AuthenticatedRequest } from '../middlewares/authenticate';
import { AuthenticatedRequest } from '../middlewares/authenticateUser';

const debug: Debugger = Debug('threedify:controller:auth');

Expand All @@ -18,7 +18,7 @@ export async function register(
next: NextFunction
) {
try {
let user: User | undefined = await authService.createNewUser(req.body);
let user: User | undefined = await userAuthService.createNewUser(req.body);

if (user) {
res.json({
Expand Down Expand Up @@ -50,7 +50,7 @@ export async function login(
) {
try {
debug('Authenticating user.');
let user: User | undefined = await authService.login(req.body);
let user: User | undefined = await userAuthService.login(req.body);

if (user) {
debug('Generating tokens for user.');
Expand Down
Loading

0 comments on commit 3d21329

Please sign in to comment.