Change password
8 |Please enter your new password using the form below!
9 | 10 | 34 |├── .github
├── CODEOWNERS
├── ISSUE_TEMPLATE.md
├── PULL_REQUEST_TEMPLATE.md
└── workflows
│ └── main.yml
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── NOTICE
├── README.md
├── playground
├── .env-sample
├── .eslintrc
├── .gitignore
├── .prettierrc.js
├── README.md
├── package-lock.json
├── package.json
├── public
│ └── stylesheets
│ │ └── main.css
├── server
│ ├── app.js
│ ├── bin
│ │ └── start.js
│ ├── config
│ │ └── index.js
│ ├── lib
│ │ └── passport
│ │ │ └── index.js
│ ├── middlewares
│ │ └── validation.js
│ ├── models
│ │ ├── ResetTokenModel.js
│ │ ├── TodolistItemModel.js
│ │ └── UserModel.js
│ ├── routes
│ │ ├── api
│ │ │ ├── index.js
│ │ │ └── todolist
│ │ │ │ └── index.js
│ │ ├── auth
│ │ │ ├── github.js
│ │ │ ├── index.js
│ │ │ ├── login.js
│ │ │ ├── registration.js
│ │ │ ├── resetpassword.js
│ │ │ └── verification.js
│ │ ├── index.js
│ │ └── playground
│ │ │ └── index.js
│ ├── services
│ │ ├── TodolistService.js
│ │ └── UserService.js
│ └── views
│ │ ├── auth
│ │ ├── changepassword.ejs
│ │ ├── complete.ejs
│ │ ├── login.ejs
│ │ ├── registration.ejs
│ │ └── resetpassword.ejs
│ │ ├── error.ejs
│ │ ├── index.ejs
│ │ ├── myaccount.ejs
│ │ ├── partials
│ │ ├── footer.ejs
│ │ ├── header.ejs
│ │ ├── jumbotron.ejs
│ │ ├── messages.ejs
│ │ └── nav.ejs
│ │ └── playground
│ │ └── userlist.ejs
└── test
│ └── app-test.js
└── todolist
├── .eslintrc.js
├── .gitignore
├── .prettierrc
├── README.md
├── babel.config.js
├── package-lock.json
├── package.json
├── public
├── favicon.png
└── index.html
└── src
├── App.vue
├── api
└── index.js
├── assets
└── logo.png
├── components
├── CreateTodo.vue
├── Login.vue
├── Todo.vue
└── TodoList.vue
└── main.js
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | # Codeowners for these exercise files:
2 | # * (asterisk) deotes "all files and folders"
3 | # Example: * @producer @instructor
4 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
7 |
8 | ## Issue Overview
9 |
10 |
11 | ## Describe your environment
12 |
13 |
14 | ## Steps to Reproduce
15 |
16 | 1.
17 | 2.
18 | 3.
19 | 4.
20 |
21 | ## Expected Behavior
22 |
23 |
24 | ## Current Behavior
25 |
26 |
27 | ## Possible Solution
28 |
29 |
30 | ## Screenshots / Video
31 |
32 |
33 | ## Related Issues
34 |
35 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | name: Copy To Branches
2 | on:
3 | workflow_dispatch:
4 | jobs:
5 | copy-to-branches:
6 | runs-on: ubuntu-latest
7 | steps:
8 | - uses: actions/checkout@v2
9 | with:
10 | fetch-depth: 0
11 | - name: Copy To Branches Action
12 | uses: planetoftheweb/copy-to-branches@v1
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules
3 | .tmp
4 | npm-debug.log
5 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 |
2 | Contribution Agreement
3 | ======================
4 |
5 | This repository does not accept pull requests (PRs). All pull requests will be closed.
6 |
7 | However, if any contributions (through pull requests, issues, feedback or otherwise) are provided, as a contributor, you represent that the code you submit is your original work or that of your employer (in which case you represent you have the right to bind your employer). By submitting code (or otherwise providing feedback), you (and, if applicable, your employer) are licensing the submitted code (and/or feedback) to LinkedIn and the open source community subject to the BSD 2-Clause license.
8 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | LinkedIn Learning Exercise Files License Agreement
2 | ==================================================
3 |
4 | This License Agreement (the "Agreement") is a binding legal agreement
5 | between you (as an individual or entity, as applicable) and LinkedIn
6 | Corporation (“LinkedIn”). By downloading or using the LinkedIn Learning
7 | exercise files in this repository (“Licensed Materials”), you agree to
8 | be bound by the terms of this Agreement. If you do not agree to these
9 | terms, do not download or use the Licensed Materials.
10 |
11 | 1. License.
12 | - a. Subject to the terms of this Agreement, LinkedIn hereby grants LinkedIn
13 | members during their LinkedIn Learning subscription a non-exclusive,
14 | non-transferable copyright license, for internal use only, to 1) make a
15 | reasonable number of copies of the Licensed Materials, and 2) make
16 | derivative works of the Licensed Materials for the sole purpose of
17 | practicing skills taught in LinkedIn Learning courses.
18 | - b. Distribution. Unless otherwise noted in the Licensed Materials, subject
19 | to the terms of this Agreement, LinkedIn hereby grants LinkedIn members
20 | with a LinkedIn Learning subscription a non-exclusive, non-transferable
21 | copyright license to distribute the Licensed Materials, except the
22 | Licensed Materials may not be included in any product or service (or
23 | otherwise used) to instruct or educate others.
24 |
25 | 2. Restrictions and Intellectual Property.
26 | - a. You may not to use, modify, copy, make derivative works of, publish,
27 | distribute, rent, lease, sell, sublicense, assign or otherwise transfer the
28 | Licensed Materials, except as expressly set forth above in Section 1.
29 | - b. Linkedin (and its licensors) retains its intellectual property rights
30 | in the Licensed Materials. Except as expressly set forth in Section 1,
31 | LinkedIn grants no licenses.
32 | - c. You indemnify LinkedIn and its licensors and affiliates for i) any
33 | alleged infringement or misappropriation of any intellectual property rights
34 | of any third party based on modifications you make to the Licensed Materials,
35 | ii) any claims arising from your use or distribution of all or part of the
36 | Licensed Materials and iii) a breach of this Agreement. You will defend, hold
37 | harmless, and indemnify LinkedIn and its affiliates (and our and their
38 | respective employees, shareholders, and directors) from any claim or action
39 | brought by a third party, including all damages, liabilities, costs and
40 | expenses, including reasonable attorneys’ fees, to the extent resulting from,
41 | alleged to have resulted from, or in connection with: (a) your breach of your
42 | obligations herein; or (b) your use or distribution of any Licensed Materials.
43 |
44 | 3. Open source. This code may include open source software, which may be
45 | subject to other license terms as provided in the files.
46 |
47 | 4. Warranty Disclaimer. LINKEDIN PROVIDES THE LICENSED MATERIALS ON AN “AS IS”
48 | AND “AS AVAILABLE” BASIS. LINKEDIN MAKES NO REPRESENTATION OR WARRANTY,
49 | WHETHER EXPRESS OR IMPLIED, ABOUT THE LICENSED MATERIALS, INCLUDING ANY
50 | REPRESENTATION THAT THE LICENSED MATERIALS WILL BE FREE OF ERRORS, BUGS OR
51 | INTERRUPTIONS, OR THAT THE LICENSED MATERIALS ARE ACCURATE, COMPLETE OR
52 | OTHERWISE VALID. TO THE FULLEST EXTENT PERMITTED BY LAW, LINKEDIN AND ITS
53 | AFFILIATES DISCLAIM ANY IMPLIED OR STATUTORY WARRANTY OR CONDITION, INCLUDING
54 | ANY IMPLIED WARRANTY OR CONDITION OF MERCHANTABILITY OR FITNESS FOR A
55 | PARTICULAR PURPOSE, AVAILABILITY, SECURITY, TITLE AND/OR NON-INFRINGEMENT.
56 | YOUR USE OF THE LICENSED MATERIALS IS AT YOUR OWN DISCRETION AND RISK, AND
57 | YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE THAT RESULTS FROM USE OF THE
58 | LICENSED MATERIALS TO YOUR COMPUTER SYSTEM OR LOSS OF DATA. NO ADVICE OR
59 | INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM US OR THROUGH OR
60 | FROM THE LICENSED MATERIALS WILL CREATE ANY WARRANTY OR CONDITION NOT
61 | EXPRESSLY STATED IN THESE TERMS.
62 |
63 | 5. Limitation of Liability. LINKEDIN SHALL NOT BE LIABLE FOR ANY INDIRECT,
64 | INCIDENTAL, SPECIAL, PUNITIVE, CONSEQUENTIAL OR EXEMPLARY DAMAGES, INCLUDING
65 | BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA OR OTHER
66 | INTANGIBLE LOSSES . IN NO EVENT WILL LINKEDIN'S AGGREGATE LIABILITY TO YOU
67 | EXCEED $100. THIS LIMITATION OF LIABILITY SHALL:
68 | - i. APPLY REGARDLESS OF WHETHER (A) YOU BASE YOUR CLAIM ON CONTRACT, TORT,
69 | STATUTE, OR ANY OTHER LEGAL THEORY, (B) WE KNEW OR SHOULD HAVE KNOWN ABOUT
70 | THE POSSIBILITY OF SUCH DAMAGES, OR (C) THE LIMITED REMEDIES PROVIDED IN THIS
71 | SECTION FAIL OF THEIR ESSENTIAL PURPOSE; AND
72 | - ii. NOT APPLY TO ANY DAMAGE THAT LINKEDIN MAY CAUSE YOU INTENTIONALLY OR
73 | KNOWINGLY IN VIOLATION OF THESE TERMS OR APPLICABLE LAW, OR AS OTHERWISE
74 | MANDATED BY APPLICABLE LAW THAT CANNOT BE DISCLAIMED IN THESE TERMS.
75 |
76 | 6. Termination. This Agreement automatically terminates upon your breach of
77 | this Agreement or termination of your LinkedIn Learning subscription. On
78 | termination, all licenses granted under this Agreement will terminate
79 | immediately and you will delete the Licensed Materials. Sections 2-7 of this
80 | Agreement survive any termination of this Agreement. LinkedIn may discontinue
81 | the availability of some or all of the Licensed Materials at any time for any
82 | reason.
83 |
84 | 7. Miscellaneous. This Agreement will be governed by and construed in
85 | accordance with the laws of the State of California without regard to conflict
86 | of laws principles. The exclusive forum for any disputes arising out of or
87 | relating to this Agreement shall be an appropriate federal or state court
88 | sitting in the County of Santa Clara, State of California. If LinkedIn does
89 | not act to enforce a breach of this Agreement, that does not mean that
90 | LinkedIn has waived its right to enforce this Agreement. The Agreement does
91 | not create a partnership, agency relationship, or joint venture between the
92 | parties. Neither party has the power or authority to bind the other or to
93 | create any obligation or responsibility on behalf of the other. You may not,
94 | without LinkedIn’s prior written consent, assign or delegate any rights or
95 | obligations under these terms, including in connection with a change of
96 | control. Any purported assignment and delegation shall be ineffective. The
97 | Agreement shall bind and inure to the benefit of the parties, their respective
98 | successors and permitted assigns. If any provision of the Agreement is
99 | unenforceable, that provision will be modified to render it enforceable to the
100 | extent possible to give effect to the parties’ intentions and the remaining
101 | provisions will not be affected. This Agreement is the only agreement between
102 | you and LinkedIn regarding the Licensed Materials, and supersedes all prior
103 | agreements relating to the Licensed Materials.
104 |
105 | Last Updated: March 2019
106 |
--------------------------------------------------------------------------------
/NOTICE:
--------------------------------------------------------------------------------
1 | Copyright 2021 LinkedIn Corporation
2 | All Rights Reserved.
3 |
4 | Licensed under the LinkedIn Learning Exercise File License (the "License").
5 | See LICENSE in the project root for license information.
6 |
7 |
8 | ATTRIBUTIONS:
9 |
10 | ESlint
11 | https://github.com/eslint/eslint
12 | Copyright JS Foundation and other contributors
13 | License: MIT license (MIT)
14 | https://opensource.org/licenses/MIT
15 |
16 | Prittier
17 | https://github.com/prettier/prettier
18 | Copyright (c) 2016 Kent C. Dodds
19 | License: MIT license (MIT)
20 | https://opensource.org/licenses/MIT
21 |
22 | Please note, this project may automatically load third party code from external
23 | repositories (for example, NPM modules, Composer packages, or other dependencies).
24 | If so, such third party code may be subject to other license terms than as set
25 | forth above. In addition, such third party code may also depend on and load
26 | multiple tiers of dependencies. Please review the applicable licenses of the
27 | additional dependencies.
28 |
29 | =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
30 |
31 | MIT License
32 |
33 | Permission is hereby granted, free of charge, to any person obtaining a copy
34 | of this software and associated documentation files (the "Software"), to deal
35 | in the Software without restriction, including without limitation the rights
36 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
37 | copies of the Software, and to permit persons to whom the Software is
38 | furnished to do so, subject to the following conditions:
39 |
40 | The above copyright notice and this permission notice shall be included in all
41 | copies or substantial portions of the Software.
42 |
43 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
44 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
45 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
46 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
47 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
48 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
49 | SOFTWARE.
50 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Node: Authentication
2 | This is the repository for the LinkedIn Learning course Node: Authentication. The full course is available from [LinkedIn Learning][lil-course-url].
3 |
4 | ![Node: Authentication][lil-thumbnail-url]
5 |
6 | If you have a website, you want visitors. And if you run a business through a website, you want those visitors to be customers. To do that, you need user registration and authentication. Authentication is the foundation of most web applications, letting you determine who is visiting your site and helping you connect them with privileges they should or should not have. In this course, Daniel Khan shows how to add user registration and authentication to an app built with Node.js and Express.js. He covers everything from simple logins using a username and password stored in a database to more complex login methods like single sign-on. Daniel teaches this hands-on course with realistic sample projects, so that you can apply this knowledge to your own work right away.
7 |
8 | ## Instructions
9 | This repository has branches for each of the videos in the course. You can use the branch pop up menu in github to switch to a specific branch and take a look at the course at that stage, or you can add `/tree/BRANCH_NAME` to the URL to go to the branch you want to access.
10 |
11 | ## Branches
12 | The branches are structured to correspond to the videos in the course. The naming convention is `CHAPTER#_MOVIE#`. As an example, the branch named `02_03` corresponds to the second chapter and the third video in that chapter.
13 | Some branches will have a beginning and an end state. These are marked with the letters `b` for "beginning" and `e` for "end". The `b` branch contains the code as it is at the beginning of the movie. The `e` branch contains the code as it is at the end of the movie. The `main` branch holds the final state of the code when in the course.
14 |
15 | When switching from one exercise files branch to the next after making changes to the files, you may get a message like this:
16 |
17 | error: Your local changes to the following files would be overwritten by checkout: [files]
18 | Please commit your changes or stash them before you switch branches.
19 | Aborting
20 |
21 | To resolve this issue:
22 |
23 | Add changes to git using this command: git add .
24 | Commit changes using this command: git commit -m "some message"
25 |
26 | ## Installing
27 | 1. To use these exercise files, you must have the following installed:
28 | - [list of requirements for course]
29 | 2. Clone this repository into your local machine using the terminal (Mac), CMD (Windows), or a GUI tool like SourceTree.
30 | 3. [Course-specific instructions]
31 |
32 |
33 | ### Instructor
34 |
35 | Daniel Khan
36 |
37 | Technology Lead, Developer, Application Architect
38 |
39 |
40 |
41 | Check out my other courses on [LinkedIn Learning](https://www.linkedin.com/learning/instructors/daniel-khan).
42 |
43 | [lil-course-url]: https://www.linkedin.com/learning/node-authentication
44 | [lil-thumbnail-url]: https://cdn.lynda.com/course/2881188/2881188-1624987742273-16x9.jpg
45 |
--------------------------------------------------------------------------------
/playground/.env-sample:
--------------------------------------------------------------------------------
1 | GITHUB_CLIENT_ID = myclientid
2 | GITHUB_CLIENT_SECRET = myclientsecret
3 | JWTSECRET = myownsecret
--------------------------------------------------------------------------------
/playground/.eslintrc:
--------------------------------------------------------------------------------
1 | // To configure Visual Stuido Code for consistent code formating and linting,
2 | // please follow https://betterprogramming.pub/integrating-prettier-and-eslint-with-vs-code-1d2f6fb53bc9
3 |
4 | {
5 | "env": {
6 | "commonjs": true,
7 | "es6": true,
8 | "node": true
9 | },
10 | "extends": ["airbnb-base", "plugin:prettier/recommended"],
11 | "plugins": ["prettier"],
12 | "globals": {
13 | "Atomics": "readonly",
14 | "SharedArrayBuffer": "readonly"
15 | },
16 | "parserOptions": {
17 | "ecmaVersion": 2018
18 | },
19 | "rules": {
20 | "no-console": 0,
21 | "prettier/prettier": "error"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/playground/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | .DS_Store
8 | # Runtime data
9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 |
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 |
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 |
20 | # nyc test coverage
21 | .nyc_output
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 |
29 | # node-waf configuration
30 | .lock-wscript
31 |
32 | # Compiled binary addons (https://nodejs.org/api/addons.html)
33 | build/Release
34 |
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 |
39 | # TypeScript v1 declaration files
40 | typings/
41 |
42 | # Optional npm cache directory
43 | .npm
44 |
45 | # Optional eslint cache
46 | .eslintcache
47 |
48 | # Optional REPL history
49 | .node_repl_history
50 |
51 | # Output of 'npm pack'
52 | *.tgz
53 |
54 | # Yarn Integrity file
55 | .yarn-integrity
56 |
57 | # dotenv environment variables file
58 | .env
59 |
60 | # next.js build output
61 | .next
62 |
63 | ~$*.pptx
--------------------------------------------------------------------------------
/playground/.prettierrc.js:
--------------------------------------------------------------------------------
1 | // To configure Visual Stuido Code for consistent code formating and linting,
2 | // please follow https://betterprogramming.pub/integrating-prettier-and-eslint-with-vs-code-1d2f6fb53bc9
3 |
4 | module.exports = {
5 | "semi": true,
6 | "singleQuote": true,
7 | "tabWidth": 2,
8 | "useTabs": false
9 | }
10 |
--------------------------------------------------------------------------------
/playground/README.md:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/playground/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "sampleapp",
3 | "version": "0.0.0",
4 | "description": "",
5 | "private": true,
6 | "main": "app.js",
7 | "scripts": {
8 | "dev": "nodemon ./server/bin/start",
9 | "start": "node ./server/bin/start"
10 | },
11 | "dependencies": {
12 | "bcrypt": "^5.0.1",
13 | "connect-ensure-login": "^0.1.1",
14 | "cookie-parser": "^1.4.4",
15 | "cookie-session": "^1.4.0",
16 | "cors": "^2.8.5",
17 | "dotenv": "^8.2.0",
18 | "ejs": "^2.6.2",
19 | "express": "^4.17.1",
20 | "express-validator": "^6.10.0",
21 | "http-errors": "^1.7.3",
22 | "jsonwebtoken": "^8.5.1",
23 | "mongoose": "^5.11.15",
24 | "passport": "^0.4.1",
25 | "passport-github2": "^0.1.12",
26 | "passport-jwt": "^4.0.0",
27 | "passport-local": "^1.0.0",
28 | "pino": "^6.11.2",
29 | "pino-pretty": "^4.7.1"
30 | },
31 | "devDependencies": {
32 | "eslint": "^7.22.0",
33 | "eslint-config-airbnb": "^18.0.0",
34 | "eslint-config-prettier": "^8.1.0",
35 | "eslint-plugin-import": "^2.18.2",
36 | "eslint-plugin-prettier": "^3.3.1",
37 | "nodemon": "^2.0.7",
38 | "prettier": "^2.2.1"
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/playground/public/stylesheets/main.css:
--------------------------------------------------------------------------------
1 | #signup .divider-text {
2 | position: relative;
3 | text-align: center;
4 | margin-top: 15px;
5 | margin-bottom: 15px;
6 | }
7 | #signup .divider-text span {
8 | padding: 7px;
9 | font-size: 12px;
10 | position: relative;
11 | z-index: 2;
12 | }
13 | #signup .divider-text:after {
14 | content: '';
15 | position: absolute;
16 | width: 100%;
17 | border-bottom: 1px solid #ddd;
18 | top: 55%;
19 | left: 0;
20 | z-index: 1;
21 | }
22 |
23 | #signup .btn-github {
24 | color: #fff;
25 | background-color: #444;
26 | border-color: rgba(0, 0, 0, 0.2);
27 | }
28 |
29 | .container {
30 | margin-top: 70px;
31 | }
32 |
--------------------------------------------------------------------------------
/playground/server/app.js:
--------------------------------------------------------------------------------
1 | const cookieParser = require('cookie-parser');
2 | const express = require('express');
3 | const httpErrors = require('http-errors');
4 | const path = require('path');
5 |
6 | // We are using cookie based sessions
7 | // http://expressjs.com/en/resources/middleware/cookie-session.html
8 | const session = require('cookie-session');
9 |
10 | // This is the root file of the routing structure
11 | const indexRouter = require('./routes/index');
12 | const setupPassport = require('./lib/passport');
13 |
14 | // This is a simple helper that avoids 404 errors when
15 | // the browser tried to look for a favicon file
16 | function ignoreFavicon(req, res, next) {
17 | if (req.originalUrl.includes('favicon.ico')) {
18 | return res.status(204).end();
19 | }
20 | return next();
21 | }
22 |
23 | module.exports = (config) => {
24 | const app = express();
25 | const passport = setupPassport(config);
26 | // Just in case we need to log something later
27 | // const { logger } = config;
28 |
29 | // This is used to show the database connection status on the website
30 | app.locals.databaseStatus = config.database.status;
31 |
32 | // Set up views
33 | app.set('views', path.join(__dirname, 'views'));
34 | // view engine setup
35 | app.set('view engine', 'ejs');
36 |
37 | // Serving static assets like styles or images
38 | // Make sure to do this before initializing session management
39 | // to avoid overhead when just serving images
40 | app.use(express.static(path.join(__dirname, '../public')));
41 |
42 | // Initialize session management with cookie-session
43 | app.use(
44 | session({
45 | name: 'session',
46 | keys: [
47 | 'a set',
48 | 'of keys',
49 | 'used',
50 | 'to encrypt',
51 | 'the session',
52 | 'change in',
53 | 'production',
54 | ],
55 | resave: false,
56 | saveUninitialized: true,
57 | sameSite: 'lax',
58 | maxAge: null,
59 | })
60 | );
61 |
62 | // See express body parsers for more information
63 | app.use(express.json());
64 | app.use(express.urlencoded({ extended: false }));
65 | app.use(cookieParser());
66 |
67 | app.use(passport.initialize());
68 | app.use(passport.session());
69 |
70 | /**
71 | * @todo: Implement a middleware that restores the user from the database if `userId` is present on the session
72 | */
73 | app.use(async (req, res, next) => {
74 | req.sessionOptions.maxAge =
75 | req.session.rememberme || req.sessionOptions.maxAge;
76 | res.locals.user = req.user;
77 | return next();
78 | });
79 |
80 | // This sets up 'flash messaging'
81 | // With that, we can store messages to the user in the session
82 | // and these messages will then be shown on the webpage and
83 | // deleted from the session once displayed.
84 | // Look into `/server/views/partials/messages.ejs`to see how this works.
85 | app.use(async (req, res, next) => {
86 | // Set up flash messaging
87 | if (!req.session.messages) {
88 | req.session.messages = [];
89 | }
90 | res.locals.messages = req.session.messages;
91 | return next();
92 | });
93 |
94 | // Note that we are calling the index router as a function
95 | app.use('/', indexRouter({ config }));
96 |
97 | // Avoid 404 errors because of a missing favicon
98 | app.use(ignoreFavicon);
99 |
100 | // catch 404 and forward to error handler
101 | app.use((req, res, next) => {
102 | next(httpErrors(404));
103 | });
104 |
105 | // error handler
106 | app.use((err, req, res) => {
107 | // set locals, only providing error in development
108 | res.locals.message = err.message;
109 | res.locals.error = req.app.get('env') === 'development' ? err : {};
110 |
111 | // render the error page
112 | res.status(err.status || 500);
113 | res.render('error');
114 | });
115 |
116 | return app;
117 | };
118 |
--------------------------------------------------------------------------------
/playground/server/bin/start.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | /**
4 | * Module dependencies.
5 | */
6 | const mongoose = require('mongoose');
7 | const http = require('http');
8 | const config = require('../config');
9 |
10 | const { logger } = config;
11 |
12 | const app = require('../app')(config);
13 | /**
14 | * Normalize a port into a number, string, or false.
15 | */
16 |
17 | function normalizePort(val) {
18 | const port = parseInt(val, 10);
19 |
20 | if (Number.isNaN(port)) {
21 | // named pipe
22 | return val;
23 | }
24 |
25 | if (port >= 0) {
26 | // port number
27 | return port;
28 | }
29 |
30 | return false;
31 | }
32 |
33 | /**
34 | * Get port from environment and store in Express.
35 | */
36 |
37 | const port = normalizePort(process.env.PORT || '3000');
38 |
39 | app.set('port', port);
40 |
41 | /**
42 | * Create HTTP server.
43 | */
44 |
45 | const server = http.createServer(app);
46 |
47 | /**
48 | * Connect to mongodb and start the webserver listening on provided port, on all network interfaces.
49 | */
50 |
51 | mongoose
52 | .connect(config.database.dsn, {
53 | useNewUrlParser: true,
54 | useUnifiedTopology: true,
55 | useCreateIndex: true,
56 | })
57 | .then(() => {
58 | config.database.status.connected = true;
59 | logger.info('Connected to MongoDB');
60 | server.listen(port);
61 | })
62 | .catch((error) => {
63 | config.database.status.error = error;
64 | logger.fatal(error);
65 | server.listen(port);
66 | });
67 |
68 | /**
69 | * Event listener for HTTP server "error" event.
70 | */
71 | /* eslint no-console: 0 */
72 | server.on('error', (error) => {
73 | if (error.syscall !== 'listen') {
74 | throw error;
75 | }
76 |
77 | const bind = typeof port === 'string' ? `Pipe ${port}` : `Port ${port}`;
78 |
79 | // handle specific listen errors with friendly messages
80 | switch (error.code) {
81 | case 'EACCES':
82 | logger.fatal(`${bind} requires elevated privileges`);
83 | process.exit(1);
84 | break;
85 | case 'EADDRINUSE':
86 | logger.fatal(`${bind} is already in use`);
87 | process.exit(1);
88 | break;
89 | default:
90 | throw error;
91 | }
92 | });
93 |
94 | /**
95 | * Event listener for HTTP server "listening" event.
96 | */
97 |
98 | server.on('listening', () => {
99 | const addr = server.address();
100 | const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;
101 | logger.info(`Listening on ${bind}`);
102 | });
103 |
--------------------------------------------------------------------------------
/playground/server/config/index.js:
--------------------------------------------------------------------------------
1 | const logger = require('pino')({ prettyPrint: true });
2 | require('dotenv').config();
3 |
4 | module.exports = {
5 | database: {
6 | dsn: 'mongodb://localhost:37017/linkedin-node-authentication',
7 | status: {
8 | connected: false,
9 | error: false,
10 | },
11 | },
12 | JWTSECRET: process.env.JWTSECRET,
13 | GITHUB_CLIENT_ID: process.env.GITHUB_CLIENT_ID,
14 | GITHUB_CLIENT_SECRET: process.env.GITHUB_CLIENT_SECRET,
15 | logger,
16 | };
17 |
--------------------------------------------------------------------------------
/playground/server/lib/passport/index.js:
--------------------------------------------------------------------------------
1 | const passport = require('passport');
2 | const passportJWT = require('passport-jwt');
3 | const LocalStrategy = require('passport-local').Strategy;
4 | const GitHubStrategy = require('passport-github2').Strategy;
5 |
6 | /* eslint-disable no-unused-vars */
7 | const UserService = require('../../services/UserService');
8 |
9 | const JWTStrategy = passportJWT.Strategy;
10 | const ExtractJWT = passportJWT.ExtractJwt;
11 |
12 | /**
13 | * This module sets up and configures passport
14 | * @param {*} config
15 | */
16 | module.exports = (config) => {
17 | passport.use(
18 | new LocalStrategy(
19 | {
20 | passReqToCallback: true,
21 | },
22 | async (req, username, password, done) => {
23 | try {
24 | const user = await UserService.findByUsername(req.body.username);
25 | if (!user) {
26 | req.session.messages.push({
27 | text: 'Invalid username or password!',
28 | type: 'danger',
29 | });
30 | return done(null, false);
31 | }
32 |
33 | if (user && !user.verified) {
34 | req.session.messages.push({
35 | text: 'Please verify your email address!',
36 | type: 'danger',
37 | });
38 | return done(null, false);
39 | }
40 | const isValid = await user.comparePassword(req.body.password);
41 | if (!isValid) {
42 | req.session.messages.push({
43 | text: 'Invalid username or password!',
44 | type: 'danger',
45 | });
46 | return done(null, false);
47 | }
48 | return done(null, user);
49 | } catch (err) {
50 | return done(err);
51 | }
52 | }
53 | )
54 | );
55 |
56 | passport.use(
57 | new JWTStrategy(
58 | {
59 | jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
60 | secretOrKey: config.JWTSECRET,
61 | },
62 | async (jwtPayload, done) => {
63 | try {
64 | const user = await UserService.findById(jwtPayload.userId);
65 | return done(null, user);
66 | } catch (err) {
67 | return done(err);
68 | }
69 | }
70 | )
71 | );
72 |
73 | passport.use(
74 | new GitHubStrategy(
75 | {
76 | clientID: config.GITHUB_CLIENT_ID,
77 | clientSecret: config.GITHUB_CLIENT_SECRET,
78 | scope: ['user:email'],
79 | callbackURL: 'http://localhost:3000/auth/github/callback',
80 | passReqToCallback: true,
81 | },
82 | async (req, accessToken, refreshToken, profile, done) => {
83 | try {
84 | req.session.tempOAuthProfile = null;
85 | const user = await UserService.findByOAuthProfile(
86 | profile.provider,
87 | profile.id
88 | );
89 | if (!user) {
90 | req.session.tempOAuthProfile = {
91 | provider: profile.provider,
92 | profileId: profile.id,
93 | };
94 | }
95 | return done(null, user);
96 | } catch (err) {
97 | return done(err);
98 | }
99 | }
100 | )
101 | );
102 |
103 | passport.serializeUser((user, done) => {
104 | done(null, user.id);
105 | });
106 |
107 | passport.deserializeUser(async (id, done) => {
108 | try {
109 | const user = await UserService.findById(id);
110 | return done(null, user);
111 | } catch (err) {
112 | return done(err);
113 | }
114 | });
115 | return passport;
116 | };
117 |
--------------------------------------------------------------------------------
/playground/server/middlewares/validation.js:
--------------------------------------------------------------------------------
1 | const { body, validationResult } = require('express-validator');
2 |
3 | module.exports.validatePassword = body('password')
4 | .isLength({ min: 8 })
5 | .trim()
6 | .withMessage('The password has to be at least 8 characters long.');
7 |
8 | module.exports.validatePasswordMatch = body('password')
9 | .custom((value, { req }) => {
10 | if (value !== req.body.confirmPassword) {
11 | return false;
12 | }
13 | return true;
14 | })
15 | .withMessage("Passwords don't match");
16 |
17 | module.exports.validateEmail = body('email')
18 | .isEmail()
19 | .normalizeEmail()
20 | .withMessage('Please enter a valid email address.');
21 |
22 | module.exports.validateUsername = body('username')
23 | .isLength({ min: 6 })
24 | .trim()
25 | .withMessage('The username has to be at least 6 characters long.');
26 |
27 | module.exports.validationResult = validationResult;
28 |
--------------------------------------------------------------------------------
/playground/server/models/ResetTokenModel.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 | const crypto = require('crypto');
3 |
4 | const resetTokenSchema = mongoose.Schema(
5 | {
6 | userId: {
7 | type: mongoose.Schema.Types.ObjectId,
8 | required: true,
9 | index: true,
10 | },
11 | token: {
12 | type: String,
13 | required: true,
14 | index: true,
15 | unique: true,
16 | default: () => crypto.randomBytes(20).toString('hex'),
17 | },
18 | },
19 | {
20 | timestamps: true,
21 | }
22 | );
23 |
24 | resetTokenSchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 });
25 | module.exports = mongoose.model('ResetToken', resetTokenSchema);
26 |
--------------------------------------------------------------------------------
/playground/server/models/TodolistItemModel.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | const todolistItemModel = mongoose.Schema(
4 | {
5 | userId: {
6 | type: mongoose.Schema.Types.ObjectId,
7 | required: true,
8 | index: true,
9 | },
10 | description: {
11 | type: String,
12 | required: true,
13 | trim: true,
14 | minlength: 2,
15 | },
16 | completed: {
17 | type: Boolean,
18 | default: false,
19 | },
20 | },
21 | {
22 | timestamps: true,
23 | }
24 | );
25 |
26 | module.exports = mongoose.model('TodolistItem', todolistItemModel);
27 |
--------------------------------------------------------------------------------
/playground/server/models/UserModel.js:
--------------------------------------------------------------------------------
1 | // First we have to bring in mongoose
2 | const mongoose = require('mongoose');
3 | const crypto = require('crypto');
4 | const bcrypt = require('bcrypt');
5 |
6 | // Here we define the schema for our users
7 | const userSchema = mongoose.Schema(
8 | {
9 | username: {
10 | type: String,
11 | required: true,
12 | trim: true, // trim preceding spaces and trailing whitespaces
13 | index: { unique: true }, // the username should be unique
14 | minlength: 6,
15 | },
16 | email: {
17 | type: String,
18 | required: true,
19 | trim: true, // trim preceding spaces and trailing whitespaces
20 | lowercase: true, // normalize email addresses to lowercase
21 | index: { unique: true }, // the email address needs to be unique
22 | },
23 | password: {
24 | type: String,
25 | required: true,
26 | minlength: 8, // A password needs to be at least 8 characters long
27 | trim: true,
28 | },
29 | verified: {
30 | type: Boolean,
31 | default: false,
32 | },
33 | verificationToken: {
34 | type: String,
35 | required: true,
36 | index: true,
37 | unique: true,
38 | default: () => crypto.randomBytes(20).toString('hex'),
39 | },
40 | oauthprofiles: [
41 | {
42 | provider: { type: String },
43 | profileId: { type: String },
44 | },
45 | ],
46 | },
47 | {
48 | timestamps: true,
49 | }
50 | );
51 |
52 | userSchema.index({
53 | 'oauthprofiles.provider': 1,
54 | 'oauthprofiles.profileId': 1,
55 | });
56 |
57 | async function generateHash(password) {
58 | return bcrypt.hash(password, 12);
59 | }
60 |
61 | userSchema.pre('save', function preSave(next) {
62 | const user = this;
63 | if (user.isModified('password')) {
64 | return generateHash(user.password)
65 | .then((hash) => {
66 | user.password = hash;
67 | return next();
68 | })
69 | .catch((error) => {
70 | return next(error);
71 | });
72 | }
73 | return next();
74 | });
75 |
76 | userSchema.methods.comparePassword = async function comparePassword(
77 | candidatePassword
78 | ) {
79 | return bcrypt.compare(candidatePassword, this.password);
80 | };
81 |
82 | // We export the model `User` from the `UserSchema`
83 | module.exports = mongoose.model('User', userSchema);
84 |
--------------------------------------------------------------------------------
/playground/server/routes/api/index.js:
--------------------------------------------------------------------------------
1 | const { Router } = require('express');
2 | const jwt = require('jsonwebtoken');
3 | const passport = require('passport');
4 |
5 | const router = Router();
6 | const todolistRouter = require('./todolist');
7 |
8 | module.exports = (params) => {
9 | const { config } = params;
10 | router.post(
11 | '/login',
12 | passport.authenticate('local', {
13 | session: false,
14 | }),
15 | async (req, res, next) => {
16 | try {
17 | const token = jwt.sign(
18 | {
19 | userId: req.user.id,
20 | },
21 | config.JWTSECRET,
22 | { expiresIn: '24h' }
23 | );
24 | return res.json({ jwt: token });
25 | } catch (err) {
26 | return next(err);
27 | }
28 | }
29 | );
30 |
31 | router.get(
32 | '/whoami',
33 | passport.authenticate('jwt', { session: false }),
34 | (req, res) => {
35 | return res.json({
36 | username: req.user.username,
37 | });
38 | }
39 | );
40 |
41 | router.use(
42 | '/todolist',
43 | passport.authenticate('jwt', { session: false }),
44 | todolistRouter(params)
45 | );
46 |
47 | return router;
48 | };
49 |
--------------------------------------------------------------------------------
/playground/server/routes/api/todolist/index.js:
--------------------------------------------------------------------------------
1 | const { Router } = require('express');
2 | const TodolistService = require('../../../services/TodolistService');
3 |
4 | const router = Router();
5 |
6 | module.exports = () => {
7 | router.post('/', async (req, res, next) => {
8 | try {
9 | await TodolistService.addItem(req.user.id, req.body.description);
10 | return res.status(201).json({ status: 'created' });
11 | } catch (err) {
12 | return next(err);
13 | }
14 | });
15 |
16 | router.get('/', async (req, res, next) => {
17 | try {
18 | const items = await TodolistService.getList(req.user.id);
19 | return res.json({ items });
20 | } catch (err) {
21 | return next(err);
22 | }
23 | });
24 |
25 | router.put('/:itemId', async (req, res, next) => {
26 | try {
27 | const result = await TodolistService.updateItem(
28 | req.user.id,
29 | req.params.itemId,
30 | req.body
31 | );
32 | return res.json({ result });
33 | } catch (err) {
34 | return next(err);
35 | }
36 | });
37 |
38 | router.delete('/:itemId', async (req, res, next) => {
39 | try {
40 | const result = await TodolistService.deleteItem(
41 | req.user.id,
42 | req.params.itemId
43 | );
44 | return res.json({ result });
45 | } catch (err) {
46 | return next(err);
47 | }
48 | });
49 |
50 | return router;
51 | };
52 |
--------------------------------------------------------------------------------
/playground/server/routes/auth/github.js:
--------------------------------------------------------------------------------
1 | const { Router } = require('express');
2 | const passport = require('passport');
3 | const UserService = require('../../services/UserService');
4 | const validation = require('../../middlewares/validation');
5 |
6 | const router = Router();
7 |
8 | module.exports = () => {
9 | /**
10 | * GET route to initiate GitHub authentication flow
11 | * @todo: Implement
12 | */
13 | router.get('/', passport.authenticate('github'));
14 |
15 | router.get(
16 | '/callback',
17 | passport.authenticate('github', {
18 | failureRedirect: '/auth/github/complete',
19 | }),
20 | async (req, res, next) => {
21 | try {
22 | req.session.messages.push({
23 | text: 'You are logged in via GitHub now!',
24 | type: 'success',
25 | });
26 | return res.redirect(req.session.returnTo || '/');
27 | } catch (err) {
28 | return next();
29 | }
30 | }
31 | );
32 |
33 | router.get('/complete', async (req, res, next) => {
34 | try {
35 | if (!req.session.tempOAuthProfile) {
36 | req.session.messages.push({
37 | text: 'Login via GitHub has failed',
38 | type: 'danger',
39 | });
40 |
41 | return res.redirect('/auth/login');
42 | }
43 | if (req.user) {
44 | const user = await UserService.findById(req.user.id);
45 | if (!user.oauthprofiles) {
46 | user.oauthprofiles = [];
47 | }
48 | user.oauthprofiles.push(req.session.tempOAuthProfile);
49 | await user.save();
50 | req.session.messages.push({
51 | text: 'Your GitHub profile was sucessfully linked!',
52 | type: 'success',
53 | });
54 | return res.redirect(req.session.returnTo || '/');
55 | }
56 | return res.render('auth/complete', { page: 'registration' });
57 | } catch (err) {
58 | return next(err);
59 | }
60 | });
61 |
62 | router.post(
63 | '/complete',
64 | // Here we call middlewares to validate the user inputs
65 | validation.validateUsername,
66 | validation.validateEmail,
67 | async (req, res, next) => {
68 | try {
69 | // This block deals with processing the validation input
70 | const validationErrors = validation.validationResult(req);
71 | const errors = [];
72 | if (!validationErrors.isEmpty()) {
73 | validationErrors.errors.forEach((error) => {
74 | errors.push(error.param);
75 | req.session.messages.push({
76 | text: error.msg,
77 | type: 'danger',
78 | });
79 | });
80 | } else {
81 | const existingEmail = await UserService.findByEmail(req.body.email);
82 | const existingUsername = await UserService.findByUsername(
83 | req.body.username
84 | );
85 |
86 | if (existingEmail || existingUsername) {
87 | errors.push('email');
88 | errors.push('username');
89 | req.session.messages.push({
90 | text: 'The given email address or the username exist already!',
91 | type: 'danger',
92 | });
93 | }
94 | }
95 |
96 | // If there was an error, we will render the form again and display the errors
97 | // We also pass in the previous user input so the user does not have to enter everything again
98 | if (errors.length) {
99 | // Render the page again and show the errors
100 | return res.render('auth/complete', {
101 | page: 'registration',
102 | data: req.body,
103 | errors,
104 | });
105 | }
106 |
107 | /**
108 | * @todo: Provide a method in UserService that will create a new user
109 | */
110 | await UserService.createSocialUser(
111 | req.body.username,
112 | req.body.email,
113 | req.session.tempOAuthProfile
114 | );
115 | req.session.messages.push({
116 | text: 'Your account was created and linked with GitHub!',
117 | type: 'success',
118 | });
119 |
120 | return res.redirect('/auth/login');
121 | } catch (err) {
122 | return next(err);
123 | }
124 | }
125 | );
126 |
127 | return router;
128 | };
129 |
--------------------------------------------------------------------------------
/playground/server/routes/auth/index.js:
--------------------------------------------------------------------------------
1 | const { Router } = require('express');
2 |
3 | const registrationRouter = require('./registration');
4 | const loginRouter = require('./login');
5 | const verificationRouter = require('./verification');
6 | const passwordResetRouter = require('./resetpassword');
7 | const githubRouter = require('./github');
8 |
9 | const router = Router();
10 |
11 | module.exports = (params) => {
12 | router.use(registrationRouter(params));
13 | router.use(loginRouter(params));
14 | router.use(verificationRouter(params));
15 | router.use(passwordResetRouter(params));
16 | router.use('/github', githubRouter(params));
17 | return router;
18 | };
19 |
--------------------------------------------------------------------------------
/playground/server/routes/auth/login.js:
--------------------------------------------------------------------------------
1 | const { Router } = require('express');
2 | const passport = require('passport');
3 | // eslint-disable-next-line no-unused-vars
4 | const UserService = require('../../services/UserService');
5 |
6 | const router = Router();
7 |
8 | module.exports = () => {
9 | /**
10 | * GET route to display the login form
11 | */
12 | router.get('/login', (req, res) => {
13 | res.render('auth/login', { page: 'login' });
14 | });
15 |
16 | /**
17 | * POST route to process the login form or display it again along with an error message in case validation fails
18 | */
19 | router.post(
20 | '/login',
21 | passport.authenticate('local', {
22 | failureRedirect: '/auth/login',
23 | }),
24 | async (req, res, next) => {
25 | try {
26 | req.session.messages.push({
27 | text: 'You are logged in now!',
28 | type: 'success',
29 | });
30 | if (req.body.remember) {
31 | req.sessionOptions.maxAge = 24 * 60 * 60 * 1000 * 14;
32 | req.session.rememberme = req.sessionOptions.maxAge;
33 | } else {
34 | req.session.rememberme = null;
35 | }
36 | return res.redirect(req.session.returnTo || '/');
37 | } catch (err) {
38 | return next(err);
39 | }
40 | }
41 | );
42 |
43 | /**
44 | * GET route to log a user out
45 | * @todo: Implement
46 | */
47 | router.get('/logout', (req, res) => {
48 | req.logout();
49 | req.session.rememberme = null;
50 | req.session.messages.push({
51 | text: 'You are logged out now!',
52 | type: 'info',
53 | });
54 | return res.redirect('/');
55 | });
56 |
57 | return router;
58 | };
59 |
--------------------------------------------------------------------------------
/playground/server/routes/auth/registration.js:
--------------------------------------------------------------------------------
1 | const { Router } = require('express');
2 |
3 | // eslint-disable-next-line no-unused-vars
4 | const UserService = require('../../services/UserService');
5 |
6 | const validation = require('../../middlewares/validation');
7 |
8 | const router = Router();
9 |
10 | module.exports = () => {
11 | /**
12 | * GET route to display the registration form
13 | */
14 | router.get('/register', (req, res) => {
15 | res.render('auth/registration', { page: 'registration' });
16 | });
17 |
18 | /**
19 | * POST route to process the registration form or display
20 | * it again along with an error message in case validation fails
21 | */
22 | router.post(
23 | '/register',
24 | // Here we call middlewares to validate the user inputs
25 | validation.validateUsername,
26 | validation.validateEmail,
27 | validation.validatePassword,
28 | validation.validatePasswordMatch,
29 | async (req, res, next) => {
30 | try {
31 | // This block deals with processing the validation input
32 | const validationErrors = validation.validationResult(req);
33 | const errors = [];
34 | if (!validationErrors.isEmpty()) {
35 | validationErrors.errors.forEach((error) => {
36 | errors.push(error.param);
37 | req.session.messages.push({
38 | text: error.msg,
39 | type: 'danger',
40 | });
41 | });
42 | } else {
43 | const existingEmail = await UserService.findByEmail(req.body.email);
44 | const existingUsername = await UserService.findByUsername(
45 | req.body.username
46 | );
47 |
48 | if (existingEmail || existingUsername) {
49 | errors.push('email');
50 | errors.push('username');
51 | req.session.messages.push({
52 | text: 'The given email address or the username exist already!',
53 | type: 'danger',
54 | });
55 | }
56 | }
57 |
58 | // If there was an error, we will render the form again and display the errors
59 | // We also pass in the previous user input so the user does not have to enter everything again
60 | if (errors.length) {
61 | // Render the page again and show the errors
62 | return res.render('auth/registration', {
63 | page: 'registration',
64 | data: req.body,
65 | errors,
66 | });
67 | }
68 |
69 | /**
70 | * @todo: Provide a method in UserService that will create a new user
71 | */
72 | await UserService.createUser(
73 | req.body.username,
74 | req.body.email,
75 | req.body.password
76 | );
77 | req.session.messages.push({
78 | text: 'Your account was created!',
79 | type: 'success',
80 | });
81 |
82 | return res.redirect('/auth/login');
83 | } catch (err) {
84 | return next(err);
85 | }
86 | }
87 | );
88 |
89 | return router;
90 | };
91 |
--------------------------------------------------------------------------------
/playground/server/routes/auth/resetpassword.js:
--------------------------------------------------------------------------------
1 | const { Router } = require('express');
2 |
3 | // eslint-disable-next-line no-unused-vars
4 | const UserService = require('../../services/UserService');
5 | const validation = require('../../middlewares/validation');
6 |
7 | const router = Router();
8 |
9 | module.exports = () => {
10 | /**
11 | * GET route to display the login form
12 | */
13 | router.get('/resetpassword', (req, res) => {
14 | res.render('auth/resetpassword', { page: 'resetpassword' });
15 | });
16 |
17 | /**
18 | * POST route to create the password reset token
19 | */
20 | router.post(
21 | '/resetpassword',
22 | validation.validateEmail,
23 | async (req, res, next) => {
24 | try {
25 | const validationErrors = validation.validationResult(req);
26 | const errors = [];
27 | if (!validationErrors.isEmpty()) {
28 | validationErrors.errors.forEach((error) => {
29 | errors.push(error.param);
30 | req.session.messages.push({
31 | text: error.msg,
32 | type: 'danger',
33 | });
34 | });
35 | } else {
36 | /**
37 | * @todo: Find the user and create a reset token
38 | */
39 | const user = await UserService.findByEmail(req.body.email);
40 | if (user) {
41 | // eslint-disable-next-line no-unused-vars
42 | const resetToken = await UserService.createPasswordResetToken(
43 | user.id
44 | );
45 | }
46 | }
47 |
48 | if (errors.length) {
49 | // Render the page again and show the errors
50 | return res.render('auth/resetpassword', {
51 | page: 'resetpassword',
52 | data: req.body,
53 | errors,
54 | });
55 | }
56 |
57 | req.session.messages.push({
58 | text:
59 | 'If we found a matching user, you will receive a password reset link.',
60 | type: 'info',
61 | });
62 | /**
63 | * @todo: On success, redirect the user to some other page, like the login page
64 | */
65 | return res.redirect('/');
66 | } catch (err) {
67 | return next(err);
68 | }
69 | }
70 | );
71 |
72 | /**
73 | * GET route to verify the reset token and show the form to change the password
74 | */
75 | router.get('/resetpassword/:userId/:resetToken', async (req, res, next) => {
76 | try {
77 | /**
78 | * @todo: Validate the token and render the password change form if valid
79 | */
80 | const resetToken = await UserService.verifyPasswordResetToken(
81 | req.params.userId,
82 | req.params.resetToken
83 | );
84 | if (!resetToken) {
85 | req.session.messages.push({
86 | text: 'The provided token is invalid!',
87 | type: 'danger',
88 | });
89 | return res.redirect('/auth/resetpassword');
90 | }
91 |
92 | return res.render('auth/changepassword', {
93 | page: 'resetpassword',
94 | userId: req.params.userId,
95 | resetToken: req.params.resetToken,
96 | });
97 | } catch (err) {
98 | return next(err);
99 | }
100 | });
101 |
102 | router.post(
103 | '/resetpassword/:userId/:resetToken',
104 | validation.validatePassword,
105 | validation.validatePasswordMatch,
106 | async (req, res, next) => {
107 | try {
108 | /**
109 | * @todo: Validate the provided credentials
110 | */
111 | const resetToken = await UserService.verifyPasswordResetToken(
112 | req.params.userId,
113 | req.params.resetToken
114 | );
115 | if (!resetToken) {
116 | req.session.messages.push({
117 | text: 'The provided token is invalid!',
118 | type: 'danger',
119 | });
120 | return res.redirect('/auth/resetpassword');
121 | }
122 | const validationErrors = validation.validationResult(req);
123 | const errors = [];
124 | if (!validationErrors.isEmpty()) {
125 | validationErrors.errors.forEach((error) => {
126 | errors.push(error.param);
127 | req.session.messages.push({
128 | text: error.msg,
129 | type: 'danger',
130 | });
131 | });
132 | }
133 |
134 | if (errors.length) {
135 | // Render the page again and show the errors
136 | return res.render('auth/changepassword', {
137 | page: 'resetpassword',
138 | data: req.body,
139 | userId: req.params.userId,
140 | resetToken: req.params.resetToken,
141 | errors,
142 | });
143 | }
144 |
145 | /**
146 | * @todo: Change password, remove token and redirect to login
147 | */
148 | await UserService.changePassword(req.params.userId, req.body.password);
149 | await UserService.deletePasswordResetToken(req.params.resetToken);
150 | req.session.messages.push({
151 | text: 'Your password was successfully changed!',
152 | type: 'success',
153 | });
154 | return res.redirect('/auth/login');
155 | } catch (err) {
156 | return next(err);
157 | }
158 | }
159 | );
160 |
161 | return router;
162 | };
163 |
--------------------------------------------------------------------------------
/playground/server/routes/auth/verification.js:
--------------------------------------------------------------------------------
1 | const { Router } = require('express');
2 |
3 | // eslint-disable-next-line no-unused-vars
4 | const UserService = require('../../services/UserService');
5 |
6 | const router = Router();
7 |
8 | module.exports = () => {
9 | /**
10 | * GET route that verifies a user by their token
11 | */
12 | router.get('/verify/:userId/:token', async (req, res, next) => {
13 | try {
14 | /**
15 | * @todo: Validate verification credentials and verify if valid
16 | */
17 | const user = await UserService.findById(req.params.userId);
18 | if (!user || user.verificationToken !== req.params.token) {
19 | req.session.messages.push({
20 | text: 'Invalid credentials provided!',
21 | type: 'danger',
22 | });
23 | } else {
24 | user.verified = true;
25 | await user.save();
26 | req.session.messages.push({
27 | text: 'You have been verified!',
28 | type: 'success',
29 | });
30 | }
31 | return res.redirect('/');
32 | } catch (err) {
33 | return next(err);
34 | }
35 | });
36 |
37 | return router;
38 | };
39 |
--------------------------------------------------------------------------------
/playground/server/routes/index.js:
--------------------------------------------------------------------------------
1 | const { Router } = require('express');
2 |
3 | const { ensureLoggedIn } = require('connect-ensure-login');
4 |
5 | const cors = require('cors');
6 | const authRouter = require('./auth');
7 | const apiRouter = require('./api');
8 | const playgroundRouter = require('./playground');
9 |
10 | const router = Router();
11 |
12 | // This module returns a function and this allows you to pass parameters down the routing chain
13 | module.exports = (params) => {
14 | /* GET index page. */
15 | router.get('/', (req, res) => {
16 | res.render('index', { page: 'index' });
17 | });
18 |
19 | router.get('/myaccount', ensureLoggedIn('/auth/login'), (req, res) => {
20 | res.render('myaccount', { page: 'myaccount' });
21 | });
22 |
23 | // This delegates everything under /auth to the respective routing module.
24 | // We also pass down the params.
25 | router.use('/auth', authRouter(params));
26 | router.use('/playground', playgroundRouter(params));
27 |
28 | // Note the CORS middleware here - this is needed as we are calling the APi from a different URL/port
29 | router.use('/api', cors(), apiRouter(params));
30 |
31 | // Always return the router from such a module.
32 | return router;
33 | };
34 |
--------------------------------------------------------------------------------
/playground/server/routes/playground/index.js:
--------------------------------------------------------------------------------
1 | const { Router } = require('express');
2 | const UserService = require('../../services/UserService');
3 |
4 | const router = Router();
5 |
6 | // This module returns a function and this allows you to pass parameters down the routing chain
7 |
8 | // eslint-disable-next-line no-unused-vars
9 | module.exports = (params) => {
10 | /* GET index page. */
11 | router.get('/userlist', async (req, res, next) => {
12 | try {
13 | const users = await UserService.getList();
14 | const userList = await Promise.all(
15 | users.map(async (user) => {
16 | const userJson = user.toJSON();
17 | const resetToken = await UserService.getResetToken(user.id);
18 | if (resetToken && resetToken.token) {
19 | userJson.resetToken = resetToken.token;
20 | }
21 | return userJson;
22 | })
23 | );
24 |
25 | return res.render('playground/userlist', {
26 | page: 'userlist',
27 | users: userList,
28 | });
29 | } catch (err) {
30 | return next(err);
31 | }
32 | });
33 |
34 | router.get('/userlist/delete/:id', async (req, res, next) => {
35 | try {
36 | await UserService.deleteUser(req.params.id);
37 |
38 | req.session.messages.push({
39 | text: 'The user was deleted',
40 | type: 'info',
41 | });
42 |
43 | return res.redirect('/playground/userlist');
44 | } catch (err) {
45 | return next(err);
46 | }
47 | });
48 |
49 | router.get(
50 | '/userlist/unlinksocial/:provider/:profileId',
51 | async (req, res, next) => {
52 | try {
53 | const user = await UserService.findByOAuthProfile(
54 | req.params.provider,
55 | req.params.profileId
56 | );
57 | user.oauthprofiles = [];
58 | await user.save();
59 | req.session.messages.push({
60 | text: 'GitHub was unlinked',
61 | type: 'info',
62 | });
63 |
64 | return res.redirect('/playground/userlist');
65 | } catch (err) {
66 | return next(err);
67 | }
68 | }
69 | );
70 |
71 | // Always return the router from such a module.
72 | return router;
73 | };
74 |
--------------------------------------------------------------------------------
/playground/server/services/TodolistService.js:
--------------------------------------------------------------------------------
1 | const TodolistitemModel = require('../models/TodolistItemModel');
2 |
3 | /**
4 | * Provides CRUD methods for the todo list
5 | */
6 | class TodolistService {
7 | /**
8 | * Adds a todolist item
9 | * @param {*} userId
10 | * @param {*} text
11 | * @returns save result
12 | */
13 | static async addItem(userId, description) {
14 | const item = new TodolistitemModel();
15 | item.description = description;
16 | item.userId = userId;
17 | return item.save();
18 | }
19 |
20 | /**
21 | * Updates an item
22 | * @param {*} itemId
23 | * @param {*} data
24 | * @returns update result
25 | */
26 | static async updateItem(userId, id, data) {
27 | const item = await TodolistitemModel.findOne({ _id: id, userId }).exec();
28 | if (!item) throw new Error('Could not find item!');
29 | item.completed = data.completed ? data.completed : item.completed;
30 | item.description = data.description ? data.description : item.description;
31 | return item.save();
32 | }
33 |
34 | static async deleteItem(userId, id) {
35 | return TodolistitemModel.deleteOne({ _id: id, userId }).exec();
36 | }
37 |
38 | /**
39 | * Returns a list of items for a given user
40 | * @param {*} userId
41 | * @returns item list
42 | */
43 | static async getList(userId) {
44 | return TodolistitemModel.find({ userId }).sort({ createdAt: -1 }).exec();
45 | }
46 | }
47 |
48 | module.exports = TodolistService;
49 |
--------------------------------------------------------------------------------
/playground/server/services/UserService.js:
--------------------------------------------------------------------------------
1 | const crypto = require('crypto');
2 |
3 | const UserModel = require('../models/UserModel');
4 | const PasswordResetModel = require('../models/ResetTokenModel');
5 | const ResetTokenModel = require('../models/ResetTokenModel');
6 |
7 | /**
8 | * Provides methods to fetch and manipulate users and password tokens
9 | */
10 | class UserService {
11 | /**
12 | * Finds and returns a user by email address
13 | *
14 | * @param {*} email
15 | * @returns database result
16 | */
17 | static async findByEmail(email) {
18 | // throw new Error('Not implemented');
19 | return UserModel.findOne({ email }).exec();
20 | }
21 |
22 | /**
23 | * Finds and returns a user by username
24 | *
25 | * @param {*} username
26 | * @returns database result
27 | */
28 | static async findByUsername(username) {
29 | // throw new Error('Not implemented');
30 | return UserModel.findOne({ username }).exec();
31 | }
32 |
33 | /**
34 | * Creates a new user
35 | *
36 | * @param {*} username
37 | * @param {*} email
38 | * @param {*} password
39 | * @returns save result
40 | */
41 | static async createUser(username, email, password) {
42 | // throw new Error('Not implemented');
43 | const user = new UserModel();
44 | user.email = email;
45 | user.password = password;
46 | user.username = username;
47 | const savedUser = await user.save();
48 | return savedUser;
49 | }
50 |
51 | static async createSocialUser(username, email, oauthProfile) {
52 | const user = new UserModel();
53 | user.email = email;
54 | user.oauthprofiles = [oauthProfile];
55 | user.password = crypto.randomBytes(10).toString('hex');
56 | user.username = username;
57 | const savedUser = await user.save();
58 | return savedUser;
59 | }
60 |
61 | /**
62 | * Creates a new password reset token
63 | *
64 | * @param {*} userId
65 | * @returns the created token
66 | */
67 | static async createPasswordResetToken(userId) {
68 | // throw new Error('Not implemented');
69 | const passwordReset = new PasswordResetModel();
70 | passwordReset.userId = userId;
71 | const savedToken = await passwordReset.save();
72 | return savedToken.token;
73 | }
74 |
75 | /**
76 | *
77 | * @param {*} userId
78 | * @param {*} token
79 | * @returns the token object if found
80 | */
81 | static async verifyPasswordResetToken(userId, token) {
82 | // throw new Error('Not implemented');
83 | return PasswordResetModel.findOne({
84 | token,
85 | userId,
86 | }).exec();
87 | }
88 |
89 | /**
90 | * Deletes a password reset token
91 | * @param {*} token
92 | * @returns
93 | */
94 | static async deletePasswordResetToken(token) {
95 | // throw new Error('Not implemented');
96 | return PasswordResetModel.findOneAndDelete({
97 | token,
98 | }).exec();
99 | }
100 |
101 | /**
102 | * Changes a user's password
103 | * @param {*} userId
104 | * @param {*} password
105 | */
106 | static async changePassword(userId, password) {
107 | // throw new Error('Not implemented');
108 | const user = await UserModel.findById(userId);
109 | if (!user) {
110 | throw new Error('User not found');
111 | }
112 | user.password = password;
113 | return user.save();
114 | }
115 |
116 | // Helpers
117 |
118 | /**
119 | * Finds a user by id
120 | * @param {*} id
121 | * @returns a user
122 | */
123 | static async findById(id) {
124 | return UserModel.findById(id).exec();
125 | }
126 |
127 | static async findByOAuthProfile(provider, profileId) {
128 | return UserModel.findOne({
129 | oauthprofiles: { $elemMatch: { provider, profileId } },
130 | }).exec();
131 | }
132 |
133 | /**
134 | * returns the password reset token for a user
135 | * @param {*} id
136 | * @returns a user
137 | */
138 | static async getResetToken(userId) {
139 | return ResetTokenModel.findOne({ userId }).exec();
140 | }
141 |
142 | /**
143 | * Get all users
144 | *
145 | * @returns a list of users
146 | */
147 | static async getList() {
148 | return UserModel.find().sort({ createdAt: -1 }).exec();
149 | }
150 |
151 | /**
152 | * Deletes a user
153 | *
154 | * @returns result
155 | */
156 | static async deleteUser(id) {
157 | return UserModel.findByIdAndDelete(id);
158 | }
159 | }
160 |
161 | module.exports = UserService;
162 |
--------------------------------------------------------------------------------
/playground/server/views/auth/changepassword.ejs:
--------------------------------------------------------------------------------
1 | <%- include('../partials/header'); -%>
2 | Please enter your new password using the form below! Please use your credentials to log in Please create an account using the form below! Please enter your email address.Change password
8 | Please complete your profile
8 |
9 |
33 | Login
9 | Registration
8 | Reset password
9 |
<%= error.stack %>4 | -------------------------------------------------------------------------------- /playground/server/views/index.ejs: -------------------------------------------------------------------------------- 1 | <%- include('./partials/header'); -%> 2 |
This is just a dump of the user object
10 |
11 | <%=user%>
12 |
13 |
14 | <%if(!user.githubId){%>
15 |