diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..0dbcb08 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,10 @@ +# /node_modules/* in the project root is ignored by default +# build artefacts +dist/* +coverage/* +# data definition files +**/*.d.ts +# 3rd party libs +/src/public/ +# custom definition files +/src/types/ \ No newline at end of file diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..68719fc --- /dev/null +++ b/.eslintrc @@ -0,0 +1,12 @@ +{ + "parser": "@typescript-eslint/parser", + "extends": ["plugin:@typescript-eslint/recommended"], + "parserOptions": { + "ecmaVersion": 2018, + "sourceType": "module" + }, + "rules": { + "semi": ["error", "always"], + "quotes": ["error", "double"] + } +} diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 713af4f..2ca40c6 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,6 +1,3 @@ { - "recommendations": [ - "ms-vscode.vscode-typescript-tslint-plugin", - "ms-azuretools.vscode-cosmosdb", - ] -} \ No newline at end of file + "recommendations": ["dbaeumer.vscode-eslint", "ms-azuretools.vscode-cosmosdb"] +} diff --git a/.vscode/settings.json b/.vscode/settings.json index 24510a4..c15715d 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,17 +1,27 @@ // Place your settings in this file to overwrite default and user settings. { - "search.exclude": { - "**/node_modules": true, - "**/bower_components": true, - "**/dist": true, - "**/coverge": true - }, - "typescript.referencesCodeLens.enabled": true, - "tslint.ignoreDefinitionFiles": false, - "tslint.autoFixOnSave": true, - "tslint.exclude": "**/node_modules/**/*", - "appService.zipIgnorePattern": [ - ".vscode{,/**}" - ], - "appService.deploySubpath": "" -} \ No newline at end of file + "eslint.autoFixOnSave": true, + "eslint.validate": [ + "javascript", + { "language": "typescript", "autoFix": true } + ], + "editor.formatOnSave": true, + "[javascript]": { + "editor.formatOnSave": false + }, + "[typescript]": { + "editor.formatOnSave": false + }, + "[markdown]": { + "editor.formatOnSave": false + }, + "search.exclude": { + "**/node_modules": true, + "**/bower_components": true, + "**/dist": true, + "**/coverge": true + }, + "typescript.referencesCodeLens.enabled": true, + "appService.zipIgnorePattern": [".vscode{,/**}"], + "appService.deploySubpath": "" +} diff --git a/README.md b/README.md index 0ce2a10..7ac8d3d 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ We will try to keep this as up-to-date as possible, but community contributions - [Type Definition (`.d.ts`) Files](#type-definition-dts-files) - [Debugging](#debugging) - [Testing](#testing) - - [TSLint](#tslint) + - [ESLint](#eslint) - [Dependencies](#dependencies) - [`dependencies`](#dependencies-1) - [`devDependencies`](#devdependencies) @@ -203,7 +203,9 @@ The full folder structure of this app is explained below: | jest.config.js | Used to configure Jest running tests written in TypeScript | | package.json | File that contains npm dependencies as well as [build scripts](#what-if-a-library-isnt-on-definitelytyped) | | tsconfig.json | Config settings for compiling server code written in TypeScript | -| tslint.json | Config settings for TSLint code style checking | +| tsconfig.tests.json | Config settings for compiling tests written in TypeScript | +| .eslintrc | Config settings for ESLint code style checking | +| .eslintignore | Config settings for paths to exclude from linting | ## Building the project It is rare for JavaScript projects not to have some kind of build pipeline these days, however Node projects typically have the least amount of build configuration. @@ -271,7 +273,7 @@ Below is a list of all the scripts this template has available: | Npm Script | Description | | ------------------------- | ------------------------------------------------------------------------------------------------- | | `start` | Does the same as 'npm run serve'. Can be invoked with `npm start` | -| `build` | Full build. Runs ALL build tasks (`build-sass`, `build-ts`, `tslint`, `copy-static-assets`) | +| `build` | Full build. Runs ALL build tasks (`build-sass`, `build-ts`, `lint`, `copy-static-assets`) | | `serve` | Runs node on `dist/server.js` which is the apps entry point | | `watch-node` | Runs node with nodemon so the process restarts if it crashes. Used in the main watch task | | `watch` | Runs all watch tasks (TypeScript, Sass, Node). Use this if you're not touching static assets. | @@ -281,7 +283,7 @@ Below is a list of all the scripts this template has available: | `watch-ts` | Same as `build-ts` but continuously watches `.ts` files and re-compiles when needed | | `build-sass` | Compiles all `.scss` files to `.css` files | | `watch-sass` | Same as `build-sass` but continuously watches `.scss` files and re-compiles when needed | -| `tslint` | Runs TSLint on project files | +| `lint` | Runs ESLint on project files | | `copy-static-assets` | Calls script that copies JS libs, fonts, and images to dist directory | | `debug` | Performs a full build and then serves the app in watch mode | | `serve-debug` | Runs the app with the --inspect flag | @@ -461,26 +463,24 @@ Note this will also generate a coverage report. Writing tests for web apps has entire books dedicated to it and best practices are strongly influenced by personal style, so I'm deliberately avoiding discussing how or when to write tests in this guide. However, if prescriptive guidance on testing is something that you're interested in, [let me know](https://www.surveymonkey.com/r/LN2CV82), I'll do some homework and get back to you. -## TSLint -TSLint is a code linter which mainly helps catch minor code quality and style issues. -TSLint is very similar to ESLint or JSLint but is built with TypeScript in mind. +## ESLint +ESLint is a code linter which mainly helps catch quickly minor code quality and style issues. -### TSLint rules -Like most linters, TSLint has a wide set of configurable rules as well as support for custom rule sets. -All rules are configured through `tslint.json`. +### ESLint rules +Like most linters, ESLint has a wide set of configurable rules as well as support for custom rule sets. +All rules are configured through `.eslintrc` configuration file. In this project, we are using a fairly basic set of rules with no additional custom rules. -The settings are largely based off the TSLint settings that we use to develop TypeScript itself. -### Running TSLint -Like the rest of our build steps, we use npm scripts to invoke TSLint. -To run TSLint you can call the main build script or just the TSLint task. +### Running ESLint +Like the rest of our build steps, we use npm scripts to invoke ESLint. +To run ESLint you can call the main build script or just the ESLint task. ``` -npm run build // runs full build including TSLint -npm run tslint // runs only TSLint +npm run build // runs full build including ESLint +npm run lint // runs only ESLint ``` -Notice that TSLint is not a part of the main watch task. -It can be annoying for TSLint to clutter the output window while in the middle of writing a function, so I elected to only run it only during the full build. -If you are interested in seeing TSLint feedback as soon as possible, I strongly recommend the [TSLint extension in VS Code](https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-typescript-tslint-plugin). +Notice that ESLint is not a part of the main watch task. + +If you are interested in seeing ESLint feedback as soon as possible, I strongly recommend the [VS Code ESLint extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint). ### VSCode Extensions @@ -488,7 +488,7 @@ To enhance your development experience while working in VSCode we also provide y ![Suggested Extensions In VSCode](https://user-images.githubusercontent.com/14539/34583539-6f290a30-f198-11e7-8804-30f40d418e20.png) -- [TSLint](https://marketplace.visualstudio.com/items?itemName=eg2.tslint) +- [VS Code ESLint extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) - [Code Spell Checker](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker) - [Azure Cosmos DB](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-cosmosdb) - [Azure App Service](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azureappservice) @@ -539,7 +539,7 @@ In that file you'll find two sections: | supertest | HTTP assertion library. | | ts-jest | A preprocessor with sourcemap support to help use TypeScript with Jest.| | ts-node | Enables directly running TS files. Used to run `copy-static-assets.ts` | -| tslint | Linter (similar to ESLint) for TypeScript files | +| eslint | Linter for JavaScript and TypeScript files | | typescript | JavaScript compiler/type checker that boosts JavaScript productivity | To install or update these dependencies you can use `npm install` or `npm update`. diff --git a/package-lock.json b/package-lock.json index 4678dcc..b81461f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -496,6 +496,12 @@ "integrity": "sha512-6ckxMjBBD8URvjB6J3NcnuAn5Pkl7t3TizAg+xdlzzQGSPSmBcXf8KoIH0ua/i+tio+ZRUHEXp0HEmvaR4kt0w==", "dev": true }, + "@types/chai": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.1.7.tgz", + "integrity": "sha512-2Y8uPt0/jwjhQ6EiluT0XCri1Dbplr0ZxfFXUz+ye13gaqE8u5gL5ppao1JrUYr9cIip5S6MvQzBS7Kke7U9VA==", + "dev": true + }, "@types/compression": { "version": "0.0.36", "resolved": "https://registry.npmjs.org/@types/compression/-/compression-0.0.36.tgz", @@ -567,6 +573,12 @@ "@types/express": "*" } }, + "@types/eslint-visitor-keys": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@types/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", + "integrity": "sha512-OCutwjDZ4aFS6PB1UZ988C4YgwlBHJd6wCeQqaLdmadZ/7e+w79+hbMUFC1QXDNCmdyoRfAFdm0RypzwR+Qpag==", + "dev": true + }, "@types/events": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.0.tgz", @@ -892,6 +904,70 @@ "integrity": "sha512-SOhuU4wNBxhhTHxYaiG5NY4HBhDIDnJF60GU+2LqHAdKKer86//e4yg69aENCtQ04n0ovz+tq2YPME5t5yp4pw==", "dev": true }, + "@typescript-eslint/eslint-plugin": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-1.12.0.tgz", + "integrity": "sha512-J/ZTZF+pLNqjXBGNfq5fahsoJ4vJOkYbitWPavA05IrZ7BXUaf4XWlhUB/ic1lpOGTRpLWF+PLAePjiHp6dz8g==", + "dev": true, + "requires": { + "@typescript-eslint/experimental-utils": "1.12.0", + "eslint-utils": "^1.3.1", + "functional-red-black-tree": "^1.0.1", + "regexpp": "^2.0.1", + "tsutils": "^3.7.0" + }, + "dependencies": { + "tsutils": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.14.0.tgz", + "integrity": "sha512-SmzGbB0l+8I0QwsPgjooFRaRvHLBLNYM8SeQ0k6rtNDru5sCGeLJcZdwilNndN+GysuFjF5EIYgN8GfFG6UeUw==", + "dev": true, + "requires": { + "tslib": "^1.8.1" + } + } + } + }, + "@typescript-eslint/experimental-utils": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-1.12.0.tgz", + "integrity": "sha512-s0soOTMJloytr9GbPteMLNiO2HvJ+qgQkRNplABXiVw6vq7uQRvidkby64Gqt/nA7pys74HksHwRULaB/QRVyw==", + "dev": true, + "requires": { + "@typescript-eslint/typescript-estree": "1.12.0", + "eslint-scope": "^4.0.0" + } + }, + "@typescript-eslint/parser": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-1.12.0.tgz", + "integrity": "sha512-0uzbaa9ZLCA5yMWJywnJJ7YVENKGWVUhJDV5UrMoldC5HoI54W5kkdPhTfmtFKpPFp93MIwmJj0/61ztvmz5Dw==", + "dev": true, + "requires": { + "@types/eslint-visitor-keys": "^1.0.0", + "@typescript-eslint/experimental-utils": "1.12.0", + "@typescript-eslint/typescript-estree": "1.12.0", + "eslint-visitor-keys": "^1.0.0" + } + }, + "@typescript-eslint/typescript-estree": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-1.12.0.tgz", + "integrity": "sha512-nwN6yy//XcVhFs0ZyU+teJHB8tbCm7AIA8mu6E2r5hu6MajwYBY3Uwop7+rPZWUN/IUOHpL8C+iUPMDVYUU3og==", + "dev": true, + "requires": { + "lodash.unescape": "4.0.1", + "semver": "5.5.0" + }, + "dependencies": { + "semver": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.0.tgz", + "integrity": "sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==", + "dev": true + } + } + }, "abab": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.0.tgz", @@ -933,6 +1009,12 @@ } } }, + "acorn-jsx": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.0.1.tgz", + "integrity": "sha512-HJ7CfNHrfJLlNTzIEUTj43LNWGkqpRLxm3YjAlcD0ACydk9XynzYsCBHxut+iqt+1aBXkx9UP/w/ZqMr13XIzg==", + "dev": true + }, "acorn-walk": { "version": "6.1.1", "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-6.1.1.tgz", @@ -1470,12 +1552,6 @@ "integrity": "sha1-mXjOMXOIxkmth5MCjDR37wRKi1E=", "dev": true }, - "builtin-modules": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", - "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", - "dev": true - }, "bytes": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", @@ -1600,6 +1676,12 @@ "is-regex": "^1.0.3" } }, + "chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true + }, "check-error": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", @@ -1677,6 +1759,21 @@ "integrity": "sha1-T6kXw+WclKAEzWH47lCdplFocUM=", "dev": true }, + "cli-cursor": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", + "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", + "dev": true, + "requires": { + "restore-cursor": "^2.0.0" + } + }, + "cli-width": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz", + "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=", + "dev": true + }, "cliui": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz", @@ -1737,12 +1834,6 @@ "delayed-stream": "~1.0.0" } }, - "commander": { - "version": "2.20.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "dev": true - }, "component-emitter": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", @@ -2205,6 +2296,15 @@ "integrity": "sha512-xLqpez+Zj9GKSnPWS0WZw1igGocZ+uua8+y+5dDNTT934N3QuY1sp2LkHzwiaYQGz60hMq0pjAshdeXm5VUOEw==", "dev": true }, + "doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "requires": { + "esutils": "^2.0.2" + } + }, "doctypes": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/doctypes/-/doctypes-1.1.0.tgz", @@ -2253,6 +2353,12 @@ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, "encodeurl": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", @@ -2334,12 +2440,150 @@ "source-map": "~0.6.1" } }, + "eslint": { + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-5.16.0.tgz", + "integrity": "sha512-S3Rz11i7c8AA5JPv7xAH+dOyq/Cu/VXHiHXBPOU1k/JAM5dXqQPt3qcrhpHSorXmrpu2g0gkIBVXAqCpzfoZIg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "ajv": "^6.9.1", + "chalk": "^2.1.0", + "cross-spawn": "^6.0.5", + "debug": "^4.0.1", + "doctrine": "^3.0.0", + "eslint-scope": "^4.0.3", + "eslint-utils": "^1.3.1", + "eslint-visitor-keys": "^1.0.0", + "espree": "^5.0.1", + "esquery": "^1.0.1", + "esutils": "^2.0.2", + "file-entry-cache": "^5.0.1", + "functional-red-black-tree": "^1.0.1", + "glob": "^7.1.2", + "globals": "^11.7.0", + "ignore": "^4.0.6", + "import-fresh": "^3.0.0", + "imurmurhash": "^0.1.4", + "inquirer": "^6.2.2", + "js-yaml": "^3.13.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.3.0", + "lodash": "^4.17.11", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "optionator": "^0.8.2", + "path-is-inside": "^1.0.2", + "progress": "^2.0.0", + "regexpp": "^2.0.1", + "semver": "^5.5.1", + "strip-ansi": "^4.0.0", + "strip-json-comments": "^2.0.1", + "table": "^5.2.3", + "text-table": "^0.2.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "eslint-scope": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.3.tgz", + "integrity": "sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg==", + "dev": true, + "requires": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + } + }, + "eslint-utils": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.0.tgz", + "integrity": "sha512-7ehnzPaP5IIEh1r1tkjuIrxqhNkzUJa9z3R92tLJdZIVdWaczEhr3EbhGtsMrVxi1KeR8qA7Off6SWc5WNQqyQ==", + "dev": true, + "requires": { + "eslint-visitor-keys": "^1.0.0" + } + }, + "eslint-visitor-keys": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", + "integrity": "sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==", + "dev": true + }, + "espree": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-5.0.1.tgz", + "integrity": "sha512-qWAZcWh4XE/RwzLJejfcofscgMc9CamR6Tn1+XRXNzrvUSSbiAjGOI/fggztjIi7y9VLPqnICMIPiGyr8JaZ0A==", + "dev": true, + "requires": { + "acorn": "^6.0.7", + "acorn-jsx": "^5.0.0", + "eslint-visitor-keys": "^1.0.0" + }, + "dependencies": { + "acorn": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.2.0.tgz", + "integrity": "sha512-8oe72N3WPMjA+2zVG71Ia0nXZ8DpQH+QyyHO+p06jT8eg8FGG3FbcUIi8KziHlAfheJQZeoqbvq1mQSQHXKYLw==", + "dev": true + } + } + }, "esprima": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", "dev": true }, + "esquery": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.1.tgz", + "integrity": "sha512-SmiyZ5zIWH9VM+SRUReLS5Q8a7GxtRdxEBVZpm98rJM7Sb+A9DVCndXfkeFUd3byderg+EbDkfnevfCwynWaNA==", + "dev": true, + "requires": { + "estraverse": "^4.0.0" + } + }, + "esrecurse": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", + "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "dev": true, + "requires": { + "estraverse": "^4.1.0" + } + }, "estraverse": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", @@ -2539,6 +2783,17 @@ } } }, + "external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dev": true, + "requires": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + } + }, "extglob": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", @@ -2654,6 +2909,24 @@ "request": "^2.79.0" } }, + "figures": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", + "dev": true, + "requires": { + "escape-string-regexp": "^1.0.5" + } + }, + "file-entry-cache": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-5.0.1.tgz", + "integrity": "sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g==", + "dev": true, + "requires": { + "flat-cache": "^2.0.1" + } + }, "fill-range": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", @@ -2700,6 +2973,23 @@ "locate-path": "^3.0.0" } }, + "flat-cache": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz", + "integrity": "sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA==", + "dev": true, + "requires": { + "flatted": "^2.0.0", + "rimraf": "2.6.3", + "write": "1.0.3" + } + }, + "flatted": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.1.tgz", + "integrity": "sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg==", + "dev": true + }, "for-in": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", @@ -3383,6 +3673,12 @@ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" }, + "functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", + "dev": true + }, "gauge": { "version": "2.7.4", "resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz", @@ -3752,12 +4048,36 @@ "safer-buffer": ">= 2.1.2 < 3" } }, + "ignore": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "dev": true + }, "ignore-by-default": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", "integrity": "sha1-SMptcvbGo68Aqa1K5odr44ieKwk=", "dev": true }, + "import-fresh": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.1.0.tgz", + "integrity": "sha512-PpuksHKGt8rXfWEr9m9EHIpgyyaltBy8+eF6GJM0QCAxMgxCfucMF3mjecK2QsJr0amJW7gTqh5/wht0z2UhEQ==", + "dev": true, + "requires": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "dependencies": { + "resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true + } + } + }, "import-lazy": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-2.1.0.tgz", @@ -3816,6 +4136,27 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", "dev": true }, + "inquirer": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.5.0.tgz", + "integrity": "sha512-scfHejeG/lVZSpvCXpsB4j/wQNPM5JC8kiElOI0OUTwmc1RTpXr4H32/HOlQHcZiYl2z2VElwuCVDRG8vFmbnA==", + "dev": true, + "requires": { + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", + "cli-cursor": "^2.1.0", + "cli-width": "^2.0.0", + "external-editor": "^3.0.3", + "figures": "^2.0.0", + "lodash": "^4.17.12", + "mute-stream": "0.0.7", + "run-async": "^2.2.0", + "rxjs": "^6.4.0", + "string-width": "^2.1.0", + "strip-ansi": "^5.1.0", + "through": "^2.3.6" + } + }, "interpret": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz", @@ -4855,6 +5196,12 @@ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" }, + "json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", + "dev": true + }, "json-stringify-safe": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", @@ -4986,6 +5333,12 @@ "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=", "dev": true }, + "lodash.unescape": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.unescape/-/lodash.unescape-4.0.1.tgz", + "integrity": "sha1-vyJJiGzlFM2hEvrpIYzcBlIR/Jw=", + "dev": true + }, "longest": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz", @@ -5450,6 +5803,12 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" }, + "mute-stream": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", + "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=", + "dev": true + }, "nan": { "version": "2.13.2", "resolved": "https://registry.npmjs.org/nan/-/nan-2.13.2.tgz", @@ -5841,6 +6200,23 @@ "wrappy": "1" } }, + "onetime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", + "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", + "dev": true, + "requires": { + "mimic-fn": "^1.0.0" + }, + "dependencies": { + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", + "dev": true + } + } + }, "optimist": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", @@ -5983,6 +6359,15 @@ "semver": "^5.1.0" } }, + "parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "requires": { + "callsites": "^3.0.0" + } + }, "parse-json": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", @@ -6198,6 +6583,12 @@ "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=", "dev": true }, + "progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true + }, "promise": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz", @@ -6510,6 +6901,12 @@ "resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-1.0.0.tgz", "integrity": "sha512-TuAasHQNamyyJ2hb97IuBEif4qBHGjPHBS64sZwytpLEqtBQ1gPJTnOaQ6qmpET16cK14kkjbazl6+p0RRv0yw==" }, + "regexpp": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-2.0.1.tgz", + "integrity": "sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw==", + "dev": true + }, "registry-auth-token": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", @@ -6676,6 +7073,16 @@ "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", "dev": true }, + "restore-cursor": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", + "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", + "dev": true, + "requires": { + "onetime": "^2.0.0", + "signal-exit": "^3.0.2" + } + }, "ret": { "version": "0.1.15", "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", @@ -6705,6 +7112,15 @@ "integrity": "sha512-6FomvYPfs+Jy9TfXmBpBuMWNH94SgCsZmJKcanySzgNNP6LjWxBvyLTa9KaMfDDM5oxRfrKDB0r/qeRsLwnBfA==", "dev": true }, + "run-async": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.3.0.tgz", + "integrity": "sha1-A3GrSuC91yDUFm19/aZP96RFpsA=", + "dev": true, + "requires": { + "is-promise": "^2.1.0" + } + }, "rxjs": { "version": "6.5.2", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", @@ -7158,6 +7574,17 @@ "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", "dev": true }, + "slice-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz", + "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.0", + "astral-regex": "^1.0.0", + "is-fullwidth-code-point": "^2.0.0" + } + }, "sliced": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", @@ -7631,6 +8058,31 @@ "integrity": "sha1-rifbOPZgp64uHDt9G8KQgZuFGeY=", "dev": true }, + "table": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/table/-/table-5.4.1.tgz", + "integrity": "sha512-E6CK1/pZe2N75rGZQotFOdmzWQ1AILtgYbMAbAjvms0S1l5IDB47zG3nCnFGB/w+7nB3vKofbLXCH7HPBo864w==", + "dev": true, + "requires": { + "ajv": "^6.9.1", + "lodash": "^4.17.11", + "slice-ansi": "^2.1.0", + "string-width": "^3.0.0" + }, + "dependencies": { + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + } + } + }, "tar": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/tar/-/tar-2.2.2.tgz", @@ -7697,18 +8149,39 @@ "require-main-filename": "^2.0.0" } }, + "text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "dev": true + }, "throat": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/throat/-/throat-4.1.0.tgz", "integrity": "sha1-iQN8vJLFarGJJua6TLsgDhVnKmo=", "dev": true }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true + }, "timed-out": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-4.0.1.tgz", "integrity": "sha1-8y6srFoXW+ol1/q1Zas+2HQe9W8=", "dev": true }, + "tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "requires": { + "os-tmpdir": "~1.0.2" + } + }, "tmpl": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.4.tgz", @@ -7886,49 +8359,11 @@ "integrity": "sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ==", "dev": true }, - "tslint": { - "version": "5.18.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.18.0.tgz", - "integrity": "sha512-Q3kXkuDEijQ37nXZZLKErssQVnwCV/+23gFEMROi8IlbaBG6tXqLPQJ5Wjcyt/yHPKBC+hD5SzuGaMora+ZS6w==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "builtin-modules": "^1.1.1", - "chalk": "^2.3.0", - "commander": "^2.12.1", - "diff": "^3.2.0", - "glob": "^7.1.1", - "js-yaml": "^3.13.1", - "minimatch": "^3.0.4", - "mkdirp": "^0.5.1", - "resolve": "^1.3.2", - "semver": "^5.3.0", - "tslib": "^1.8.0", - "tsutils": "^2.29.0" - }, - "dependencies": { - "diff": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", - "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", - "dev": true - } - } - }, "tsscmp": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz", "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==" }, - "tsutils": { - "version": "2.29.0", - "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.29.0.tgz", - "integrity": "sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA==", - "dev": true, - "requires": { - "tslib": "^1.8.1" - } - }, "tunnel-agent": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", @@ -8395,6 +8830,15 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, + "write": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/write/-/write-1.0.3.tgz", + "integrity": "sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig==", + "dev": true, + "requires": { + "mkdirp": "^0.5.1" + } + }, "write-file-atomic": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.1.tgz", diff --git a/package.json b/package.json index 6d40bd9..597056e 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "license": "MIT", "scripts": { "start": "npm run serve", - "build": "npm run build-sass && npm run build-ts && npm run tslint && npm run copy-static-assets", + "build": "npm run build-sass && npm run build-ts && npm run lint && npm run copy-static-assets", "serve": "node dist/server.js", "watch-node": "nodemon dist/server.js", "watch": "concurrently -k -p \"[{name}]\" -n \"Sass,TypeScript,Node\" -c \"yellow.bold,cyan.bold,green.bold\" \"npm run watch-sass\" \"npm run watch-ts\" \"npm run watch-node\"", @@ -20,7 +20,7 @@ "watch-ts": "tsc -w", "build-sass": "node-sass src/public/css/main.scss dist/public/css/main.css", "watch-sass": "node-sass -w src/public/css/main.scss dist/public/css/main.css", - "tslint": "tslint -c tslint.json -p tsconfig.json", + "lint": "tsc --noEmit && eslint '*/**/*.{js,ts}' --quiet --fix", "copy-static-assets": "ts-node copyStaticAssets.ts", "debug": "npm run build && npm run watch-debug", "serve-debug": "nodemon --inspect dist/server.js", @@ -57,6 +57,7 @@ "@types/bcrypt-nodejs": "^0.0.30", "@types/bluebird": "^3.5.27", "@types/body-parser": "^1.17.0", + "@types/chai": "^4.1.7", "@types/compression": "^0.0.36", "@types/connect-mongo": "^0.0.42", "@types/dotenv": "^6.1.1", @@ -80,8 +81,11 @@ "@types/shelljs": "^0.8.5", "@types/supertest": "^2.0.7", "@types/winston": "^2.3.9", + "@typescript-eslint/eslint-plugin": "^1.12.0", + "@typescript-eslint/parser": "^1.12.0", "chai": "^4.2.0", "concurrently": "^4.1.0", + "eslint": "^5.0.0", "jest": "^24.8.0", "node-sass": "^4.12.0", "nodemon": "^1.19.1", @@ -89,7 +93,6 @@ "supertest": "^4.0.2", "ts-jest": "^24.0.2", "ts-node": "^8.3.0", - "tslint": "^5.18.0", "typescript": "^3.5.2" } } diff --git a/src/app.ts b/src/app.ts index ddcca64..42ac910 100644 --- a/src/app.ts +++ b/src/app.ts @@ -29,13 +29,13 @@ const app = express(); // Connect to MongoDB const mongoUrl = MONGODB_URI; -(mongoose).Promise = bluebird; +mongoose.Promise = bluebird; mongoose.connect(mongoUrl, { useNewUrlParser: true} ).then( - () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ }, + () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ }, ).catch(err => { - console.log("MongoDB connection error. Please make sure MongoDB is running. " + err); - // process.exit(); + console.log("MongoDB connection error. Please make sure MongoDB is running. " + err); + // process.exit(); }); // Express configuration @@ -46,13 +46,13 @@ app.use(compression()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(session({ - resave: true, - saveUninitialized: true, - secret: SESSION_SECRET, - store: new MongoStore({ - url: mongoUrl, - autoReconnect: true - }) + resave: true, + saveUninitialized: true, + secret: SESSION_SECRET, + store: new MongoStore({ + url: mongoUrl, + autoReconnect: true + }) })); app.use(passport.initialize()); app.use(passport.session()); @@ -60,26 +60,26 @@ app.use(flash()); app.use(lusca.xframe("SAMEORIGIN")); app.use(lusca.xssProtection(true)); app.use((req, res, next) => { - res.locals.user = req.user; - next(); + res.locals.user = req.user; + next(); }); app.use((req, res, next) => { - // After successful login, redirect back to the intended page - if (!req.user && + // After successful login, redirect back to the intended page + if (!req.user && req.path !== "/login" && req.path !== "/signup" && !req.path.match(/^\/auth/) && !req.path.match(/\./)) { - req.session.returnTo = req.path; - } else if (req.user && + req.session.returnTo = req.path; + } else if (req.user && req.path == "/account") { - req.session.returnTo = req.path; - } - next(); + req.session.returnTo = req.path; + } + next(); }); app.use( - express.static(path.join(__dirname, "public"), { maxAge: 31557600000 }) + express.static(path.join(__dirname, "public"), { maxAge: 31557600000 }) ); /** @@ -114,7 +114,7 @@ app.get("/api/facebook", passportConfig.isAuthenticated, passportConfig.isAuthor */ app.get("/auth/facebook", passport.authenticate("facebook", { scope: ["email", "public_profile"] })); app.get("/auth/facebook/callback", passport.authenticate("facebook", { failureRedirect: "/login" }), (req, res) => { - res.redirect(req.session.returnTo || "/"); + res.redirect(req.session.returnTo || "/"); }); export default app; diff --git a/src/config/passport.ts b/src/config/passport.ts index adc7928..dca2080 100644 --- a/src/config/passport.ts +++ b/src/config/passport.ts @@ -11,13 +11,13 @@ const LocalStrategy = passportLocal.Strategy; const FacebookStrategy = passportFacebook.Strategy; passport.serializeUser((user, done) => { - done(undefined, user.id); + done(undefined, user.id); }); passport.deserializeUser((id, done) => { - User.findById(id, (err, user) => { - done(err, user); - }); + User.findById(id, (err, user) => { + done(err, user); + }); }); @@ -25,19 +25,19 @@ passport.deserializeUser((id, done) => { * Sign in using Email and Password. */ passport.use(new LocalStrategy({ usernameField: "email" }, (email, password, done) => { - User.findOne({ email: email.toLowerCase() }, (err, user: any) => { - if (err) { return done(err); } - if (!user) { - return done(undefined, false, { message: `Email ${email} not found.` }); - } - user.comparePassword(password, (err: Error, isMatch: boolean) => { - if (err) { return done(err); } - if (isMatch) { - return done(undefined, user); - } - return done(undefined, false, { message: "Invalid email or password." }); + User.findOne({ email: email.toLowerCase() }, (err, user: any) => { + if (err) { return done(err); } + if (!user) { + return done(undefined, false, { message: `Email ${email} not found.` }); + } + user.comparePassword(password, (err: Error, isMatch: boolean) => { + if (err) { return done(err); } + if (isMatch) { + return done(undefined, user); + } + return done(undefined, false, { message: "Invalid email or password." }); + }); }); - }); })); @@ -61,81 +61,81 @@ passport.use(new LocalStrategy({ usernameField: "email" }, (email, password, don * Sign in with Facebook. */ passport.use(new FacebookStrategy({ - clientID: process.env.FACEBOOK_ID, - clientSecret: process.env.FACEBOOK_SECRET, - callbackURL: "/auth/facebook/callback", - profileFields: ["name", "email", "link", "locale", "timezone"], - passReqToCallback: true + clientID: process.env.FACEBOOK_ID, + clientSecret: process.env.FACEBOOK_SECRET, + callbackURL: "/auth/facebook/callback", + profileFields: ["name", "email", "link", "locale", "timezone"], + passReqToCallback: true }, (req: any, accessToken, refreshToken, profile, done) => { - if (req.user) { - User.findOne({ facebook: profile.id }, (err, existingUser) => { - if (err) { return done(err); } - if (existingUser) { - req.flash("errors", { msg: "There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account." }); - done(err); - } else { - User.findById(req.user.id, (err, user: any) => { - if (err) { return done(err); } - user.facebook = profile.id; - user.tokens.push({ kind: "facebook", accessToken }); - user.profile.name = user.profile.name || `${profile.name.givenName} ${profile.name.familyName}`; - user.profile.gender = user.profile.gender || profile._json.gender; - user.profile.picture = user.profile.picture || `https://graph.facebook.com/${profile.id}/picture?type=large`; - user.save((err: Error) => { - req.flash("info", { msg: "Facebook account has been linked." }); - done(err, user); - }); + if (req.user) { + User.findOne({ facebook: profile.id }, (err, existingUser) => { + if (err) { return done(err); } + if (existingUser) { + req.flash("errors", { msg: "There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account." }); + done(err); + } else { + User.findById(req.user.id, (err, user: any) => { + if (err) { return done(err); } + user.facebook = profile.id; + user.tokens.push({ kind: "facebook", accessToken }); + user.profile.name = user.profile.name || `${profile.name.givenName} ${profile.name.familyName}`; + user.profile.gender = user.profile.gender || profile._json.gender; + user.profile.picture = user.profile.picture || `https://graph.facebook.com/${profile.id}/picture?type=large`; + user.save((err: Error) => { + req.flash("info", { msg: "Facebook account has been linked." }); + done(err, user); + }); + }); + } }); - } - }); - } else { - User.findOne({ facebook: profile.id }, (err, existingUser) => { - if (err) { return done(err); } - if (existingUser) { - return done(undefined, existingUser); - } - User.findOne({ email: profile._json.email }, (err, existingEmailUser) => { - if (err) { return done(err); } - if (existingEmailUser) { - req.flash("errors", { msg: "There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings." }); - done(err); - } else { - const user: any = new User(); - user.email = profile._json.email; - user.facebook = profile.id; - user.tokens.push({ kind: "facebook", accessToken }); - user.profile.name = `${profile.name.givenName} ${profile.name.familyName}`; - user.profile.gender = profile._json.gender; - user.profile.picture = `https://graph.facebook.com/${profile.id}/picture?type=large`; - user.profile.location = (profile._json.location) ? profile._json.location.name : ""; - user.save((err: Error) => { - done(err, user); - }); - } - }); - }); - } + } else { + User.findOne({ facebook: profile.id }, (err, existingUser) => { + if (err) { return done(err); } + if (existingUser) { + return done(undefined, existingUser); + } + User.findOne({ email: profile._json.email }, (err, existingEmailUser) => { + if (err) { return done(err); } + if (existingEmailUser) { + req.flash("errors", { msg: "There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings." }); + done(err); + } else { + const user: any = new User(); + user.email = profile._json.email; + user.facebook = profile.id; + user.tokens.push({ kind: "facebook", accessToken }); + user.profile.name = `${profile.name.givenName} ${profile.name.familyName}`; + user.profile.gender = profile._json.gender; + user.profile.picture = `https://graph.facebook.com/${profile.id}/picture?type=large`; + user.profile.location = (profile._json.location) ? profile._json.location.name : ""; + user.save((err: Error) => { + done(err, user); + }); + } + }); + }); + } })); /** * Login Required middleware. */ export const isAuthenticated = (req: Request, res: Response, next: NextFunction) => { - if (req.isAuthenticated()) { - return next(); - } - res.redirect("/login"); + if (req.isAuthenticated()) { + return next(); + } + res.redirect("/login"); }; /** * Authorization Required middleware. */ export const isAuthorized = (req: Request, res: Response, next: NextFunction) => { - const provider = req.path.split("/").slice(-1)[0]; + const provider = req.path.split("/").slice(-1)[0]; - if (_.find(req.user.tokens, { kind: provider })) { - next(); - } else { - res.redirect(`/auth/${provider}`); - } + if (_.find(req.user.tokens, { kind: provider })) { + next(); + } else { + res.redirect(`/auth/${provider}`); + } }; diff --git a/src/controllers/api.ts b/src/controllers/api.ts index fc7a77f..e8bcfdc 100644 --- a/src/controllers/api.ts +++ b/src/controllers/api.ts @@ -9,9 +9,9 @@ import { Response, Request, NextFunction } from "express"; * List of API examples. */ export const getApi = (req: Request, res: Response) => { - res.render("api/index", { - title: "API Examples" - }); + res.render("api/index", { + title: "API Examples" + }); }; /** @@ -19,13 +19,13 @@ export const getApi = (req: Request, res: Response) => { * Facebook API example. */ export const getFacebook = (req: Request, res: Response, next: NextFunction) => { - const token = req.user.tokens.find((token: any) => token.kind === "facebook"); - graph.setAccessToken(token.accessToken); - graph.get(`${req.user.facebook}?fields=id,name,email,first_name,last_name,gender,link,locale,timezone`, (err: Error, results: graph.FacebookUser) => { - if (err) { return next(err); } - res.render("api/facebook", { - title: "Facebook API", - profile: results + const token = req.user.tokens.find((token: any) => token.kind === "facebook"); + graph.setAccessToken(token.accessToken); + graph.get(`${req.user.facebook}?fields=id,name,email,first_name,last_name,gender,link,locale,timezone`, (err: Error, results: graph.FacebookUser) => { + if (err) { return next(err); } + res.render("api/facebook", { + title: "Facebook API", + profile: results + }); }); - }); }; diff --git a/src/controllers/contact.ts b/src/controllers/contact.ts index f14925e..6a33b2c 100644 --- a/src/controllers/contact.ts +++ b/src/controllers/contact.ts @@ -3,11 +3,11 @@ import { Request, Response } from "express"; import { check, validationResult } from "express-validator"; const transporter = nodemailer.createTransport({ - service: "SendGrid", - auth: { - user: process.env.SENDGRID_USER, - pass: process.env.SENDGRID_PASSWORD - } + service: "SendGrid", + auth: { + user: process.env.SENDGRID_USER, + pass: process.env.SENDGRID_PASSWORD + } }); /** @@ -15,9 +15,9 @@ const transporter = nodemailer.createTransport({ * Contact form page. */ export const getContact = (req: Request, res: Response) => { - res.render("contact", { - title: "Contact" - }); + res.render("contact", { + title: "Contact" + }); }; /** @@ -25,30 +25,30 @@ export const getContact = (req: Request, res: Response) => { * Send a contact form via Nodemailer. */ export const postContact = (req: Request, res: Response) => { - check("name", "Name cannot be blank").not().isEmpty(); - check("email", "Email is not valid").isEmail(); - check("message", "Message cannot be blank").not().isEmpty(); + check("name", "Name cannot be blank").not().isEmpty(); + check("email", "Email is not valid").isEmail(); + check("message", "Message cannot be blank").not().isEmpty(); - const errors = validationResult(req); + const errors = validationResult(req); - if (!errors.isEmpty()) { - req.flash("errors", errors.array()); - return res.redirect("/contact"); - } + if (!errors.isEmpty()) { + req.flash("errors", errors.array()); + return res.redirect("/contact"); + } - const mailOptions = { - to: "your@email.com", - from: `${req.body.name} <${req.body.email}>`, - subject: "Contact Form", - text: req.body.message - }; + const mailOptions = { + to: "your@email.com", + from: `${req.body.name} <${req.body.email}>`, + subject: "Contact Form", + text: req.body.message + }; - transporter.sendMail(mailOptions, (err) => { - if (err) { - req.flash("errors", { msg: err.message }); - return res.redirect("/contact"); - } - req.flash("success", { msg: "Email has been sent successfully!" }); - res.redirect("/contact"); - }); + transporter.sendMail(mailOptions, (err) => { + if (err) { + req.flash("errors", { msg: err.message }); + return res.redirect("/contact"); + } + req.flash("success", { msg: "Email has been sent successfully!" }); + res.redirect("/contact"); + }); }; diff --git a/src/controllers/home.ts b/src/controllers/home.ts index 3f3bc20..4380717 100644 --- a/src/controllers/home.ts +++ b/src/controllers/home.ts @@ -5,7 +5,7 @@ import { Request, Response } from "express"; * Home page. */ export const index = (req: Request, res: Response) => { - res.render("home", { - title: "Home" - }); + res.render("home", { + title: "Home" + }); }; diff --git a/src/controllers/user.ts b/src/controllers/user.ts index 4c4865a..a7e4c14 100644 --- a/src/controllers/user.ts +++ b/src/controllers/user.ts @@ -14,12 +14,12 @@ import "../config/passport"; * Login page. */ export const getLogin = (req: Request, res: Response) => { - if (req.user) { - return res.redirect("/"); - } - res.render("account/login", { - title: "Login" - }); + if (req.user) { + return res.redirect("/"); + } + res.render("account/login", { + title: "Login" + }); }; /** @@ -27,29 +27,30 @@ export const getLogin = (req: Request, res: Response) => { * Sign in using email and password. */ export const postLogin = (req: Request, res: Response, next: NextFunction) => { - check("email", "Email is not valid").isEmail(); - check("password", "Password cannot be blank").isLength({min: 1}); - sanitize("email").normalizeEmail({ gmail_remove_dots: false }); - - const errors = validationResult(req); - - if (!errors.isEmpty()) { - req.flash("errors", errors.array()); - return res.redirect("/login"); - } - - passport.authenticate("local", (err: Error, user: UserDocument, info: IVerifyOptions) => { - if (err) { return next(err); } - if (!user) { - req.flash("errors", {msg: info.message}); - return res.redirect("/login"); + check("email", "Email is not valid").isEmail(); + check("password", "Password cannot be blank").isLength({min: 1}); + // eslint-disable-next-line @typescript-eslint/camelcase + sanitize("email").normalizeEmail({ gmail_remove_dots: false }); + + const errors = validationResult(req); + + if (!errors.isEmpty()) { + req.flash("errors", errors.array()); + return res.redirect("/login"); } - req.logIn(user, (err) => { - if (err) { return next(err); } - req.flash("success", { msg: "Success! You are logged in." }); - res.redirect(req.session.returnTo || "/"); - }); - })(req, res, next); + + passport.authenticate("local", (err: Error, user: UserDocument, info: IVerifyOptions) => { + if (err) { return next(err); } + if (!user) { + req.flash("errors", {msg: info.message}); + return res.redirect("/login"); + } + req.logIn(user, (err) => { + if (err) { return next(err); } + req.flash("success", { msg: "Success! You are logged in." }); + res.redirect(req.session.returnTo || "/"); + }); + })(req, res, next); }; /** @@ -57,8 +58,8 @@ export const postLogin = (req: Request, res: Response, next: NextFunction) => { * Log out. */ export const logout = (req: Request, res: Response) => { - req.logout(); - res.redirect("/"); + req.logout(); + res.redirect("/"); }; /** @@ -66,12 +67,12 @@ export const logout = (req: Request, res: Response) => { * Signup page. */ export const getSignup = (req: Request, res: Response) => { - if (req.user) { - return res.redirect("/"); - } - res.render("account/signup", { - title: "Create Account" - }); + if (req.user) { + return res.redirect("/"); + } + res.render("account/signup", { + title: "Create Account" + }); }; /** @@ -79,39 +80,40 @@ export const getSignup = (req: Request, res: Response) => { * Create a new local account. */ export const postSignup = (req: Request, res: Response, next: NextFunction) => { - check("email", "Email is not valid").isEmail(); - check("password", "Password must be at least 4 characters long").isLength({ min: 4 }); - check("confirmPassword", "Passwords do not match").equals(req.body.password); - sanitize("email").normalizeEmail({ gmail_remove_dots: false }); - - const errors = validationResult(req); - - if (!errors.isEmpty()) { - req.flash("errors", errors.array()); - return res.redirect("/signup"); - } - - const user = new User({ - email: req.body.email, - password: req.body.password - }); - - User.findOne({ email: req.body.email }, (err, existingUser) => { - if (err) { return next(err); } - if (existingUser) { - req.flash("errors", { msg: "Account with that email address already exists." }); - return res.redirect("/signup"); + check("email", "Email is not valid").isEmail(); + check("password", "Password must be at least 4 characters long").isLength({ min: 4 }); + check("confirmPassword", "Passwords do not match").equals(req.body.password); + // eslint-disable-next-line @typescript-eslint/camelcase + sanitize("email").normalizeEmail({ gmail_remove_dots: false }); + + const errors = validationResult(req); + + if (!errors.isEmpty()) { + req.flash("errors", errors.array()); + return res.redirect("/signup"); } - user.save((err) => { - if (err) { return next(err); } - req.logIn(user, (err) => { - if (err) { - return next(err); + + const user = new User({ + email: req.body.email, + password: req.body.password + }); + + User.findOne({ email: req.body.email }, (err, existingUser) => { + if (err) { return next(err); } + if (existingUser) { + req.flash("errors", { msg: "Account with that email address already exists." }); + return res.redirect("/signup"); } - res.redirect("/"); - }); + user.save((err) => { + if (err) { return next(err); } + req.logIn(user, (err) => { + if (err) { + return next(err); + } + res.redirect("/"); + }); + }); }); - }); }; /** @@ -119,9 +121,9 @@ export const postSignup = (req: Request, res: Response, next: NextFunction) => { * Profile page. */ export const getAccount = (req: Request, res: Response) => { - res.render("account/profile", { - title: "Account Management" - }); + res.render("account/profile", { + title: "Account Management" + }); }; /** @@ -129,35 +131,36 @@ export const getAccount = (req: Request, res: Response) => { * Update profile information. */ export const postUpdateProfile = (req: Request, res: Response, next: NextFunction) => { - check("email", "Please enter a valid email address.").isEmail(); - sanitize("email").normalizeEmail({ gmail_remove_dots: false }); - - const errors = validationResult(req); - - if (!errors.isEmpty()) { - req.flash("errors", errors.array()); - return res.redirect("/account"); - } - - User.findById(req.user.id, (err, user: UserDocument) => { - if (err) { return next(err); } - user.email = req.body.email || ""; - user.profile.name = req.body.name || ""; - user.profile.gender = req.body.gender || ""; - user.profile.location = req.body.location || ""; - user.profile.website = req.body.website || ""; - user.save((err: WriteError) => { - if (err) { - if (err.code === 11000) { - req.flash("errors", { msg: "The email address you have entered is already associated with an account." }); - return res.redirect("/account"); - } - return next(err); - } - req.flash("success", { msg: "Profile information has been updated." }); - res.redirect("/account"); + check("email", "Please enter a valid email address.").isEmail(); + // eslint-disable-next-line @typescript-eslint/camelcase + sanitize("email").normalizeEmail({ gmail_remove_dots: false }); + + const errors = validationResult(req); + + if (!errors.isEmpty()) { + req.flash("errors", errors.array()); + return res.redirect("/account"); + } + + User.findById(req.user.id, (err, user: UserDocument) => { + if (err) { return next(err); } + user.email = req.body.email || ""; + user.profile.name = req.body.name || ""; + user.profile.gender = req.body.gender || ""; + user.profile.location = req.body.location || ""; + user.profile.website = req.body.website || ""; + user.save((err: WriteError) => { + if (err) { + if (err.code === 11000) { + req.flash("errors", { msg: "The email address you have entered is already associated with an account." }); + return res.redirect("/account"); + } + return next(err); + } + req.flash("success", { msg: "Profile information has been updated." }); + res.redirect("/account"); + }); }); - }); }; /** @@ -165,25 +168,25 @@ export const postUpdateProfile = (req: Request, res: Response, next: NextFunctio * Update current password. */ export const postUpdatePassword = (req: Request, res: Response, next: NextFunction) => { - check("password", "Password must be at least 4 characters long").isLength({ min: 4 }); - check("confirmPassword", "Passwords do not match").equals(req.body.password); - - const errors = validationResult(req); - - if (!errors.isEmpty()) { - req.flash("errors", errors.array()); - return res.redirect("/account"); - } - - User.findById(req.user.id, (err, user: UserDocument) => { - if (err) { return next(err); } - user.password = req.body.password; - user.save((err: WriteError) => { - if (err) { return next(err); } - req.flash("success", { msg: "Password has been changed." }); - res.redirect("/account"); + check("password", "Password must be at least 4 characters long").isLength({ min: 4 }); + check("confirmPassword", "Passwords do not match").equals(req.body.password); + + const errors = validationResult(req); + + if (!errors.isEmpty()) { + req.flash("errors", errors.array()); + return res.redirect("/account"); + } + + User.findById(req.user.id, (err, user: UserDocument) => { + if (err) { return next(err); } + user.password = req.body.password; + user.save((err: WriteError) => { + if (err) { return next(err); } + req.flash("success", { msg: "Password has been changed." }); + res.redirect("/account"); + }); }); - }); }; /** @@ -191,12 +194,12 @@ export const postUpdatePassword = (req: Request, res: Response, next: NextFuncti * Delete user account. */ export const postDeleteAccount = (req: Request, res: Response, next: NextFunction) => { - User.remove({ _id: req.user.id }, (err) => { - if (err) { return next(err); } - req.logout(); - req.flash("info", { msg: "Your account has been deleted." }); - res.redirect("/"); - }); + User.remove({ _id: req.user.id }, (err) => { + if (err) { return next(err); } + req.logout(); + req.flash("info", { msg: "Your account has been deleted." }); + res.redirect("/"); + }); }; /** @@ -204,17 +207,17 @@ export const postDeleteAccount = (req: Request, res: Response, next: NextFunctio * Unlink OAuth provider. */ export const getOauthUnlink = (req: Request, res: Response, next: NextFunction) => { - const provider = req.params.provider; - User.findById(req.user.id, (err, user: any) => { - if (err) { return next(err); } - user[provider] = undefined; - user.tokens = user.tokens.filter((token: AuthToken) => token.kind !== provider); - user.save((err: WriteError) => { - if (err) { return next(err); } - req.flash("info", { msg: `${provider} account has been unlinked.` }); - res.redirect("/account"); + const provider = req.params.provider; + User.findById(req.user.id, (err, user: any) => { + if (err) { return next(err); } + user[provider] = undefined; + user.tokens = user.tokens.filter((token: AuthToken) => token.kind !== provider); + user.save((err: WriteError) => { + if (err) { return next(err); } + req.flash("info", { msg: `${provider} account has been unlinked.` }); + res.redirect("/account"); + }); }); - }); }; /** @@ -222,22 +225,22 @@ export const getOauthUnlink = (req: Request, res: Response, next: NextFunction) * Reset Password page. */ export const getReset = (req: Request, res: Response, next: NextFunction) => { - if (req.isAuthenticated()) { - return res.redirect("/"); - } - User - .findOne({ passwordResetToken: req.params.token }) - .where("passwordResetExpires").gt(Date.now()) - .exec((err, user) => { - if (err) { return next(err); } - if (!user) { - req.flash("errors", { msg: "Password reset token is invalid or has expired." }); - return res.redirect("/forgot"); - } - res.render("account/reset", { - title: "Password Reset" - }); - }); + if (req.isAuthenticated()) { + return res.redirect("/"); + } + User + .findOne({ passwordResetToken: req.params.token }) + .where("passwordResetExpires").gt(Date.now()) + .exec((err, user) => { + if (err) { return next(err); } + if (!user) { + req.flash("errors", { msg: "Password reset token is invalid or has expired." }); + return res.redirect("/forgot"); + } + res.render("account/reset", { + title: "Password Reset" + }); + }); }; /** @@ -245,61 +248,61 @@ export const getReset = (req: Request, res: Response, next: NextFunction) => { * Process the reset password request. */ export const postReset = (req: Request, res: Response, next: NextFunction) => { - check("password", "Password must be at least 4 characters long.").isLength({ min: 4 }); - check("confirm", "Passwords must match.").equals(req.body.password); + check("password", "Password must be at least 4 characters long.").isLength({ min: 4 }); + check("confirm", "Passwords must match.").equals(req.body.password); - const errors = validationResult(req); + const errors = validationResult(req); - if (!errors.isEmpty()) { - req.flash("errors", errors.array()); - return res.redirect("back"); - } + if (!errors.isEmpty()) { + req.flash("errors", errors.array()); + return res.redirect("back"); + } - async.waterfall([ - function resetPassword(done: Function) { - User - .findOne({ passwordResetToken: req.params.token }) - .where("passwordResetExpires").gt(Date.now()) - .exec((err, user: any) => { - if (err) { return next(err); } - if (!user) { - req.flash("errors", { msg: "Password reset token is invalid or has expired." }); - return res.redirect("back"); - } - user.password = req.body.password; - user.passwordResetToken = undefined; - user.passwordResetExpires = undefined; - user.save((err: WriteError) => { - if (err) { return next(err); } - req.logIn(user, (err) => { - done(err, user); + async.waterfall([ + function resetPassword(done: Function) { + User + .findOne({ passwordResetToken: req.params.token }) + .where("passwordResetExpires").gt(Date.now()) + .exec((err, user: any) => { + if (err) { return next(err); } + if (!user) { + req.flash("errors", { msg: "Password reset token is invalid or has expired." }); + return res.redirect("back"); + } + user.password = req.body.password; + user.passwordResetToken = undefined; + user.passwordResetExpires = undefined; + user.save((err: WriteError) => { + if (err) { return next(err); } + req.logIn(user, (err) => { + done(err, user); + }); + }); + }); + }, + function sendResetPasswordEmail(user: UserDocument, done: Function) { + const transporter = nodemailer.createTransport({ + service: "SendGrid", + auth: { + user: process.env.SENDGRID_USER, + pass: process.env.SENDGRID_PASSWORD + } + }); + const mailOptions = { + to: user.email, + from: "express-ts@starter.com", + subject: "Your password has been changed", + text: `Hello,\n\nThis is a confirmation that the password for your account ${user.email} has just been changed.\n` + }; + transporter.sendMail(mailOptions, (err) => { + req.flash("success", { msg: "Success! Your password has been changed." }); + done(err); }); - }); - }); - }, - function sendResetPasswordEmail(user: UserDocument, done: Function) { - const transporter = nodemailer.createTransport({ - service: "SendGrid", - auth: { - user: process.env.SENDGRID_USER, - pass: process.env.SENDGRID_PASSWORD } - }); - const mailOptions = { - to: user.email, - from: "express-ts@starter.com", - subject: "Your password has been changed", - text: `Hello,\n\nThis is a confirmation that the password for your account ${user.email} has just been changed.\n` - }; - transporter.sendMail(mailOptions, (err) => { - req.flash("success", { msg: "Success! Your password has been changed." }); - done(err); - }); - } - ], (err) => { - if (err) { return next(err); } - res.redirect("/"); - }); + ], (err) => { + if (err) { return next(err); } + res.redirect("/"); + }); }; /** @@ -307,12 +310,12 @@ export const postReset = (req: Request, res: Response, next: NextFunction) => { * Forgot Password page. */ export const getForgot = (req: Request, res: Response) => { - if (req.isAuthenticated()) { - return res.redirect("/"); - } - res.render("account/forgot", { - title: "Forgot Password" - }); + if (req.isAuthenticated()) { + return res.redirect("/"); + } + res.render("account/forgot", { + title: "Forgot Password" + }); }; /** @@ -320,61 +323,62 @@ export const getForgot = (req: Request, res: Response) => { * Create a random token, then the send user an email with a reset link. */ export const postForgot = (req: Request, res: Response, next: NextFunction) => { - check("email", "Please enter a valid email address.").isEmail(); - sanitize("email").normalizeEmail({ gmail_remove_dots: false }); - - const errors = validationResult(req); - - if (!errors.isEmpty()) { - req.flash("errors", errors.array()); - return res.redirect("/forgot"); - } - - async.waterfall([ - function createRandomToken(done: Function) { - crypto.randomBytes(16, (err, buf) => { - const token = buf.toString("hex"); - done(err, token); - }); - }, - function setRandomToken(token: AuthToken, done: Function) { - User.findOne({ email: req.body.email }, (err, user: any) => { - if (err) { return done(err); } - if (!user) { - req.flash("errors", { msg: "Account with that email address does not exist." }); - return res.redirect("/forgot"); - } - user.passwordResetToken = token; - user.passwordResetExpires = Date.now() + 3600000; // 1 hour - user.save((err: WriteError) => { - done(err, token, user); - }); - }); - }, - function sendForgotPasswordEmail(token: AuthToken, user: UserDocument, done: Function) { - const transporter = nodemailer.createTransport({ - service: "SendGrid", - auth: { - user: process.env.SENDGRID_USER, - pass: process.env.SENDGRID_PASSWORD - } - }); - const mailOptions = { - to: user.email, - from: "hackathon@starter.com", - subject: "Reset your password on Hackathon Starter", - text: `You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n + check("email", "Please enter a valid email address.").isEmail(); + // eslint-disable-next-line @typescript-eslint/camelcase + sanitize("email").normalizeEmail({ gmail_remove_dots: false }); + + const errors = validationResult(req); + + if (!errors.isEmpty()) { + req.flash("errors", errors.array()); + return res.redirect("/forgot"); + } + + async.waterfall([ + function createRandomToken(done: Function) { + crypto.randomBytes(16, (err, buf) => { + const token = buf.toString("hex"); + done(err, token); + }); + }, + function setRandomToken(token: AuthToken, done: Function) { + User.findOne({ email: req.body.email }, (err, user: any) => { + if (err) { return done(err); } + if (!user) { + req.flash("errors", { msg: "Account with that email address does not exist." }); + return res.redirect("/forgot"); + } + user.passwordResetToken = token; + user.passwordResetExpires = Date.now() + 3600000; // 1 hour + user.save((err: WriteError) => { + done(err, token, user); + }); + }); + }, + function sendForgotPasswordEmail(token: AuthToken, user: UserDocument, done: Function) { + const transporter = nodemailer.createTransport({ + service: "SendGrid", + auth: { + user: process.env.SENDGRID_USER, + pass: process.env.SENDGRID_PASSWORD + } + }); + const mailOptions = { + to: user.email, + from: "hackathon@starter.com", + subject: "Reset your password on Hackathon Starter", + text: `You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n Please click on the following link, or paste this into your browser to complete the process:\n\n http://${req.headers.host}/reset/${token}\n\n If you did not request this, please ignore this email and your password will remain unchanged.\n` - }; - transporter.sendMail(mailOptions, (err) => { - req.flash("info", { msg: `An e-mail has been sent to ${user.email} with further instructions.` }); - done(err); - }); - } - ], (err) => { - if (err) { return next(err); } - res.redirect("/forgot"); - }); + }; + transporter.sendMail(mailOptions, (err) => { + req.flash("info", { msg: `An e-mail has been sent to ${user.email} with further instructions.` }); + done(err); + }); + } + ], (err) => { + if (err) { return next(err); } + res.redirect("/forgot"); + }); }; diff --git a/src/models/User.ts b/src/models/User.ts index fb939d3..0157e6f 100644 --- a/src/models/User.ts +++ b/src/models/User.ts @@ -3,73 +3,73 @@ import crypto from "crypto"; import mongoose from "mongoose"; export type UserDocument = mongoose.Document & { - email: string, - password: string, - passwordResetToken: string, - passwordResetExpires: Date, + email: string; + password: string; + passwordResetToken: string; + passwordResetExpires: Date; - facebook: string, - tokens: AuthToken[], + facebook: string; + tokens: AuthToken[]; - profile: { - name: string, - gender: string, - location: string, - website: string, - picture: string - }, + profile: { + name: string; + gender: string; + location: string; + website: string; + picture: string; + }; - comparePassword: comparePasswordFunction, - gravatar: (size: number) => string + comparePassword: comparePasswordFunction; + gravatar: (size: number) => string; }; type comparePasswordFunction = (candidatePassword: string, cb: (err: any, isMatch: any) => {}) => void; -export type AuthToken = { - accessToken: string, - kind: string -}; +export interface AuthToken { + accessToken: string; + kind: string; +} const userSchema = new mongoose.Schema({ - email: { type: String, unique: true }, - password: String, - passwordResetToken: String, - passwordResetExpires: Date, + email: { type: String, unique: true }, + password: String, + passwordResetToken: String, + passwordResetExpires: Date, - facebook: String, - twitter: String, - google: String, - tokens: Array, + facebook: String, + twitter: String, + google: String, + tokens: Array, - profile: { - name: String, - gender: String, - location: String, - website: String, - picture: String - } + profile: { + name: String, + gender: String, + location: String, + website: String, + picture: String + } }, { timestamps: true }); /** * Password hash middleware. */ userSchema.pre("save", function save(next) { - const user = this as UserDocument; - if (!user.isModified("password")) { return next(); } - bcrypt.genSalt(10, (err, salt) => { - if (err) { return next(err); } - bcrypt.hash(user.password, salt, undefined, (err: mongoose.Error, hash) => { - if (err) { return next(err); } - user.password = hash; - next(); + const user = this as UserDocument; + if (!user.isModified("password")) { return next(); } + bcrypt.genSalt(10, (err, salt) => { + if (err) { return next(err); } + bcrypt.hash(user.password, salt, undefined, (err: mongoose.Error, hash) => { + if (err) { return next(err); } + user.password = hash; + next(); + }); }); - }); }); const comparePassword: comparePasswordFunction = function (candidatePassword, cb) { - bcrypt.compare(candidatePassword, this.password, (err: mongoose.Error, isMatch: boolean) => { - cb(err, isMatch); - }); + bcrypt.compare(candidatePassword, this.password, (err: mongoose.Error, isMatch: boolean) => { + cb(err, isMatch); + }); }; userSchema.methods.comparePassword = comparePassword; @@ -78,11 +78,11 @@ userSchema.methods.comparePassword = comparePassword; * Helper method for getting user's gravatar. */ userSchema.methods.gravatar = function (size: number = 200) { - if (!this.email) { - return `https://gravatar.com/avatar/?s=${size}&d=retro`; - } - const md5 = crypto.createHash("md5").update(this.email).digest("hex"); - return `https://gravatar.com/avatar/${md5}?s=${size}&d=retro`; + if (!this.email) { + return `https://gravatar.com/avatar/?s=${size}&d=retro`; + } + const md5 = crypto.createHash("md5").update(this.email).digest("hex"); + return `https://gravatar.com/avatar/${md5}?s=${size}&d=retro`; }; export const User = mongoose.model("User", userSchema); diff --git a/src/server.ts b/src/server.ts index 56f3222..c8ae8a1 100644 --- a/src/server.ts +++ b/src/server.ts @@ -11,12 +11,12 @@ app.use(errorHandler()); * Start Express server. */ const server = app.listen(app.get("port"), () => { - console.log( - " App is running at http://localhost:%d in %s mode", - app.get("port"), - app.get("env") - ); - console.log(" Press CTRL-C to stop\n"); + console.log( + " App is running at http://localhost:%d in %s mode", + app.get("port"), + app.get("env") + ); + console.log(" Press CTRL-C to stop\n"); }); export default server; diff --git a/src/util/logger.ts b/src/util/logger.ts index 5082624..74271fa 100644 --- a/src/util/logger.ts +++ b/src/util/logger.ts @@ -1,18 +1,18 @@ import { Logger, LoggerOptions, transports } from "winston"; const options: LoggerOptions = { - transports: [ - new transports.Console({ - level: process.env.NODE_ENV === "production" ? "error" : "debug" - }), - new transports.File({ filename: "debug.log", level: "debug" }) - ] + transports: [ + new transports.Console({ + level: process.env.NODE_ENV === "production" ? "error" : "debug" + }), + new transports.File({ filename: "debug.log", level: "debug" }) + ] }; const logger = new Logger(options); if (process.env.NODE_ENV !== "production") { - logger.debug("Logging initialized at debug level"); + logger.debug("Logging initialized at debug level"); } export default logger; diff --git a/test/api.test.ts b/test/api.test.ts index b0b00c9..5cd68bf 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -2,8 +2,8 @@ import request from "supertest"; import app from "../src/app"; describe("GET /api", () => { - it("should return 200 OK", () => { - return request(app).get("/api") - .expect(200); - }); + it("should return 200 OK", () => { + return request(app).get("/api") + .expect(200); + }); }); diff --git a/test/app.test.ts b/test/app.test.ts index fa81eeb..050e89f 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -2,8 +2,8 @@ import request from "supertest"; import app from "../src/app"; describe("GET /random-url", () => { - it("should return 404", (done) => { - request(app).get("/reset") - .expect(404, done); - }); + it("should return 404", (done) => { + request(app).get("/reset") + .expect(404, done); + }); }); diff --git a/test/contact.test.ts b/test/contact.test.ts index 2f1fb0d..4401997 100644 --- a/test/contact.test.ts +++ b/test/contact.test.ts @@ -1,27 +1,25 @@ import request from "supertest"; import app from "../src/app"; - -const chai = require("chai"); -const expect = chai.expect; +import { expect} from "chai"; describe("GET /contact", () => { - it("should return 200 OK", (done) => { - request(app).get("/contact") - .expect(200, done); - }); + it("should return 200 OK", (done) => { + request(app).get("/contact") + .expect(200, done); + }); }); describe("POST /contact", () => { - it("should return false from assert when no message is found", (done) => { - request(app).post("/contact") - .field("name", "John Doe") - .field("email", "john@me.com") - .end(function(err, res) { - expect(res.error).to.be.false; - done(); - }) - .expect(302); + it("should return false from assert when no message is found", (done) => { + request(app).post("/contact") + .field("name", "John Doe") + .field("email", "john@me.com") + .end(function(err, res) { + expect(res.error).to.be.false; + done(); + }) + .expect(302); - }); + }); }); \ No newline at end of file diff --git a/test/home.test.ts b/test/home.test.ts index 8649781..6e76f08 100644 --- a/test/home.test.ts +++ b/test/home.test.ts @@ -2,8 +2,8 @@ import request from "supertest"; import app from "../src/app"; describe("GET /", () => { - it("should return 200 OK", (done) => { - request(app).get("/") - .expect(200, done); - }); + it("should return 200 OK", (done) => { + request(app).get("/") + .expect(200, done); + }); }); diff --git a/test/user.test.ts b/test/user.test.ts index d511eb0..152792b 100644 --- a/test/user.test.ts +++ b/test/user.test.ts @@ -1,34 +1,32 @@ import request from "supertest"; import app from "../src/app"; - -const chai = require("chai"); -const expect = chai.expect; +import { expect } from "chai"; describe("GET /login", () => { - it("should return 200 OK", () => { - return request(app).get("/login") - .expect(200); - }); + it("should return 200 OK", () => { + return request(app).get("/login") + .expect(200); + }); }); describe("GET /signup", () => { - it("should return 200 OK", () => { - return request(app).get("/signup") - .expect(200); - }); + it("should return 200 OK", () => { + return request(app).get("/signup") + .expect(200); + }); }); describe("POST /login", () => { - it("should return some defined error message with valid parameters", (done) => { - return request(app).post("/login") - .field("email", "john@me.com") - .field("password", "Hunter2") - .expect(302) - .end(function(err, res) { - expect(res.error).not.to.be.undefined; - done(); - }); + it("should return some defined error message with valid parameters", (done) => { + return request(app).post("/login") + .field("email", "john@me.com") + .field("password", "Hunter2") + .expect(302) + .end(function(err, res) { + expect(res.error).not.to.be.undefined; + done(); + }); - }); + }); }); diff --git a/tslint.json b/tslint.json deleted file mode 100644 index 182b694..0000000 --- a/tslint.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "rules": { - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "indent": [ - true, - "spaces" - ], - "one-line": [ - true, - "check-open-brace", - "check-whitespace" - ], - "no-var-keyword": true, - "quotemark": [ - true, - "double", - "avoid-escape" - ], - "semicolon": [ - true, - "always", - "ignore-bound-class-methods" - ], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-module", - "check-separator", - "check-type" - ], - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - }, - { - "call-signature": "onespace", - "index-signature": "onespace", - "parameter": "onespace", - "property-declaration": "onespace", - "variable-declaration": "onespace" - } - ], - "no-internal-module": true, - "no-trailing-whitespace": true, - "no-null-keyword": true, - "prefer-const": true, - "jsdoc-format": true - } -} \ No newline at end of file